1: /* $Id: imach.c,v 1.237 2016/08/26 09:20:19 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.237 2016/08/26 09:20:19 brouard
5: Summary: to valgrind
6:
7: Revision 1.236 2016/08/25 10:50:18 brouard
8: *** empty log message ***
9:
10: Revision 1.235 2016/08/25 06:59:23 brouard
11: *** empty log message ***
12:
13: Revision 1.234 2016/08/23 16:51:20 brouard
14: *** empty log message ***
15:
16: Revision 1.233 2016/08/23 07:40:50 brouard
17: Summary: not working
18:
19: Revision 1.232 2016/08/22 14:20:21 brouard
20: Summary: not working
21:
22: Revision 1.231 2016/08/22 07:17:15 brouard
23: Summary: not working
24:
25: Revision 1.230 2016/08/22 06:55:53 brouard
26: Summary: Not working
27:
28: Revision 1.229 2016/07/23 09:45:53 brouard
29: Summary: Completing for func too
30:
31: Revision 1.228 2016/07/22 17:45:30 brouard
32: Summary: Fixing some arrays, still debugging
33:
34: Revision 1.226 2016/07/12 18:42:34 brouard
35: Summary: temp
36:
37: Revision 1.225 2016/07/12 08:40:03 brouard
38: Summary: saving but not running
39:
40: Revision 1.224 2016/07/01 13:16:01 brouard
41: Summary: Fixes
42:
43: Revision 1.223 2016/02/19 09:23:35 brouard
44: Summary: temporary
45:
46: Revision 1.222 2016/02/17 08:14:50 brouard
47: Summary: Probably last 0.98 stable version 0.98r6
48:
49: Revision 1.221 2016/02/15 23:35:36 brouard
50: Summary: minor bug
51:
52: Revision 1.219 2016/02/15 00:48:12 brouard
53: *** empty log message ***
54:
55: Revision 1.218 2016/02/12 11:29:23 brouard
56: Summary: 0.99 Back projections
57:
58: Revision 1.217 2015/12/23 17:18:31 brouard
59: Summary: Experimental backcast
60:
61: Revision 1.216 2015/12/18 17:32:11 brouard
62: Summary: 0.98r4 Warning and status=-2
63:
64: Version 0.98r4 is now:
65: - displaying an error when status is -1, date of interview unknown and date of death known;
66: - permitting a status -2 when the vital status is unknown at a known date of right truncation.
67: Older changes concerning s=-2, dating from 2005 have been supersed.
68:
69: Revision 1.215 2015/12/16 08:52:24 brouard
70: Summary: 0.98r4 working
71:
72: Revision 1.214 2015/12/16 06:57:54 brouard
73: Summary: temporary not working
74:
75: Revision 1.213 2015/12/11 18:22:17 brouard
76: Summary: 0.98r4
77:
78: Revision 1.212 2015/11/21 12:47:24 brouard
79: Summary: minor typo
80:
81: Revision 1.211 2015/11/21 12:41:11 brouard
82: Summary: 0.98r3 with some graph of projected cross-sectional
83:
84: Author: Nicolas Brouard
85:
86: Revision 1.210 2015/11/18 17:41:20 brouard
87: Summary: Start working on projected prevalences
88:
89: Revision 1.209 2015/11/17 22:12:03 brouard
90: Summary: Adding ftolpl parameter
91: Author: N Brouard
92:
93: We had difficulties to get smoothed confidence intervals. It was due
94: to the period prevalence which wasn't computed accurately. The inner
95: parameter ftolpl is now an outer parameter of the .imach parameter
96: file after estepm. If ftolpl is small 1.e-4 and estepm too,
97: computation are long.
98:
99: Revision 1.208 2015/11/17 14:31:57 brouard
100: Summary: temporary
101:
102: Revision 1.207 2015/10/27 17:36:57 brouard
103: *** empty log message ***
104:
105: Revision 1.206 2015/10/24 07:14:11 brouard
106: *** empty log message ***
107:
108: Revision 1.205 2015/10/23 15:50:53 brouard
109: Summary: 0.98r3 some clarification for graphs on likelihood contributions
110:
111: Revision 1.204 2015/10/01 16:20:26 brouard
112: Summary: Some new graphs of contribution to likelihood
113:
114: Revision 1.203 2015/09/30 17:45:14 brouard
115: Summary: looking at better estimation of the hessian
116:
117: Also a better criteria for convergence to the period prevalence And
118: therefore adding the number of years needed to converge. (The
119: prevalence in any alive state shold sum to one
120:
121: Revision 1.202 2015/09/22 19:45:16 brouard
122: Summary: Adding some overall graph on contribution to likelihood. Might change
123:
124: Revision 1.201 2015/09/15 17:34:58 brouard
125: Summary: 0.98r0
126:
127: - Some new graphs like suvival functions
128: - Some bugs fixed like model=1+age+V2.
129:
130: Revision 1.200 2015/09/09 16:53:55 brouard
131: Summary: Big bug thanks to Flavia
132:
133: Even model=1+age+V2. did not work anymore
134:
135: Revision 1.199 2015/09/07 14:09:23 brouard
136: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
137:
138: Revision 1.198 2015/09/03 07:14:39 brouard
139: Summary: 0.98q5 Flavia
140:
141: Revision 1.197 2015/09/01 18:24:39 brouard
142: *** empty log message ***
143:
144: Revision 1.196 2015/08/18 23:17:52 brouard
145: Summary: 0.98q5
146:
147: Revision 1.195 2015/08/18 16:28:39 brouard
148: Summary: Adding a hack for testing purpose
149:
150: After reading the title, ftol and model lines, if the comment line has
151: a q, starting with #q, the answer at the end of the run is quit. It
152: permits to run test files in batch with ctest. The former workaround was
153: $ echo q | imach foo.imach
154:
155: Revision 1.194 2015/08/18 13:32:00 brouard
156: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
157:
158: Revision 1.193 2015/08/04 07:17:42 brouard
159: Summary: 0.98q4
160:
161: Revision 1.192 2015/07/16 16:49:02 brouard
162: Summary: Fixing some outputs
163:
164: Revision 1.191 2015/07/14 10:00:33 brouard
165: Summary: Some fixes
166:
167: Revision 1.190 2015/05/05 08:51:13 brouard
168: Summary: Adding digits in output parameters (7 digits instead of 6)
169:
170: Fix 1+age+.
171:
172: Revision 1.189 2015/04/30 14:45:16 brouard
173: Summary: 0.98q2
174:
175: Revision 1.188 2015/04/30 08:27:53 brouard
176: *** empty log message ***
177:
178: Revision 1.187 2015/04/29 09:11:15 brouard
179: *** empty log message ***
180:
181: Revision 1.186 2015/04/23 12:01:52 brouard
182: Summary: V1*age is working now, version 0.98q1
183:
184: Some codes had been disabled in order to simplify and Vn*age was
185: working in the optimization phase, ie, giving correct MLE parameters,
186: but, as usual, outputs were not correct and program core dumped.
187:
188: Revision 1.185 2015/03/11 13:26:42 brouard
189: Summary: Inclusion of compile and links command line for Intel Compiler
190:
191: Revision 1.184 2015/03/11 11:52:39 brouard
192: Summary: Back from Windows 8. Intel Compiler
193:
194: Revision 1.183 2015/03/10 20:34:32 brouard
195: Summary: 0.98q0, trying with directest, mnbrak fixed
196:
197: We use directest instead of original Powell test; probably no
198: incidence on the results, but better justifications;
199: We fixed Numerical Recipes mnbrak routine which was wrong and gave
200: wrong results.
201:
202: Revision 1.182 2015/02/12 08:19:57 brouard
203: Summary: Trying to keep directest which seems simpler and more general
204: Author: Nicolas Brouard
205:
206: Revision 1.181 2015/02/11 23:22:24 brouard
207: Summary: Comments on Powell added
208:
209: Author:
210:
211: Revision 1.180 2015/02/11 17:33:45 brouard
212: Summary: Finishing move from main to function (hpijx and prevalence_limit)
213:
214: Revision 1.179 2015/01/04 09:57:06 brouard
215: Summary: back to OS/X
216:
217: Revision 1.178 2015/01/04 09:35:48 brouard
218: *** empty log message ***
219:
220: Revision 1.177 2015/01/03 18:40:56 brouard
221: Summary: Still testing ilc32 on OSX
222:
223: Revision 1.176 2015/01/03 16:45:04 brouard
224: *** empty log message ***
225:
226: Revision 1.175 2015/01/03 16:33:42 brouard
227: *** empty log message ***
228:
229: Revision 1.174 2015/01/03 16:15:49 brouard
230: Summary: Still in cross-compilation
231:
232: Revision 1.173 2015/01/03 12:06:26 brouard
233: Summary: trying to detect cross-compilation
234:
235: Revision 1.172 2014/12/27 12:07:47 brouard
236: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
237:
238: Revision 1.171 2014/12/23 13:26:59 brouard
239: Summary: Back from Visual C
240:
241: Still problem with utsname.h on Windows
242:
243: Revision 1.170 2014/12/23 11:17:12 brouard
244: Summary: Cleaning some \%% back to %%
245:
246: The escape was mandatory for a specific compiler (which one?), but too many warnings.
247:
248: Revision 1.169 2014/12/22 23:08:31 brouard
249: Summary: 0.98p
250:
251: Outputs some informations on compiler used, OS etc. Testing on different platforms.
252:
253: Revision 1.168 2014/12/22 15:17:42 brouard
254: Summary: update
255:
256: Revision 1.167 2014/12/22 13:50:56 brouard
257: Summary: Testing uname and compiler version and if compiled 32 or 64
258:
259: Testing on Linux 64
260:
261: Revision 1.166 2014/12/22 11:40:47 brouard
262: *** empty log message ***
263:
264: Revision 1.165 2014/12/16 11:20:36 brouard
265: Summary: After compiling on Visual C
266:
267: * imach.c (Module): Merging 1.61 to 1.162
268:
269: Revision 1.164 2014/12/16 10:52:11 brouard
270: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
271:
272: * imach.c (Module): Merging 1.61 to 1.162
273:
274: Revision 1.163 2014/12/16 10:30:11 brouard
275: * imach.c (Module): Merging 1.61 to 1.162
276:
277: Revision 1.162 2014/09/25 11:43:39 brouard
278: Summary: temporary backup 0.99!
279:
280: Revision 1.1 2014/09/16 11:06:58 brouard
281: Summary: With some code (wrong) for nlopt
282:
283: Author:
284:
285: Revision 1.161 2014/09/15 20:41:41 brouard
286: Summary: Problem with macro SQR on Intel compiler
287:
288: Revision 1.160 2014/09/02 09:24:05 brouard
289: *** empty log message ***
290:
291: Revision 1.159 2014/09/01 10:34:10 brouard
292: Summary: WIN32
293: Author: Brouard
294:
295: Revision 1.158 2014/08/27 17:11:51 brouard
296: *** empty log message ***
297:
298: Revision 1.157 2014/08/27 16:26:55 brouard
299: Summary: Preparing windows Visual studio version
300: Author: Brouard
301:
302: In order to compile on Visual studio, time.h is now correct and time_t
303: and tm struct should be used. difftime should be used but sometimes I
304: just make the differences in raw time format (time(&now).
305: Trying to suppress #ifdef LINUX
306: Add xdg-open for __linux in order to open default browser.
307:
308: Revision 1.156 2014/08/25 20:10:10 brouard
309: *** empty log message ***
310:
311: Revision 1.155 2014/08/25 18:32:34 brouard
312: Summary: New compile, minor changes
313: Author: Brouard
314:
315: Revision 1.154 2014/06/20 17:32:08 brouard
316: Summary: Outputs now all graphs of convergence to period prevalence
317:
318: Revision 1.153 2014/06/20 16:45:46 brouard
319: Summary: If 3 live state, convergence to period prevalence on same graph
320: Author: Brouard
321:
322: Revision 1.152 2014/06/18 17:54:09 brouard
323: Summary: open browser, use gnuplot on same dir than imach if not found in the path
324:
325: Revision 1.151 2014/06/18 16:43:30 brouard
326: *** empty log message ***
327:
328: Revision 1.150 2014/06/18 16:42:35 brouard
329: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
330: Author: brouard
331:
332: Revision 1.149 2014/06/18 15:51:14 brouard
333: Summary: Some fixes in parameter files errors
334: Author: Nicolas Brouard
335:
336: Revision 1.148 2014/06/17 17:38:48 brouard
337: Summary: Nothing new
338: Author: Brouard
339:
340: Just a new packaging for OS/X version 0.98nS
341:
342: Revision 1.147 2014/06/16 10:33:11 brouard
343: *** empty log message ***
344:
345: Revision 1.146 2014/06/16 10:20:28 brouard
346: Summary: Merge
347: Author: Brouard
348:
349: Merge, before building revised version.
350:
351: Revision 1.145 2014/06/10 21:23:15 brouard
352: Summary: Debugging with valgrind
353: Author: Nicolas Brouard
354:
355: Lot of changes in order to output the results with some covariates
356: After the Edimburgh REVES conference 2014, it seems mandatory to
357: improve the code.
358: No more memory valgrind error but a lot has to be done in order to
359: continue the work of splitting the code into subroutines.
360: Also, decodemodel has been improved. Tricode is still not
361: optimal. nbcode should be improved. Documentation has been added in
362: the source code.
363:
364: Revision 1.143 2014/01/26 09:45:38 brouard
365: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
366:
367: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
368: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
369:
370: Revision 1.142 2014/01/26 03:57:36 brouard
371: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
372:
373: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
374:
375: Revision 1.141 2014/01/26 02:42:01 brouard
376: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
377:
378: Revision 1.140 2011/09/02 10:37:54 brouard
379: Summary: times.h is ok with mingw32 now.
380:
381: Revision 1.139 2010/06/14 07:50:17 brouard
382: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
383: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
384:
385: Revision 1.138 2010/04/30 18:19:40 brouard
386: *** empty log message ***
387:
388: Revision 1.137 2010/04/29 18:11:38 brouard
389: (Module): Checking covariates for more complex models
390: than V1+V2. A lot of change to be done. Unstable.
391:
392: Revision 1.136 2010/04/26 20:30:53 brouard
393: (Module): merging some libgsl code. Fixing computation
394: of likelione (using inter/intrapolation if mle = 0) in order to
395: get same likelihood as if mle=1.
396: Some cleaning of code and comments added.
397:
398: Revision 1.135 2009/10/29 15:33:14 brouard
399: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
400:
401: Revision 1.134 2009/10/29 13:18:53 brouard
402: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
403:
404: Revision 1.133 2009/07/06 10:21:25 brouard
405: just nforces
406:
407: Revision 1.132 2009/07/06 08:22:05 brouard
408: Many tings
409:
410: Revision 1.131 2009/06/20 16:22:47 brouard
411: Some dimensions resccaled
412:
413: Revision 1.130 2009/05/26 06:44:34 brouard
414: (Module): Max Covariate is now set to 20 instead of 8. A
415: lot of cleaning with variables initialized to 0. Trying to make
416: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
417:
418: Revision 1.129 2007/08/31 13:49:27 lievre
419: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
420:
421: Revision 1.128 2006/06/30 13:02:05 brouard
422: (Module): Clarifications on computing e.j
423:
424: Revision 1.127 2006/04/28 18:11:50 brouard
425: (Module): Yes the sum of survivors was wrong since
426: imach-114 because nhstepm was no more computed in the age
427: loop. Now we define nhstepma in the age loop.
428: (Module): In order to speed up (in case of numerous covariates) we
429: compute health expectancies (without variances) in a first step
430: and then all the health expectancies with variances or standard
431: deviation (needs data from the Hessian matrices) which slows the
432: computation.
433: In the future we should be able to stop the program is only health
434: expectancies and graph are needed without standard deviations.
435:
436: Revision 1.126 2006/04/28 17:23:28 brouard
437: (Module): Yes the sum of survivors was wrong since
438: imach-114 because nhstepm was no more computed in the age
439: loop. Now we define nhstepma in the age loop.
440: Version 0.98h
441:
442: Revision 1.125 2006/04/04 15:20:31 lievre
443: Errors in calculation of health expectancies. Age was not initialized.
444: Forecasting file added.
445:
446: Revision 1.124 2006/03/22 17:13:53 lievre
447: Parameters are printed with %lf instead of %f (more numbers after the comma).
448: The log-likelihood is printed in the log file
449:
450: Revision 1.123 2006/03/20 10:52:43 brouard
451: * imach.c (Module): <title> changed, corresponds to .htm file
452: name. <head> headers where missing.
453:
454: * imach.c (Module): Weights can have a decimal point as for
455: English (a comma might work with a correct LC_NUMERIC environment,
456: otherwise the weight is truncated).
457: Modification of warning when the covariates values are not 0 or
458: 1.
459: Version 0.98g
460:
461: Revision 1.122 2006/03/20 09:45:41 brouard
462: (Module): Weights can have a decimal point as for
463: English (a comma might work with a correct LC_NUMERIC environment,
464: otherwise the weight is truncated).
465: Modification of warning when the covariates values are not 0 or
466: 1.
467: Version 0.98g
468:
469: Revision 1.121 2006/03/16 17:45:01 lievre
470: * imach.c (Module): Comments concerning covariates added
471:
472: * imach.c (Module): refinements in the computation of lli if
473: status=-2 in order to have more reliable computation if stepm is
474: not 1 month. Version 0.98f
475:
476: Revision 1.120 2006/03/16 15:10:38 lievre
477: (Module): refinements in the computation of lli if
478: status=-2 in order to have more reliable computation if stepm is
479: not 1 month. Version 0.98f
480:
481: Revision 1.119 2006/03/15 17:42:26 brouard
482: (Module): Bug if status = -2, the loglikelihood was
483: computed as likelihood omitting the logarithm. Version O.98e
484:
485: Revision 1.118 2006/03/14 18:20:07 brouard
486: (Module): varevsij Comments added explaining the second
487: table of variances if popbased=1 .
488: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
489: (Module): Function pstamp added
490: (Module): Version 0.98d
491:
492: Revision 1.117 2006/03/14 17:16:22 brouard
493: (Module): varevsij Comments added explaining the second
494: table of variances if popbased=1 .
495: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
496: (Module): Function pstamp added
497: (Module): Version 0.98d
498:
499: Revision 1.116 2006/03/06 10:29:27 brouard
500: (Module): Variance-covariance wrong links and
501: varian-covariance of ej. is needed (Saito).
502:
503: Revision 1.115 2006/02/27 12:17:45 brouard
504: (Module): One freematrix added in mlikeli! 0.98c
505:
506: Revision 1.114 2006/02/26 12:57:58 brouard
507: (Module): Some improvements in processing parameter
508: filename with strsep.
509:
510: Revision 1.113 2006/02/24 14:20:24 brouard
511: (Module): Memory leaks checks with valgrind and:
512: datafile was not closed, some imatrix were not freed and on matrix
513: allocation too.
514:
515: Revision 1.112 2006/01/30 09:55:26 brouard
516: (Module): Back to gnuplot.exe instead of wgnuplot.exe
517:
518: Revision 1.111 2006/01/25 20:38:18 brouard
519: (Module): Lots of cleaning and bugs added (Gompertz)
520: (Module): Comments can be added in data file. Missing date values
521: can be a simple dot '.'.
522:
523: Revision 1.110 2006/01/25 00:51:50 brouard
524: (Module): Lots of cleaning and bugs added (Gompertz)
525:
526: Revision 1.109 2006/01/24 19:37:15 brouard
527: (Module): Comments (lines starting with a #) are allowed in data.
528:
529: Revision 1.108 2006/01/19 18:05:42 lievre
530: Gnuplot problem appeared...
531: To be fixed
532:
533: Revision 1.107 2006/01/19 16:20:37 brouard
534: Test existence of gnuplot in imach path
535:
536: Revision 1.106 2006/01/19 13:24:36 brouard
537: Some cleaning and links added in html output
538:
539: Revision 1.105 2006/01/05 20:23:19 lievre
540: *** empty log message ***
541:
542: Revision 1.104 2005/09/30 16:11:43 lievre
543: (Module): sump fixed, loop imx fixed, and simplifications.
544: (Module): If the status is missing at the last wave but we know
545: that the person is alive, then we can code his/her status as -2
546: (instead of missing=-1 in earlier versions) and his/her
547: contributions to the likelihood is 1 - Prob of dying from last
548: health status (= 1-p13= p11+p12 in the easiest case of somebody in
549: the healthy state at last known wave). Version is 0.98
550:
551: Revision 1.103 2005/09/30 15:54:49 lievre
552: (Module): sump fixed, loop imx fixed, and simplifications.
553:
554: Revision 1.102 2004/09/15 17:31:30 brouard
555: Add the possibility to read data file including tab characters.
556:
557: Revision 1.101 2004/09/15 10:38:38 brouard
558: Fix on curr_time
559:
560: Revision 1.100 2004/07/12 18:29:06 brouard
561: Add version for Mac OS X. Just define UNIX in Makefile
562:
563: Revision 1.99 2004/06/05 08:57:40 brouard
564: *** empty log message ***
565:
566: Revision 1.98 2004/05/16 15:05:56 brouard
567: New version 0.97 . First attempt to estimate force of mortality
568: directly from the data i.e. without the need of knowing the health
569: state at each age, but using a Gompertz model: log u =a + b*age .
570: This is the basic analysis of mortality and should be done before any
571: other analysis, in order to test if the mortality estimated from the
572: cross-longitudinal survey is different from the mortality estimated
573: from other sources like vital statistic data.
574:
575: The same imach parameter file can be used but the option for mle should be -3.
576:
577: Agnès, who wrote this part of the code, tried to keep most of the
578: former routines in order to include the new code within the former code.
579:
580: The output is very simple: only an estimate of the intercept and of
581: the slope with 95% confident intervals.
582:
583: Current limitations:
584: A) Even if you enter covariates, i.e. with the
585: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
586: B) There is no computation of Life Expectancy nor Life Table.
587:
588: Revision 1.97 2004/02/20 13:25:42 lievre
589: Version 0.96d. Population forecasting command line is (temporarily)
590: suppressed.
591:
592: Revision 1.96 2003/07/15 15:38:55 brouard
593: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
594: rewritten within the same printf. Workaround: many printfs.
595:
596: Revision 1.95 2003/07/08 07:54:34 brouard
597: * imach.c (Repository):
598: (Repository): Using imachwizard code to output a more meaningful covariance
599: matrix (cov(a12,c31) instead of numbers.
600:
601: Revision 1.94 2003/06/27 13:00:02 brouard
602: Just cleaning
603:
604: Revision 1.93 2003/06/25 16:33:55 brouard
605: (Module): On windows (cygwin) function asctime_r doesn't
606: exist so I changed back to asctime which exists.
607: (Module): Version 0.96b
608:
609: Revision 1.92 2003/06/25 16:30:45 brouard
610: (Module): On windows (cygwin) function asctime_r doesn't
611: exist so I changed back to asctime which exists.
612:
613: Revision 1.91 2003/06/25 15:30:29 brouard
614: * imach.c (Repository): Duplicated warning errors corrected.
615: (Repository): Elapsed time after each iteration is now output. It
616: helps to forecast when convergence will be reached. Elapsed time
617: is stamped in powell. We created a new html file for the graphs
618: concerning matrix of covariance. It has extension -cov.htm.
619:
620: Revision 1.90 2003/06/24 12:34:15 brouard
621: (Module): Some bugs corrected for windows. Also, when
622: mle=-1 a template is output in file "or"mypar.txt with the design
623: of the covariance matrix to be input.
624:
625: Revision 1.89 2003/06/24 12:30:52 brouard
626: (Module): Some bugs corrected for windows. Also, when
627: mle=-1 a template is output in file "or"mypar.txt with the design
628: of the covariance matrix to be input.
629:
630: Revision 1.88 2003/06/23 17:54:56 brouard
631: * 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.
632:
633: Revision 1.87 2003/06/18 12:26:01 brouard
634: Version 0.96
635:
636: Revision 1.86 2003/06/17 20:04:08 brouard
637: (Module): Change position of html and gnuplot routines and added
638: routine fileappend.
639:
640: Revision 1.85 2003/06/17 13:12:43 brouard
641: * imach.c (Repository): Check when date of death was earlier that
642: current date of interview. It may happen when the death was just
643: prior to the death. In this case, dh was negative and likelihood
644: was wrong (infinity). We still send an "Error" but patch by
645: assuming that the date of death was just one stepm after the
646: interview.
647: (Repository): Because some people have very long ID (first column)
648: we changed int to long in num[] and we added a new lvector for
649: memory allocation. But we also truncated to 8 characters (left
650: truncation)
651: (Repository): No more line truncation errors.
652:
653: Revision 1.84 2003/06/13 21:44:43 brouard
654: * imach.c (Repository): Replace "freqsummary" at a correct
655: place. It differs from routine "prevalence" which may be called
656: many times. Probs is memory consuming and must be used with
657: parcimony.
658: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
659:
660: Revision 1.83 2003/06/10 13:39:11 lievre
661: *** empty log message ***
662:
663: Revision 1.82 2003/06/05 15:57:20 brouard
664: Add log in imach.c and fullversion number is now printed.
665:
666: */
667: /*
668: Interpolated Markov Chain
669:
670: Short summary of the programme:
671:
672: This program computes Healthy Life Expectancies or State-specific
673: (if states aren't health statuses) Expectancies from
674: cross-longitudinal data. Cross-longitudinal data consist in:
675:
676: -1- a first survey ("cross") where individuals from different ages
677: are interviewed on their health status or degree of disability (in
678: the case of a health survey which is our main interest)
679:
680: -2- at least a second wave of interviews ("longitudinal") which
681: measure each change (if any) in individual health status. Health
682: expectancies are computed from the time spent in each health state
683: according to a model. More health states you consider, more time is
684: necessary to reach the Maximum Likelihood of the parameters involved
685: in the model. The simplest model is the multinomial logistic model
686: where pij is the probability to be observed in state j at the second
687: wave conditional to be observed in state i at the first
688: wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
689: etc , where 'age' is age and 'sex' is a covariate. If you want to
690: have a more complex model than "constant and age", you should modify
691: the program where the markup *Covariates have to be included here
692: again* invites you to do it. More covariates you add, slower the
693: convergence.
694:
695: The advantage of this computer programme, compared to a simple
696: multinomial logistic model, is clear when the delay between waves is not
697: identical for each individual. Also, if a individual missed an
698: intermediate interview, the information is lost, but taken into
699: account using an interpolation or extrapolation.
700:
701: hPijx is the probability to be observed in state i at age x+h
702: conditional to the observed state i at age x. The delay 'h' can be
703: split into an exact number (nh*stepm) of unobserved intermediate
704: states. This elementary transition (by month, quarter,
705: semester or year) is modelled as a multinomial logistic. The hPx
706: matrix is simply the matrix product of nh*stepm elementary matrices
707: and the contribution of each individual to the likelihood is simply
708: hPijx.
709:
710: Also this programme outputs the covariance matrix of the parameters but also
711: of the life expectancies. It also computes the period (stable) prevalence.
712:
713: Back prevalence and projections:
714:
715: - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
716: double agemaxpar, double ftolpl, int *ncvyearp, double
717: dateprev1,double dateprev2, int firstpass, int lastpass, int
718: mobilavproj)
719:
720: Computes the back prevalence limit for any combination of
721: covariate values k at any age between ageminpar and agemaxpar and
722: returns it in **bprlim. In the loops,
723:
724: - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
725: **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
726:
727: - hBijx Back Probability to be in state i at age x-h being in j at x
728: Computes for any combination of covariates k and any age between bage and fage
729: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
730: oldm=oldms;savm=savms;
731:
732: - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
733: Computes the transition matrix starting at age 'age' over
734: 'nhstepm*hstepm*stepm' months (i.e. until
735: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
736: nhstepm*hstepm matrices.
737:
738: Returns p3mat[i][j][h] after calling
739: p3mat[i][j][h]=matprod2(newm,
740: bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
741: dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
742: oldm);
743:
744: Important routines
745:
746: - func (or funcone), computes logit (pij) distinguishing
747: o fixed variables (single or product dummies or quantitative);
748: o varying variables by:
749: (1) wave (single, product dummies, quantitative),
750: (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
751: % fixed dummy (treated) or quantitative (not done because time-consuming);
752: % varying dummy (not done) or quantitative (not done);
753: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
754: and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
755: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
756: o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
757: race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
758:
759:
760:
761: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
762: Institut national d'études démographiques, Paris.
763: This software have been partly granted by Euro-REVES, a concerted action
764: from the European Union.
765: It is copyrighted identically to a GNU software product, ie programme and
766: software can be distributed freely for non commercial use. Latest version
767: can be accessed at http://euroreves.ined.fr/imach .
768:
769: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
770: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
771:
772: **********************************************************************/
773: /*
774: main
775: read parameterfile
776: read datafile
777: concatwav
778: freqsummary
779: if (mle >= 1)
780: mlikeli
781: print results files
782: if mle==1
783: computes hessian
784: read end of parameter file: agemin, agemax, bage, fage, estepm
785: begin-prev-date,...
786: open gnuplot file
787: open html file
788: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
789: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
790: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
791: freexexit2 possible for memory heap.
792:
793: h Pij x | pij_nom ficrestpij
794: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
795: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
796: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
797:
798: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
799: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
800: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
801: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
802: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
803:
804: forecasting if prevfcast==1 prevforecast call prevalence()
805: health expectancies
806: Variance-covariance of DFLE
807: prevalence()
808: movingaverage()
809: varevsij()
810: if popbased==1 varevsij(,popbased)
811: total life expectancies
812: Variance of period (stable) prevalence
813: end
814: */
815:
816: /* #define DEBUG */
817: /* #define DEBUGBRENT */
818: /* #define DEBUGLINMIN */
819: /* #define DEBUGHESS */
820: #define DEBUGHESSIJ
821: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan) *\/ */
822: #define POWELL /* Instead of NLOPT */
823: #define POWELLNOF3INFF1TEST /* Skip test */
824: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
825: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
826:
827: #include <math.h>
828: #include <stdio.h>
829: #include <stdlib.h>
830: #include <string.h>
831: #include <ctype.h>
832:
833: #ifdef _WIN32
834: #include <io.h>
835: #include <windows.h>
836: #include <tchar.h>
837: #else
838: #include <unistd.h>
839: #endif
840:
841: #include <limits.h>
842: #include <sys/types.h>
843:
844: #if defined(__GNUC__)
845: #include <sys/utsname.h> /* Doesn't work on Windows */
846: #endif
847:
848: #include <sys/stat.h>
849: #include <errno.h>
850: /* extern int errno; */
851:
852: /* #ifdef LINUX */
853: /* #include <time.h> */
854: /* #include "timeval.h" */
855: /* #else */
856: /* #include <sys/time.h> */
857: /* #endif */
858:
859: #include <time.h>
860:
861: #ifdef GSL
862: #include <gsl/gsl_errno.h>
863: #include <gsl/gsl_multimin.h>
864: #endif
865:
866:
867: #ifdef NLOPT
868: #include <nlopt.h>
869: typedef struct {
870: double (* function)(double [] );
871: } myfunc_data ;
872: #endif
873:
874: /* #include <libintl.h> */
875: /* #define _(String) gettext (String) */
876:
877: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
878:
879: #define GNUPLOTPROGRAM "gnuplot"
880: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
881: #define FILENAMELENGTH 132
882:
883: #define GLOCK_ERROR_NOPATH -1 /* empty path */
884: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
885:
886: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
887: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
888:
889: #define NINTERVMAX 8
890: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
891: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
892: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
893: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
894: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
895: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
896: #define MAXN 20000
897: #define YEARM 12. /**< Number of months per year */
898: /* #define AGESUP 130 */
899: #define AGESUP 150
900: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
901: #define AGEBASE 40
902: #define AGEOVERFLOW 1.e20
903: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
904: #ifdef _WIN32
905: #define DIRSEPARATOR '\\'
906: #define CHARSEPARATOR "\\"
907: #define ODIRSEPARATOR '/'
908: #else
909: #define DIRSEPARATOR '/'
910: #define CHARSEPARATOR "/"
911: #define ODIRSEPARATOR '\\'
912: #endif
913:
914: /* $Id: imach.c,v 1.237 2016/08/26 09:20:19 brouard Exp $ */
915: /* $State: Exp $ */
916: #include "version.h"
917: char version[]=__IMACH_VERSION__;
918: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
919: char fullversion[]="$Revision: 1.237 $ $Date: 2016/08/26 09:20:19 $";
920: char strstart[80];
921: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
922: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
923: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
924: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
925: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
926: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
927: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
928: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
929: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
930: int cptcovprodnoage=0; /**< Number of covariate products without age */
931: int cptcoveff=0; /* Total number of covariates to vary for printing results */
932: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
933: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
934: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
935: int nsd=0; /**< Total number of single dummy variables (output) */
936: int nsq=0; /**< Total number of single quantitative variables (output) */
937: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
938: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
939: int ntveff=0; /**< ntveff number of effective time varying variables */
940: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
941: int cptcov=0; /* Working variable */
942: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
943: int npar=NPARMAX;
944: int nlstate=2; /* Number of live states */
945: int ndeath=1; /* Number of dead states */
946: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
947: int nqv=0, ntv=0, nqtv=0; /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */
948: int popbased=0;
949:
950: int *wav; /* Number of waves for this individuual 0 is possible */
951: int maxwav=0; /* Maxim number of waves */
952: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
953: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
954: int gipmx=0, gsw=0; /* Global variables on the number of contributions
955: to the likelihood and the sum of weights (done by funcone)*/
956: int mle=1, weightopt=0;
957: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
958: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
959: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
960: * wave mi and wave mi+1 is not an exact multiple of stepm. */
961: int countcallfunc=0; /* Count the number of calls to func */
962: int selected(int kvar); /* Is covariate kvar selected for printing results */
963:
964: double jmean=1; /* Mean space between 2 waves */
965: double **matprod2(); /* test */
966: double **oldm, **newm, **savm; /* Working pointers to matrices */
967: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
968: double **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
969:
970: /*FILE *fic ; */ /* Used in readdata only */
971: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
972: FILE *ficlog, *ficrespow;
973: int globpr=0; /* Global variable for printing or not */
974: double fretone; /* Only one call to likelihood */
975: long ipmx=0; /* Number of contributions */
976: double sw; /* Sum of weights */
977: char filerespow[FILENAMELENGTH];
978: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
979: FILE *ficresilk;
980: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
981: FILE *ficresprobmorprev;
982: FILE *fichtm, *fichtmcov; /* Html File */
983: FILE *ficreseij;
984: char filerese[FILENAMELENGTH];
985: FILE *ficresstdeij;
986: char fileresstde[FILENAMELENGTH];
987: FILE *ficrescveij;
988: char filerescve[FILENAMELENGTH];
989: FILE *ficresvij;
990: char fileresv[FILENAMELENGTH];
991: FILE *ficresvpl;
992: char fileresvpl[FILENAMELENGTH];
993: char title[MAXLINE];
994: char model[MAXLINE]; /**< The model line */
995: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH], fileresplb[FILENAMELENGTH];
996: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
997: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
998: char command[FILENAMELENGTH];
999: int outcmd=0;
1000:
1001: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1002: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1003: char filelog[FILENAMELENGTH]; /* Log file */
1004: char filerest[FILENAMELENGTH];
1005: char fileregp[FILENAMELENGTH];
1006: char popfile[FILENAMELENGTH];
1007:
1008: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
1009:
1010: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
1011: /* struct timezone tzp; */
1012: /* extern int gettimeofday(); */
1013: struct tm tml, *gmtime(), *localtime();
1014:
1015: extern time_t time();
1016:
1017: struct tm start_time, end_time, curr_time, last_time, forecast_time;
1018: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1019: struct tm tm;
1020:
1021: char strcurr[80], strfor[80];
1022:
1023: char *endptr;
1024: long lval;
1025: double dval;
1026:
1027: #define NR_END 1
1028: #define FREE_ARG char*
1029: #define FTOL 1.0e-10
1030:
1031: #define NRANSI
1032: #define ITMAX 200
1033:
1034: #define TOL 2.0e-4
1035:
1036: #define CGOLD 0.3819660
1037: #define ZEPS 1.0e-10
1038: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
1039:
1040: #define GOLD 1.618034
1041: #define GLIMIT 100.0
1042: #define TINY 1.0e-20
1043:
1044: static double maxarg1,maxarg2;
1045: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
1046: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
1047:
1048: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
1049: #define rint(a) floor(a+0.5)
1050: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1051: #define mytinydouble 1.0e-16
1052: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
1053: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
1054: /* static double dsqrarg; */
1055: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1056: static double sqrarg;
1057: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
1058: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
1059: int agegomp= AGEGOMP;
1060:
1061: int imx;
1062: int stepm=1;
1063: /* Stepm, step in month: minimum step interpolation*/
1064:
1065: int estepm;
1066: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
1067:
1068: int m,nb;
1069: long *num;
1070: int firstpass=0, lastpass=4,*cod, *cens;
1071: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
1072: covariate for which somebody answered excluding
1073: undefined. Usually 2: 0 and 1. */
1074: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
1075: covariate for which somebody answered including
1076: undefined. Usually 3: -1, 0 and 1. */
1077: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1078: double **pmmij, ***probs; /* Global pointer */
1079: double ***mobaverage, ***mobaverages; /* New global variable */
1080: double *ageexmed,*agecens;
1081: double dateintmean=0;
1082:
1083: double *weight;
1084: int **s; /* Status */
1085: double *agedc;
1086: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1087: * covar=matrix(0,NCOVMAX,1,n);
1088: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1089: double **coqvar; /* Fixed quantitative covariate iqv */
1090: double ***cotvar; /* Time varying covariate itv */
1091: double ***cotqvar; /* Time varying quantitative covariate itqv */
1092: double idx;
1093: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1094: /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1095: /*k 1 2 3 4 5 6 7 8 9 */
1096: /*Tvar[k]= 5 4 3 6 5 2 7 1 1 */
1097: /* Tndvar[k] 1 2 3 4 5 */
1098: /*TDvar 4 3 6 7 1 */ /* For outputs only; combination of dummies fixed or varying */
1099: /* Tns[k] 1 2 2 4 5 */ /* Number of single cova */
1100: /* TvarsD[k] 1 2 3 */ /* Number of single dummy cova */
1101: /* TvarsDind 2 3 9 */ /* position K of single dummy cova */
1102: /* TvarsQ[k] 1 2 */ /* Number of single quantitative cova */
1103: /* TvarsQind 1 6 */ /* position K of single quantitative cova */
1104: /* Tprod[i]=k 4 7 */
1105: /* Tage[i]=k 5 8 */
1106: /* */
1107: /* Type */
1108: /* V 1 2 3 4 5 */
1109: /* F F V V V */
1110: /* D Q D D Q */
1111: /* */
1112: int *TvarsD;
1113: int *TvarsDind;
1114: int *TvarsQ;
1115: int *TvarsQind;
1116:
1117: #define MAXRESULTLINES 10
1118: int nresult=0;
1119: int TKresult[MAXRESULTLINES];
1120: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1121: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1122: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
1123: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1124: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1125: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
1126:
1127: /* int *TDvar; /\**< TDvar[1]=4, TDvarF[2]=3, TDvar[3]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
1128: int *TvarF; /**< TvarF[1]=Tvar[6]=2, TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1129: int *TvarFind; /**< TvarFind[1]=6, TvarFind[2]=7, Tvarind[3]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1130: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1131: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1132: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1133: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1134: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1135: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1136: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1137: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1138: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1139: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1140: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1141: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1142:
1143: int *Tvarsel; /**< Selected covariates for output */
1144: double *Tvalsel; /**< Selected modality value of covariate for output */
1145: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
1146: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
1147: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */
1148: int *Tage;
1149: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */
1150: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1151: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1152: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1153: int *Ndum; /** Freq of modality (tricode */
1154: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1155: int **Tvard;
1156: int *Tprod;/**< Gives the k position of the k1 product */
1157: int *Tposprod; /**< Gives the k1 product from the k position */
1158: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
1159: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
1160: Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2
1161: */
1162: int cptcovprod, *Tvaraff, *invalidvarcomb;
1163: double *lsurv, *lpop, *tpop;
1164:
1165: #define FD 1; /* Fixed dummy covariate */
1166: #define FQ 2; /* Fixed quantitative covariate */
1167: #define FP 3; /* Fixed product covariate */
1168: #define FPDD 7; /* Fixed product dummy*dummy covariate */
1169: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
1170: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
1171: #define VD 10; /* Varying dummy covariate */
1172: #define VQ 11; /* Varying quantitative covariate */
1173: #define VP 12; /* Varying product covariate */
1174: #define VPDD 13; /* Varying product dummy*dummy covariate */
1175: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
1176: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
1177: #define APFD 16; /* Age product * fixed dummy covariate */
1178: #define APFQ 17; /* Age product * fixed quantitative covariate */
1179: #define APVD 18; /* Age product * varying dummy covariate */
1180: #define APVQ 19; /* Age product * varying quantitative covariate */
1181:
1182: #define FTYPE 1; /* Fixed covariate */
1183: #define VTYPE 2; /* Varying covariate (loop in wave) */
1184: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
1185:
1186: struct kmodel{
1187: int maintype; /* main type */
1188: int subtype; /* subtype */
1189: };
1190: struct kmodel modell[NCOVMAX];
1191:
1192: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
1193: double ftolhess; /**< Tolerance for computing hessian */
1194:
1195: /**************** split *************************/
1196: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
1197: {
1198: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
1199: the name of the file (name), its extension only (ext) and its first part of the name (finame)
1200: */
1201: char *ss; /* pointer */
1202: int l1=0, l2=0; /* length counters */
1203:
1204: l1 = strlen(path ); /* length of path */
1205: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
1206: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
1207: if ( ss == NULL ) { /* no directory, so determine current directory */
1208: strcpy( name, path ); /* we got the fullname name because no directory */
1209: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
1210: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
1211: /* get current working directory */
1212: /* extern char* getcwd ( char *buf , int len);*/
1213: #ifdef WIN32
1214: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
1215: #else
1216: if (getcwd(dirc, FILENAME_MAX) == NULL) {
1217: #endif
1218: return( GLOCK_ERROR_GETCWD );
1219: }
1220: /* got dirc from getcwd*/
1221: printf(" DIRC = %s \n",dirc);
1222: } else { /* strip directory from path */
1223: ss++; /* after this, the filename */
1224: l2 = strlen( ss ); /* length of filename */
1225: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
1226: strcpy( name, ss ); /* save file name */
1227: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1228: dirc[l1-l2] = '\0'; /* add zero */
1229: printf(" DIRC2 = %s \n",dirc);
1230: }
1231: /* We add a separator at the end of dirc if not exists */
1232: l1 = strlen( dirc ); /* length of directory */
1233: if( dirc[l1-1] != DIRSEPARATOR ){
1234: dirc[l1] = DIRSEPARATOR;
1235: dirc[l1+1] = 0;
1236: printf(" DIRC3 = %s \n",dirc);
1237: }
1238: ss = strrchr( name, '.' ); /* find last / */
1239: if (ss >0){
1240: ss++;
1241: strcpy(ext,ss); /* save extension */
1242: l1= strlen( name);
1243: l2= strlen(ss)+1;
1244: strncpy( finame, name, l1-l2);
1245: finame[l1-l2]= 0;
1246: }
1247:
1248: return( 0 ); /* we're done */
1249: }
1250:
1251:
1252: /******************************************/
1253:
1254: void replace_back_to_slash(char *s, char*t)
1255: {
1256: int i;
1257: int lg=0;
1258: i=0;
1259: lg=strlen(t);
1260: for(i=0; i<= lg; i++) {
1261: (s[i] = t[i]);
1262: if (t[i]== '\\') s[i]='/';
1263: }
1264: }
1265:
1266: char *trimbb(char *out, char *in)
1267: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1268: char *s;
1269: s=out;
1270: while (*in != '\0'){
1271: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1272: in++;
1273: }
1274: *out++ = *in++;
1275: }
1276: *out='\0';
1277: return s;
1278: }
1279:
1280: /* char *substrchaine(char *out, char *in, char *chain) */
1281: /* { */
1282: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1283: /* char *s, *t; */
1284: /* t=in;s=out; */
1285: /* while ((*in != *chain) && (*in != '\0')){ */
1286: /* *out++ = *in++; */
1287: /* } */
1288:
1289: /* /\* *in matches *chain *\/ */
1290: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1291: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1292: /* } */
1293: /* in--; chain--; */
1294: /* while ( (*in != '\0')){ */
1295: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1296: /* *out++ = *in++; */
1297: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1298: /* } */
1299: /* *out='\0'; */
1300: /* out=s; */
1301: /* return out; */
1302: /* } */
1303: char *substrchaine(char *out, char *in, char *chain)
1304: {
1305: /* Substract chain 'chain' from 'in', return and output 'out' */
1306: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1307:
1308: char *strloc;
1309:
1310: strcpy (out, in);
1311: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1312: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1313: if(strloc != NULL){
1314: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1315: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1316: /* strcpy (strloc, strloc +strlen(chain));*/
1317: }
1318: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1319: return out;
1320: }
1321:
1322:
1323: char *cutl(char *blocc, char *alocc, char *in, char occ)
1324: {
1325: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1326: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1327: gives blocc="abcdef" and alocc="ghi2j".
1328: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1329: */
1330: char *s, *t;
1331: t=in;s=in;
1332: while ((*in != occ) && (*in != '\0')){
1333: *alocc++ = *in++;
1334: }
1335: if( *in == occ){
1336: *(alocc)='\0';
1337: s=++in;
1338: }
1339:
1340: if (s == t) {/* occ not found */
1341: *(alocc-(in-s))='\0';
1342: in=s;
1343: }
1344: while ( *in != '\0'){
1345: *blocc++ = *in++;
1346: }
1347:
1348: *blocc='\0';
1349: return t;
1350: }
1351: char *cutv(char *blocc, char *alocc, char *in, char occ)
1352: {
1353: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1354: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1355: gives blocc="abcdef2ghi" and alocc="j".
1356: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1357: */
1358: char *s, *t;
1359: t=in;s=in;
1360: while (*in != '\0'){
1361: while( *in == occ){
1362: *blocc++ = *in++;
1363: s=in;
1364: }
1365: *blocc++ = *in++;
1366: }
1367: if (s == t) /* occ not found */
1368: *(blocc-(in-s))='\0';
1369: else
1370: *(blocc-(in-s)-1)='\0';
1371: in=s;
1372: while ( *in != '\0'){
1373: *alocc++ = *in++;
1374: }
1375:
1376: *alocc='\0';
1377: return s;
1378: }
1379:
1380: int nbocc(char *s, char occ)
1381: {
1382: int i,j=0;
1383: int lg=20;
1384: i=0;
1385: lg=strlen(s);
1386: for(i=0; i<= lg; i++) {
1387: if (s[i] == occ ) j++;
1388: }
1389: return j;
1390: }
1391:
1392: /* void cutv(char *u,char *v, char*t, char occ) */
1393: /* { */
1394: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1395: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1396: /* gives u="abcdef2ghi" and v="j" *\/ */
1397: /* int i,lg,j,p=0; */
1398: /* i=0; */
1399: /* lg=strlen(t); */
1400: /* for(j=0; j<=lg-1; j++) { */
1401: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1402: /* } */
1403:
1404: /* for(j=0; j<p; j++) { */
1405: /* (u[j] = t[j]); */
1406: /* } */
1407: /* u[p]='\0'; */
1408:
1409: /* for(j=0; j<= lg; j++) { */
1410: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1411: /* } */
1412: /* } */
1413:
1414: #ifdef _WIN32
1415: char * strsep(char **pp, const char *delim)
1416: {
1417: char *p, *q;
1418:
1419: if ((p = *pp) == NULL)
1420: return 0;
1421: if ((q = strpbrk (p, delim)) != NULL)
1422: {
1423: *pp = q + 1;
1424: *q = '\0';
1425: }
1426: else
1427: *pp = 0;
1428: return p;
1429: }
1430: #endif
1431:
1432: /********************** nrerror ********************/
1433:
1434: void nrerror(char error_text[])
1435: {
1436: fprintf(stderr,"ERREUR ...\n");
1437: fprintf(stderr,"%s\n",error_text);
1438: exit(EXIT_FAILURE);
1439: }
1440: /*********************** vector *******************/
1441: double *vector(int nl, int nh)
1442: {
1443: double *v;
1444: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1445: if (!v) nrerror("allocation failure in vector");
1446: return v-nl+NR_END;
1447: }
1448:
1449: /************************ free vector ******************/
1450: void free_vector(double*v, int nl, int nh)
1451: {
1452: free((FREE_ARG)(v+nl-NR_END));
1453: }
1454:
1455: /************************ivector *******************************/
1456: int *ivector(long nl,long nh)
1457: {
1458: int *v;
1459: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1460: if (!v) nrerror("allocation failure in ivector");
1461: return v-nl+NR_END;
1462: }
1463:
1464: /******************free ivector **************************/
1465: void free_ivector(int *v, long nl, long nh)
1466: {
1467: free((FREE_ARG)(v+nl-NR_END));
1468: }
1469:
1470: /************************lvector *******************************/
1471: long *lvector(long nl,long nh)
1472: {
1473: long *v;
1474: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1475: if (!v) nrerror("allocation failure in ivector");
1476: return v-nl+NR_END;
1477: }
1478:
1479: /******************free lvector **************************/
1480: void free_lvector(long *v, long nl, long nh)
1481: {
1482: free((FREE_ARG)(v+nl-NR_END));
1483: }
1484:
1485: /******************* imatrix *******************************/
1486: int **imatrix(long nrl, long nrh, long ncl, long nch)
1487: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1488: {
1489: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1490: int **m;
1491:
1492: /* allocate pointers to rows */
1493: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1494: if (!m) nrerror("allocation failure 1 in matrix()");
1495: m += NR_END;
1496: m -= nrl;
1497:
1498:
1499: /* allocate rows and set pointers to them */
1500: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1501: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1502: m[nrl] += NR_END;
1503: m[nrl] -= ncl;
1504:
1505: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1506:
1507: /* return pointer to array of pointers to rows */
1508: return m;
1509: }
1510:
1511: /****************** free_imatrix *************************/
1512: void free_imatrix(m,nrl,nrh,ncl,nch)
1513: int **m;
1514: long nch,ncl,nrh,nrl;
1515: /* free an int matrix allocated by imatrix() */
1516: {
1517: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1518: free((FREE_ARG) (m+nrl-NR_END));
1519: }
1520:
1521: /******************* matrix *******************************/
1522: double **matrix(long nrl, long nrh, long ncl, long nch)
1523: {
1524: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1525: double **m;
1526:
1527: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1528: if (!m) nrerror("allocation failure 1 in matrix()");
1529: m += NR_END;
1530: m -= nrl;
1531:
1532: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1533: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1534: m[nrl] += NR_END;
1535: m[nrl] -= ncl;
1536:
1537: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1538: return m;
1539: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1540: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1541: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1542: */
1543: }
1544:
1545: /*************************free matrix ************************/
1546: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1547: {
1548: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1549: free((FREE_ARG)(m+nrl-NR_END));
1550: }
1551:
1552: /******************* ma3x *******************************/
1553: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1554: {
1555: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1556: double ***m;
1557:
1558: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1559: if (!m) nrerror("allocation failure 1 in matrix()");
1560: m += NR_END;
1561: m -= nrl;
1562:
1563: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1564: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1565: m[nrl] += NR_END;
1566: m[nrl] -= ncl;
1567:
1568: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1569:
1570: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1571: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1572: m[nrl][ncl] += NR_END;
1573: m[nrl][ncl] -= nll;
1574: for (j=ncl+1; j<=nch; j++)
1575: m[nrl][j]=m[nrl][j-1]+nlay;
1576:
1577: for (i=nrl+1; i<=nrh; i++) {
1578: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1579: for (j=ncl+1; j<=nch; j++)
1580: m[i][j]=m[i][j-1]+nlay;
1581: }
1582: return m;
1583: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1584: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1585: */
1586: }
1587:
1588: /*************************free ma3x ************************/
1589: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1590: {
1591: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1592: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1593: free((FREE_ARG)(m+nrl-NR_END));
1594: }
1595:
1596: /*************** function subdirf ***********/
1597: char *subdirf(char fileres[])
1598: {
1599: /* Caution optionfilefiname is hidden */
1600: strcpy(tmpout,optionfilefiname);
1601: strcat(tmpout,"/"); /* Add to the right */
1602: strcat(tmpout,fileres);
1603: return tmpout;
1604: }
1605:
1606: /*************** function subdirf2 ***********/
1607: char *subdirf2(char fileres[], char *preop)
1608: {
1609:
1610: /* Caution optionfilefiname is hidden */
1611: strcpy(tmpout,optionfilefiname);
1612: strcat(tmpout,"/");
1613: strcat(tmpout,preop);
1614: strcat(tmpout,fileres);
1615: return tmpout;
1616: }
1617:
1618: /*************** function subdirf3 ***********/
1619: char *subdirf3(char fileres[], char *preop, char *preop2)
1620: {
1621:
1622: /* Caution optionfilefiname is hidden */
1623: strcpy(tmpout,optionfilefiname);
1624: strcat(tmpout,"/");
1625: strcat(tmpout,preop);
1626: strcat(tmpout,preop2);
1627: strcat(tmpout,fileres);
1628: return tmpout;
1629: }
1630:
1631: /*************** function subdirfext ***********/
1632: char *subdirfext(char fileres[], char *preop, char *postop)
1633: {
1634:
1635: strcpy(tmpout,preop);
1636: strcat(tmpout,fileres);
1637: strcat(tmpout,postop);
1638: return tmpout;
1639: }
1640:
1641: /*************** function subdirfext3 ***********/
1642: char *subdirfext3(char fileres[], char *preop, char *postop)
1643: {
1644:
1645: /* Caution optionfilefiname is hidden */
1646: strcpy(tmpout,optionfilefiname);
1647: strcat(tmpout,"/");
1648: strcat(tmpout,preop);
1649: strcat(tmpout,fileres);
1650: strcat(tmpout,postop);
1651: return tmpout;
1652: }
1653:
1654: char *asc_diff_time(long time_sec, char ascdiff[])
1655: {
1656: long sec_left, days, hours, minutes;
1657: days = (time_sec) / (60*60*24);
1658: sec_left = (time_sec) % (60*60*24);
1659: hours = (sec_left) / (60*60) ;
1660: sec_left = (sec_left) %(60*60);
1661: minutes = (sec_left) /60;
1662: sec_left = (sec_left) % (60);
1663: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1664: return ascdiff;
1665: }
1666:
1667: /***************** f1dim *************************/
1668: extern int ncom;
1669: extern double *pcom,*xicom;
1670: extern double (*nrfunc)(double []);
1671:
1672: double f1dim(double x)
1673: {
1674: int j;
1675: double f;
1676: double *xt;
1677:
1678: xt=vector(1,ncom);
1679: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1680: f=(*nrfunc)(xt);
1681: free_vector(xt,1,ncom);
1682: return f;
1683: }
1684:
1685: /*****************brent *************************/
1686: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1687: {
1688: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1689: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1690: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1691: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1692: * returned function value.
1693: */
1694: int iter;
1695: double a,b,d,etemp;
1696: double fu=0,fv,fw,fx;
1697: double ftemp=0.;
1698: double p,q,r,tol1,tol2,u,v,w,x,xm;
1699: double e=0.0;
1700:
1701: a=(ax < cx ? ax : cx);
1702: b=(ax > cx ? ax : cx);
1703: x=w=v=bx;
1704: fw=fv=fx=(*f)(x);
1705: for (iter=1;iter<=ITMAX;iter++) {
1706: xm=0.5*(a+b);
1707: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1708: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1709: printf(".");fflush(stdout);
1710: fprintf(ficlog,".");fflush(ficlog);
1711: #ifdef DEBUGBRENT
1712: 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);
1713: 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);
1714: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1715: #endif
1716: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1717: *xmin=x;
1718: return fx;
1719: }
1720: ftemp=fu;
1721: if (fabs(e) > tol1) {
1722: r=(x-w)*(fx-fv);
1723: q=(x-v)*(fx-fw);
1724: p=(x-v)*q-(x-w)*r;
1725: q=2.0*(q-r);
1726: if (q > 0.0) p = -p;
1727: q=fabs(q);
1728: etemp=e;
1729: e=d;
1730: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1731: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1732: else {
1733: d=p/q;
1734: u=x+d;
1735: if (u-a < tol2 || b-u < tol2)
1736: d=SIGN(tol1,xm-x);
1737: }
1738: } else {
1739: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1740: }
1741: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1742: fu=(*f)(u);
1743: if (fu <= fx) {
1744: if (u >= x) a=x; else b=x;
1745: SHFT(v,w,x,u)
1746: SHFT(fv,fw,fx,fu)
1747: } else {
1748: if (u < x) a=u; else b=u;
1749: if (fu <= fw || w == x) {
1750: v=w;
1751: w=u;
1752: fv=fw;
1753: fw=fu;
1754: } else if (fu <= fv || v == x || v == w) {
1755: v=u;
1756: fv=fu;
1757: }
1758: }
1759: }
1760: nrerror("Too many iterations in brent");
1761: *xmin=x;
1762: return fx;
1763: }
1764:
1765: /****************** mnbrak ***********************/
1766:
1767: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1768: double (*func)(double))
1769: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1770: the downhill direction (defined by the function as evaluated at the initial points) and returns
1771: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1772: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1773: */
1774: double ulim,u,r,q, dum;
1775: double fu;
1776:
1777: double scale=10.;
1778: int iterscale=0;
1779:
1780: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1781: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1782:
1783:
1784: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1785: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1786: /* *bx = *ax - (*ax - *bx)/scale; */
1787: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1788: /* } */
1789:
1790: if (*fb > *fa) {
1791: SHFT(dum,*ax,*bx,dum)
1792: SHFT(dum,*fb,*fa,dum)
1793: }
1794: *cx=(*bx)+GOLD*(*bx-*ax);
1795: *fc=(*func)(*cx);
1796: #ifdef DEBUG
1797: printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1798: fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1799: #endif
1800: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
1801: r=(*bx-*ax)*(*fb-*fc);
1802: q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1803: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1804: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1805: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1806: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1807: fu=(*func)(u);
1808: #ifdef DEBUG
1809: /* f(x)=A(x-u)**2+f(u) */
1810: double A, fparabu;
1811: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1812: fparabu= *fa - A*(*ax-u)*(*ax-u);
1813: printf("\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
1814: fprintf(ficlog,"\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
1815: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1816: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1817: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1818: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1819: #endif
1820: #ifdef MNBRAKORIGINAL
1821: #else
1822: /* if (fu > *fc) { */
1823: /* #ifdef DEBUG */
1824: /* printf("mnbrak4 fu > fc \n"); */
1825: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1826: /* #endif */
1827: /* /\* 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 *\\/ *\/ */
1828: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1829: /* dum=u; /\* Shifting c and u *\/ */
1830: /* u = *cx; */
1831: /* *cx = dum; */
1832: /* dum = fu; */
1833: /* fu = *fc; */
1834: /* *fc =dum; */
1835: /* } else { /\* end *\/ */
1836: /* #ifdef DEBUG */
1837: /* printf("mnbrak3 fu < fc \n"); */
1838: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1839: /* #endif */
1840: /* dum=u; /\* Shifting c and u *\/ */
1841: /* u = *cx; */
1842: /* *cx = dum; */
1843: /* dum = fu; */
1844: /* fu = *fc; */
1845: /* *fc =dum; */
1846: /* } */
1847: #ifdef DEBUGMNBRAK
1848: double A, fparabu;
1849: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1850: fparabu= *fa - A*(*ax-u)*(*ax-u);
1851: printf("\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
1852: fprintf(ficlog,"\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
1853: #endif
1854: dum=u; /* Shifting c and u */
1855: u = *cx;
1856: *cx = dum;
1857: dum = fu;
1858: fu = *fc;
1859: *fc =dum;
1860: #endif
1861: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1862: #ifdef DEBUG
1863: printf("\nmnbrak2 u=%lf after c=%lf but before ulim\n",u,*cx);
1864: fprintf(ficlog,"\nmnbrak2 u=%lf after c=%lf but before ulim\n",u,*cx);
1865: #endif
1866: fu=(*func)(u);
1867: if (fu < *fc) {
1868: #ifdef DEBUG
1869: printf("\nmnbrak2 u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
1870: fprintf(ficlog,"\nmnbrak2 u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
1871: #endif
1872: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1873: SHFT(*fb,*fc,fu,(*func)(u))
1874: #ifdef DEBUG
1875: printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1876: #endif
1877: }
1878: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1879: #ifdef DEBUG
1880: printf("\nmnbrak2 u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1881: fprintf(ficlog,"\nmnbrak2 u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1882: #endif
1883: u=ulim;
1884: fu=(*func)(u);
1885: } else { /* u could be left to b (if r > q parabola has a maximum) */
1886: #ifdef DEBUG
1887: printf("\nmnbrak2 u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
1888: fprintf(ficlog,"\nmnbrak2 u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
1889: #endif
1890: u=(*cx)+GOLD*(*cx-*bx);
1891: fu=(*func)(u);
1892: #ifdef DEBUG
1893: printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
1894: fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
1895: #endif
1896: } /* end tests */
1897: SHFT(*ax,*bx,*cx,u)
1898: SHFT(*fa,*fb,*fc,fu)
1899: #ifdef DEBUG
1900: printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1901: fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1902: #endif
1903: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1904: }
1905:
1906: /*************** linmin ************************/
1907: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1908: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1909: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1910: the value of func at the returned location p . This is actually all accomplished by calling the
1911: routines mnbrak and brent .*/
1912: int ncom;
1913: double *pcom,*xicom;
1914: double (*nrfunc)(double []);
1915:
1916: #ifdef LINMINORIGINAL
1917: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1918: #else
1919: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat)
1920: #endif
1921: {
1922: double brent(double ax, double bx, double cx,
1923: double (*f)(double), double tol, double *xmin);
1924: double f1dim(double x);
1925: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1926: double *fc, double (*func)(double));
1927: int j;
1928: double xx,xmin,bx,ax;
1929: double fx,fb,fa;
1930:
1931: #ifdef LINMINORIGINAL
1932: #else
1933: double scale=10., axs, xxs; /* Scale added for infinity */
1934: #endif
1935:
1936: ncom=n;
1937: pcom=vector(1,n);
1938: xicom=vector(1,n);
1939: nrfunc=func;
1940: for (j=1;j<=n;j++) {
1941: pcom[j]=p[j];
1942: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1943: }
1944:
1945: #ifdef LINMINORIGINAL
1946: xx=1.;
1947: #else
1948: axs=0.0;
1949: xxs=1.;
1950: do{
1951: xx= xxs;
1952: #endif
1953: ax=0.;
1954: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1955: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1956: /* 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)) */
1957: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1958: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1959: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1960: /* 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]]*/
1961: #ifdef LINMINORIGINAL
1962: #else
1963: if (fx != fx){
1964: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1965: printf("|");
1966: fprintf(ficlog,"|");
1967: #ifdef DEBUGLINMIN
1968: 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);
1969: #endif
1970: }
1971: }while(fx != fx && xxs > 1.e-5);
1972: #endif
1973:
1974: #ifdef DEBUGLINMIN
1975: 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);
1976: 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);
1977: #endif
1978: #ifdef LINMINORIGINAL
1979: #else
1980: if(fb == fx){ /* Flat function in the direction */
1981: xmin=xx;
1982: *flat=1;
1983: }else{
1984: *flat=0;
1985: #endif
1986: /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1987: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1988: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1989: /* fmin = f(p[j] + xmin * xi[j]) */
1990: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1991: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1992: #ifdef DEBUG
1993: printf("retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
1994: fprintf(ficlog,"retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
1995: #endif
1996: #ifdef LINMINORIGINAL
1997: #else
1998: }
1999: #endif
2000: #ifdef DEBUGLINMIN
2001: printf("linmin end ");
2002: fprintf(ficlog,"linmin end ");
2003: #endif
2004: for (j=1;j<=n;j++) {
2005: #ifdef LINMINORIGINAL
2006: xi[j] *= xmin;
2007: #else
2008: #ifdef DEBUGLINMIN
2009: if(xxs <1.0)
2010: printf(" before xi[%d]=%12.8f", j,xi[j]);
2011: #endif
2012: 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) */
2013: #ifdef DEBUGLINMIN
2014: if(xxs <1.0)
2015: 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 );
2016: #endif
2017: #endif
2018: p[j] += xi[j]; /* Parameters values are updated accordingly */
2019: }
2020: #ifdef DEBUGLINMIN
2021: printf("\n");
2022: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
2023: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
2024: for (j=1;j<=n;j++) {
2025: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
2026: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
2027: if(j % ncovmodel == 0){
2028: printf("\n");
2029: fprintf(ficlog,"\n");
2030: }
2031: }
2032: #else
2033: #endif
2034: free_vector(xicom,1,n);
2035: free_vector(pcom,1,n);
2036: }
2037:
2038:
2039: /*************** powell ************************/
2040: /*
2041: Minimization of a function func of n variables. Input consists of an initial starting point
2042: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
2043: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
2044: such that failure to decrease by more than this amount on one iteration signals doneness. On
2045: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
2046: function value at p , and iter is the number of iterations taken. The routine linmin is used.
2047: */
2048: #ifdef LINMINORIGINAL
2049: #else
2050: int *flatdir; /* Function is vanishing in that direction */
2051: int flat=0, flatd=0; /* Function is vanishing in that direction */
2052: #endif
2053: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
2054: double (*func)(double []))
2055: {
2056: #ifdef LINMINORIGINAL
2057: void linmin(double p[], double xi[], int n, double *fret,
2058: double (*func)(double []));
2059: #else
2060: void linmin(double p[], double xi[], int n, double *fret,
2061: double (*func)(double []),int *flat);
2062: #endif
2063: int i,ibig,j;
2064: double del,t,*pt,*ptt,*xit;
2065: double directest;
2066: double fp,fptt;
2067: double *xits;
2068: int niterf, itmp;
2069: #ifdef LINMINORIGINAL
2070: #else
2071:
2072: flatdir=ivector(1,n);
2073: for (j=1;j<=n;j++) flatdir[j]=0;
2074: #endif
2075:
2076: pt=vector(1,n);
2077: ptt=vector(1,n);
2078: xit=vector(1,n);
2079: xits=vector(1,n);
2080: *fret=(*func)(p);
2081: for (j=1;j<=n;j++) pt[j]=p[j];
2082: rcurr_time = time(NULL);
2083: for (*iter=1;;++(*iter)) {
2084: fp=(*fret); /* From former iteration or initial value */
2085: ibig=0;
2086: del=0.0;
2087: rlast_time=rcurr_time;
2088: /* (void) gettimeofday(&curr_time,&tzp); */
2089: rcurr_time = time(NULL);
2090: curr_time = *localtime(&rcurr_time);
2091: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
2092: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
2093: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
2094: for (i=1;i<=n;i++) {
2095: printf(" %d %.12f",i, p[i]);
2096: fprintf(ficlog," %d %.12lf",i, p[i]);
2097: fprintf(ficrespow," %.12lf", p[i]);
2098: }
2099: printf("\n");
2100: fprintf(ficlog,"\n");
2101: fprintf(ficrespow,"\n");fflush(ficrespow);
2102: if(*iter <=3){
2103: tml = *localtime(&rcurr_time);
2104: strcpy(strcurr,asctime(&tml));
2105: rforecast_time=rcurr_time;
2106: itmp = strlen(strcurr);
2107: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
2108: strcurr[itmp-1]='\0';
2109: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
2110: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
2111: for(niterf=10;niterf<=30;niterf+=10){
2112: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
2113: forecast_time = *localtime(&rforecast_time);
2114: strcpy(strfor,asctime(&forecast_time));
2115: itmp = strlen(strfor);
2116: if(strfor[itmp-1]=='\n')
2117: strfor[itmp-1]='\0';
2118: 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);
2119: 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);
2120: }
2121: }
2122: for (i=1;i<=n;i++) { /* For each direction i */
2123: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
2124: fptt=(*fret);
2125: #ifdef DEBUG
2126: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
2127: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
2128: #endif
2129: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
2130: fprintf(ficlog,"%d",i);fflush(ficlog);
2131: #ifdef LINMINORIGINAL
2132: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
2133: #else
2134: linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
2135: flatdir[i]=flat; /* Function is vanishing in that direction i */
2136: #endif
2137: /* Outputs are fret(new point p) p is updated and xit rescaled */
2138: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
2139: /* because that direction will be replaced unless the gain del is small */
2140: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
2141: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
2142: /* with the new direction. */
2143: del=fabs(fptt-(*fret));
2144: ibig=i;
2145: }
2146: #ifdef DEBUG
2147: printf("%d %.12e",i,(*fret));
2148: fprintf(ficlog,"%d %.12e",i,(*fret));
2149: for (j=1;j<=n;j++) {
2150: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
2151: printf(" x(%d)=%.12e",j,xit[j]);
2152: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
2153: }
2154: for(j=1;j<=n;j++) {
2155: printf(" p(%d)=%.12e",j,p[j]);
2156: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
2157: }
2158: printf("\n");
2159: fprintf(ficlog,"\n");
2160: #endif
2161: } /* end loop on each direction i */
2162: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
2163: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
2164: /* New value of last point Pn is not computed, P(n-1) */
2165: for(j=1;j<=n;j++) {
2166: if(flatdir[j] >0){
2167: printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
2168: fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
2169: }
2170: /* printf("\n"); */
2171: /* fprintf(ficlog,"\n"); */
2172: }
2173: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
2174: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
2175: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
2176: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
2177: /* decreased of more than 3.84 */
2178: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
2179: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
2180: /* By adding 10 parameters more the gain should be 18.31 */
2181:
2182: /* Starting the program with initial values given by a former maximization will simply change */
2183: /* the scales of the directions and the directions, because the are reset to canonical directions */
2184: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
2185: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
2186: #ifdef DEBUG
2187: int k[2],l;
2188: k[0]=1;
2189: k[1]=-1;
2190: printf("Max: %.12e",(*func)(p));
2191: fprintf(ficlog,"Max: %.12e",(*func)(p));
2192: for (j=1;j<=n;j++) {
2193: printf(" %.12e",p[j]);
2194: fprintf(ficlog," %.12e",p[j]);
2195: }
2196: printf("\n");
2197: fprintf(ficlog,"\n");
2198: for(l=0;l<=1;l++) {
2199: for (j=1;j<=n;j++) {
2200: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
2201: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
2202: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
2203: }
2204: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
2205: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
2206: }
2207: #endif
2208:
2209: #ifdef LINMINORIGINAL
2210: #else
2211: free_ivector(flatdir,1,n);
2212: #endif
2213: free_vector(xit,1,n);
2214: free_vector(xits,1,n);
2215: free_vector(ptt,1,n);
2216: free_vector(pt,1,n);
2217: return;
2218: } /* enough precision */
2219: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
2220: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
2221: ptt[j]=2.0*p[j]-pt[j];
2222: xit[j]=p[j]-pt[j];
2223: pt[j]=p[j];
2224: }
2225: fptt=(*func)(ptt); /* f_3 */
2226: #ifdef NODIRECTIONCHANGEDUNTILNITER /* No change in drections until some iterations are done */
2227: if (*iter <=4) {
2228: #else
2229: #endif
2230: #ifdef POWELLNOF3INFF1TEST /* skips test F3 <F1 */
2231: #else
2232: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
2233: #endif
2234: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
2235: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
2236: /* Let f"(x2) be the 2nd derivative equal everywhere. */
2237: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
2238: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
2239: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
2240: /* also lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
2241: /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
2242: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
2243: /* Even if f3 <f1, directest can be negative and t >0 */
2244: /* mu² and del² are equal when f3=f1 */
2245: /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
2246: /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
2247: /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0 */
2248: /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0 */
2249: #ifdef NRCORIGINAL
2250: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
2251: #else
2252: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
2253: t= t- del*SQR(fp-fptt);
2254: #endif
2255: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
2256: #ifdef DEBUG
2257: 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);
2258: 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);
2259: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
2260: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
2261: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
2262: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
2263: 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);
2264: 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);
2265: #endif
2266: #ifdef POWELLORIGINAL
2267: if (t < 0.0) { /* Then we use it for new direction */
2268: #else
2269: if (directest*t < 0.0) { /* Contradiction between both tests */
2270: 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);
2271: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
2272: fprintf(ficlog,"directest= %.12lf (if directest<0 or t<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);
2273: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
2274: }
2275: if (directest < 0.0) { /* Then we use it for new direction */
2276: #endif
2277: #ifdef DEBUGLINMIN
2278: printf("Before linmin in direction P%d-P0\n",n);
2279: for (j=1;j<=n;j++) {
2280: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2281: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2282: if(j % ncovmodel == 0){
2283: printf("\n");
2284: fprintf(ficlog,"\n");
2285: }
2286: }
2287: #endif
2288: #ifdef LINMINORIGINAL
2289: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
2290: #else
2291: linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
2292: flatdir[i]=flat; /* Function is vanishing in that direction i */
2293: #endif
2294:
2295: #ifdef DEBUGLINMIN
2296: for (j=1;j<=n;j++) {
2297: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2298: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2299: if(j % ncovmodel == 0){
2300: printf("\n");
2301: fprintf(ficlog,"\n");
2302: }
2303: }
2304: #endif
2305: for (j=1;j<=n;j++) {
2306: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
2307: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
2308: }
2309: #ifdef LINMINORIGINAL
2310: #else
2311: for (j=1, flatd=0;j<=n;j++) {
2312: if(flatdir[j]>0)
2313: flatd++;
2314: }
2315: if(flatd >0){
2316: printf("%d flat directions\n",flatd);
2317: fprintf(ficlog,"%d flat directions\n",flatd);
2318: for (j=1;j<=n;j++) {
2319: if(flatdir[j]>0){
2320: printf("%d ",j);
2321: fprintf(ficlog,"%d ",j);
2322: }
2323: }
2324: printf("\n");
2325: fprintf(ficlog,"\n");
2326: }
2327: #endif
2328: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2329: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2330:
2331: #ifdef DEBUG
2332: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2333: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2334: for(j=1;j<=n;j++){
2335: printf(" %lf",xit[j]);
2336: fprintf(ficlog," %lf",xit[j]);
2337: }
2338: printf("\n");
2339: fprintf(ficlog,"\n");
2340: #endif
2341: } /* end of t or directest negative */
2342: #ifdef POWELLNOF3INFF1TEST
2343: #else
2344: } /* end if (fptt < fp) */
2345: #endif
2346: #ifdef NODIRECTIONCHANGEDUNTILNITER /* No change in drections until some iterations are done */
2347: } /*NODIRECTIONCHANGEDUNTILNITER No change in drections until some iterations are done */
2348: #else
2349: #endif
2350: } /* loop iteration */
2351: }
2352:
2353: /**** Prevalence limit (stable or period prevalence) ****************/
2354:
2355: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
2356: {
2357: /* Computes the prevalence limit in each live state at age x and for covariate combination ij
2358: (and selected quantitative values in nres)
2359: by left multiplying the unit
2360: matrix by transitions matrix until convergence is reached with precision ftolpl */
2361: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2362: /* Wx is row vector: population in state 1, population in state 2, population dead */
2363: /* or prevalence in state 1, prevalence in state 2, 0 */
2364: /* newm is the matrix after multiplications, its rows are identical at a factor */
2365: /* Initial matrix pimij */
2366: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2367: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2368: /* 0, 0 , 1} */
2369: /*
2370: * and after some iteration: */
2371: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2372: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2373: /* 0, 0 , 1} */
2374: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2375: /* {0.51571254859325999, 0.4842874514067399, */
2376: /* 0.51326036147820708, 0.48673963852179264} */
2377: /* If we start from prlim again, prlim tends to a constant matrix */
2378:
2379: int i, ii,j,k;
2380: double *min, *max, *meandiff, maxmax,sumnew=0.;
2381: /* double **matprod2(); */ /* test */
2382: double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
2383: double **newm;
2384: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2385: int ncvloop=0;
2386:
2387: min=vector(1,nlstate);
2388: max=vector(1,nlstate);
2389: meandiff=vector(1,nlstate);
2390:
2391: /* Starting with matrix unity */
2392: for (ii=1;ii<=nlstate+ndeath;ii++)
2393: for (j=1;j<=nlstate+ndeath;j++){
2394: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2395: }
2396:
2397: cov[1]=1.;
2398:
2399: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2400: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2401: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2402: ncvloop++;
2403: newm=savm;
2404: /* Covariates have to be included here again */
2405: cov[2]=agefin;
2406: if(nagesqr==1)
2407: cov[3]= agefin*agefin;;
2408: for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
2409: /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
2410: cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
2411: /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
2412: }
2413: for (k=1; k<=nsq;k++) { /* For single varying covariates only */
2414: /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
2415: cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
2416: /* printf("prevalim Quantitative k=%d TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
2417: }
2418: for (k=1; k<=cptcovage;k++){ /* For product with age */
2419: if(Dummy[Tvar[Tage[k]]]){
2420: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2421: } else{
2422: cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
2423: }
2424: /* printf("prevalim Age combi=%d k=%d Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
2425: }
2426: for (k=1; k<=cptcovprod;k++){ /* For product without age */
2427: /* printf("prevalim Prod ij=%d k=%d Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
2428: if(Dummy[Tvard[k][1]==0]){
2429: if(Dummy[Tvard[k][2]==0]){
2430: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2431: }else{
2432: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
2433: }
2434: }else{
2435: if(Dummy[Tvard[k][2]==0]){
2436: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
2437: }else{
2438: cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]* Tqinvresult[nres][Tvard[k][2]];
2439: }
2440: }
2441: }
2442: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2443: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2444: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2445: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2446: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2447: /* age and covariate values of ij are in 'cov' */
2448: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2449:
2450: savm=oldm;
2451: oldm=newm;
2452:
2453: for(j=1; j<=nlstate; j++){
2454: max[j]=0.;
2455: min[j]=1.;
2456: }
2457: for(i=1;i<=nlstate;i++){
2458: sumnew=0;
2459: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2460: for(j=1; j<=nlstate; j++){
2461: prlim[i][j]= newm[i][j]/(1-sumnew);
2462: max[j]=FMAX(max[j],prlim[i][j]);
2463: min[j]=FMIN(min[j],prlim[i][j]);
2464: }
2465: }
2466:
2467: maxmax=0.;
2468: for(j=1; j<=nlstate; j++){
2469: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2470: maxmax=FMAX(maxmax,meandiff[j]);
2471: /* 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); */
2472: } /* j loop */
2473: *ncvyear= (int)age- (int)agefin;
2474: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2475: if(maxmax < ftolpl){
2476: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2477: free_vector(min,1,nlstate);
2478: free_vector(max,1,nlstate);
2479: free_vector(meandiff,1,nlstate);
2480: return prlim;
2481: }
2482: } /* age loop */
2483: /* After some age loop it doesn't converge */
2484: 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\
2485: 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);
2486: /* 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); */
2487: free_vector(min,1,nlstate);
2488: free_vector(max,1,nlstate);
2489: free_vector(meandiff,1,nlstate);
2490:
2491: return prlim; /* should not reach here */
2492: }
2493:
2494:
2495: /**** Back Prevalence limit (stable or period prevalence) ****************/
2496:
2497: /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
2498: /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
2499: double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
2500: {
2501: /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
2502: matrix by transitions matrix until convergence is reached with precision ftolpl */
2503: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2504: /* Wx is row vector: population in state 1, population in state 2, population dead */
2505: /* or prevalence in state 1, prevalence in state 2, 0 */
2506: /* newm is the matrix after multiplications, its rows are identical at a factor */
2507: /* Initial matrix pimij */
2508: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2509: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2510: /* 0, 0 , 1} */
2511: /*
2512: * and after some iteration: */
2513: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2514: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2515: /* 0, 0 , 1} */
2516: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2517: /* {0.51571254859325999, 0.4842874514067399, */
2518: /* 0.51326036147820708, 0.48673963852179264} */
2519: /* If we start from prlim again, prlim tends to a constant matrix */
2520:
2521: int i, ii,j,k;
2522: double *min, *max, *meandiff, maxmax,sumnew=0.;
2523: /* double **matprod2(); */ /* test */
2524: double **out, cov[NCOVMAX+1], **bmij();
2525: double **newm;
2526: double **dnewm, **doldm, **dsavm; /* for use */
2527: double **oldm, **savm; /* for use */
2528:
2529: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2530: int ncvloop=0;
2531:
2532: min=vector(1,nlstate);
2533: max=vector(1,nlstate);
2534: meandiff=vector(1,nlstate);
2535:
2536: dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
2537: oldm=oldms; savm=savms;
2538:
2539: /* Starting with matrix unity */
2540: for (ii=1;ii<=nlstate+ndeath;ii++)
2541: for (j=1;j<=nlstate+ndeath;j++){
2542: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2543: }
2544:
2545: cov[1]=1.;
2546:
2547: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2548: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2549: /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
2550: for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
2551: ncvloop++;
2552: newm=savm; /* oldm should be kept from previous iteration or unity at start */
2553: /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
2554: /* Covariates have to be included here again */
2555: cov[2]=agefin;
2556: if(nagesqr==1)
2557: cov[3]= agefin*agefin;;
2558: for (k=1; k<=cptcovn;k++) {
2559: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2560: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2561: /* 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])]); */
2562: }
2563: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2564: for (k=1; k<=cptcovprod;k++) /* Useless */
2565: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2566: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2567:
2568: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2569: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2570: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2571: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2572: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2573: /* ij should be linked to the correct index of cov */
2574: /* age and covariate values ij are in 'cov', but we need to pass
2575: * ij for the observed prevalence at age and status and covariate
2576: * number: prevacurrent[(int)agefin][ii][ij]
2577: */
2578: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
2579: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
2580: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
2581: savm=oldm;
2582: oldm=newm;
2583: for(j=1; j<=nlstate; j++){
2584: max[j]=0.;
2585: min[j]=1.;
2586: }
2587: for(j=1; j<=nlstate; j++){
2588: for(i=1;i<=nlstate;i++){
2589: /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
2590: bprlim[i][j]= newm[i][j];
2591: max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
2592: min[i]=FMIN(min[i],bprlim[i][j]);
2593: }
2594: }
2595:
2596: maxmax=0.;
2597: for(i=1; i<=nlstate; i++){
2598: meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
2599: maxmax=FMAX(maxmax,meandiff[i]);
2600: /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
2601: } /* j loop */
2602: *ncvyear= -( (int)age- (int)agefin);
2603: /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
2604: if(maxmax < ftolpl){
2605: /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2606: free_vector(min,1,nlstate);
2607: free_vector(max,1,nlstate);
2608: free_vector(meandiff,1,nlstate);
2609: return bprlim;
2610: }
2611: } /* age loop */
2612: /* After some age loop it doesn't converge */
2613: printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
2614: Oldest 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);
2615: /* 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); */
2616: free_vector(min,1,nlstate);
2617: free_vector(max,1,nlstate);
2618: free_vector(meandiff,1,nlstate);
2619:
2620: return bprlim; /* should not reach here */
2621: }
2622:
2623: /*************** transition probabilities ***************/
2624:
2625: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2626: {
2627: /* According to parameters values stored in x and the covariate's values stored in cov,
2628: computes the probability to be observed in state j being in state i by appying the
2629: model to the ncovmodel covariates (including constant and age).
2630: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2631: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2632: ncth covariate in the global vector x is given by the formula:
2633: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2634: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2635: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2636: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2637: Outputs ps[i][j] the probability to be observed in j being in j according to
2638: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2639: */
2640: double s1, lnpijopii;
2641: /*double t34;*/
2642: int i,j, nc, ii, jj;
2643:
2644: for(i=1; i<= nlstate; i++){
2645: for(j=1; j<i;j++){
2646: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2647: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2648: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2649: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2650: }
2651: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2652: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2653: }
2654: for(j=i+1; j<=nlstate+ndeath;j++){
2655: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2656: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2657: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2658: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2659: }
2660: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2661: }
2662: }
2663:
2664: for(i=1; i<= nlstate; i++){
2665: s1=0;
2666: for(j=1; j<i; j++){
2667: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2668: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2669: }
2670: for(j=i+1; j<=nlstate+ndeath; j++){
2671: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2672: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2673: }
2674: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2675: ps[i][i]=1./(s1+1.);
2676: /* Computing other pijs */
2677: for(j=1; j<i; j++)
2678: ps[i][j]= exp(ps[i][j])*ps[i][i];
2679: for(j=i+1; j<=nlstate+ndeath; j++)
2680: ps[i][j]= exp(ps[i][j])*ps[i][i];
2681: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2682: } /* end i */
2683:
2684: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2685: for(jj=1; jj<= nlstate+ndeath; jj++){
2686: ps[ii][jj]=0;
2687: ps[ii][ii]=1;
2688: }
2689: }
2690:
2691:
2692: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2693: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2694: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2695: /* } */
2696: /* printf("\n "); */
2697: /* } */
2698: /* printf("\n ");printf("%lf ",cov[2]);*/
2699: /*
2700: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2701: goto end;*/
2702: return ps;
2703: }
2704:
2705: /*************** backward transition probabilities ***************/
2706:
2707: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate, double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
2708: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate, double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
2709: double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate, double ***prevacurrent, int ij )
2710: {
2711: /* Computes the backward probability at age agefin and covariate ij
2712: * and returns in **ps as well as **bmij.
2713: */
2714: int i, ii, j,k;
2715:
2716: double **out, **pmij();
2717: double sumnew=0.;
2718: double agefin;
2719:
2720: double **dnewm, **dsavm, **doldm;
2721: double **bbmij;
2722:
2723: doldm=ddoldms; /* global pointers */
2724: dnewm=ddnewms;
2725: dsavm=ddsavms;
2726:
2727: agefin=cov[2];
2728: /* bmij *//* age is cov[2], ij is included in cov, but we need for
2729: the observed prevalence (with this covariate ij) */
2730: dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
2731: /* We do have the matrix Px in savm and we need pij */
2732: for (j=1;j<=nlstate+ndeath;j++){
2733: sumnew=0.; /* w1 p11 + w2 p21 only on live states */
2734: for (ii=1;ii<=nlstate;ii++){
2735: sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
2736: } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
2737: for (ii=1;ii<=nlstate+ndeath;ii++){
2738: if(sumnew >= 1.e-10){
2739: /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
2740: /* doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
2741: /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
2742: /* doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
2743: /* }else */
2744: doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
2745: }else{
2746: printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
2747: }
2748: } /*End ii */
2749: } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
2750: /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
2751: bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
2752: /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
2753: /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
2754: /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
2755: /* left Product of this matrix by diag matrix of prevalences (savm) */
2756: for (j=1;j<=nlstate+ndeath;j++){
2757: for (ii=1;ii<=nlstate+ndeath;ii++){
2758: dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
2759: }
2760: } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
2761: ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
2762: /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
2763: /* end bmij */
2764: return ps;
2765: }
2766: /*************** transition probabilities ***************/
2767:
2768: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2769: {
2770: /* According to parameters values stored in x and the covariate's values stored in cov,
2771: computes the probability to be observed in state j being in state i by appying the
2772: model to the ncovmodel covariates (including constant and age).
2773: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2774: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2775: ncth covariate in the global vector x is given by the formula:
2776: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2777: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2778: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2779: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2780: Outputs ps[i][j] the probability to be observed in j being in j according to
2781: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2782: */
2783: double s1, lnpijopii;
2784: /*double t34;*/
2785: int i,j, nc, ii, jj;
2786:
2787: for(i=1; i<= nlstate; i++){
2788: for(j=1; j<i;j++){
2789: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2790: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2791: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2792: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2793: }
2794: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2795: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2796: }
2797: for(j=i+1; j<=nlstate+ndeath;j++){
2798: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2799: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2800: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2801: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2802: }
2803: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2804: }
2805: }
2806:
2807: for(i=1; i<= nlstate; i++){
2808: s1=0;
2809: for(j=1; j<i; j++){
2810: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2811: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2812: }
2813: for(j=i+1; j<=nlstate+ndeath; j++){
2814: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2815: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2816: }
2817: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2818: ps[i][i]=1./(s1+1.);
2819: /* Computing other pijs */
2820: for(j=1; j<i; j++)
2821: ps[i][j]= exp(ps[i][j])*ps[i][i];
2822: for(j=i+1; j<=nlstate+ndeath; j++)
2823: ps[i][j]= exp(ps[i][j])*ps[i][i];
2824: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2825: } /* end i */
2826:
2827: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2828: for(jj=1; jj<= nlstate+ndeath; jj++){
2829: ps[ii][jj]=0;
2830: ps[ii][ii]=1;
2831: }
2832: }
2833: /* Added for backcast */ /* Transposed matrix too */
2834: for(jj=1; jj<= nlstate+ndeath; jj++){
2835: s1=0.;
2836: for(ii=1; ii<= nlstate+ndeath; ii++){
2837: s1+=ps[ii][jj];
2838: }
2839: for(ii=1; ii<= nlstate; ii++){
2840: ps[ii][jj]=ps[ii][jj]/s1;
2841: }
2842: }
2843: /* Transposition */
2844: for(jj=1; jj<= nlstate+ndeath; jj++){
2845: for(ii=jj; ii<= nlstate+ndeath; ii++){
2846: s1=ps[ii][jj];
2847: ps[ii][jj]=ps[jj][ii];
2848: ps[jj][ii]=s1;
2849: }
2850: }
2851: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2852: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2853: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2854: /* } */
2855: /* printf("\n "); */
2856: /* } */
2857: /* printf("\n ");printf("%lf ",cov[2]);*/
2858: /*
2859: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2860: goto end;*/
2861: return ps;
2862: }
2863:
2864:
2865: /**************** Product of 2 matrices ******************/
2866:
2867: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2868: {
2869: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2870: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2871: /* in, b, out are matrice of pointers which should have been initialized
2872: before: only the contents of out is modified. The function returns
2873: a pointer to pointers identical to out */
2874: int i, j, k;
2875: for(i=nrl; i<= nrh; i++)
2876: for(k=ncolol; k<=ncoloh; k++){
2877: out[i][k]=0.;
2878: for(j=ncl; j<=nch; j++)
2879: out[i][k] +=in[i][j]*b[j][k];
2880: }
2881: return out;
2882: }
2883:
2884:
2885: /************* Higher Matrix Product ***************/
2886:
2887: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
2888: {
2889: /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over
2890: 'nhstepm*hstepm*stepm' months (i.e. until
2891: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2892: nhstepm*hstepm matrices.
2893: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2894: (typically every 2 years instead of every month which is too big
2895: for the memory).
2896: Model is determined by parameters x and covariates have to be
2897: included manually here.
2898:
2899: */
2900:
2901: int i, j, d, h, k;
2902: double **out, cov[NCOVMAX+1];
2903: double **newm;
2904: double agexact;
2905: double agebegin, ageend;
2906:
2907: /* Hstepm could be zero and should return the unit matrix */
2908: for (i=1;i<=nlstate+ndeath;i++)
2909: for (j=1;j<=nlstate+ndeath;j++){
2910: oldm[i][j]=(i==j ? 1.0 : 0.0);
2911: po[i][j][0]=(i==j ? 1.0 : 0.0);
2912: }
2913: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2914: for(h=1; h <=nhstepm; h++){
2915: for(d=1; d <=hstepm; d++){
2916: newm=savm;
2917: /* Covariates have to be included here again */
2918: cov[1]=1.;
2919: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
2920: cov[2]=agexact;
2921: if(nagesqr==1)
2922: cov[3]= agexact*agexact;
2923: for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
2924: /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
2925: cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
2926: /* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
2927: }
2928: for (k=1; k<=nsq;k++) { /* For single varying covariates only */
2929: /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
2930: cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
2931: /* printf("hPxij Quantitative k=%d TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
2932: }
2933: for (k=1; k<=cptcovage;k++){
2934: if(Dummy[Tvar[Tage[k]]]){
2935: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2936: } else{
2937: cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
2938: }
2939: /* printf("hPxij Age combi=%d k=%d Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
2940: }
2941: for (k=1; k<=cptcovprod;k++){ /* */
2942: /* printf("hPxij Prod ij=%d k=%d Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
2943: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2944: }
2945: /* for (k=1; k<=cptcovn;k++) */
2946: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
2947: /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
2948: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
2949: /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
2950: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
2951:
2952:
2953: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2954: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2955: /* right multiplication of oldm by the current matrix */
2956: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2957: pmij(pmmij,cov,ncovmodel,x,nlstate));
2958: /* if((int)age == 70){ */
2959: /* printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
2960: /* for(i=1; i<=nlstate+ndeath; i++) { */
2961: /* printf("%d pmmij ",i); */
2962: /* for(j=1;j<=nlstate+ndeath;j++) { */
2963: /* printf("%f ",pmmij[i][j]); */
2964: /* } */
2965: /* printf(" oldm "); */
2966: /* for(j=1;j<=nlstate+ndeath;j++) { */
2967: /* printf("%f ",oldm[i][j]); */
2968: /* } */
2969: /* printf("\n"); */
2970: /* } */
2971: /* } */
2972: savm=oldm;
2973: oldm=newm;
2974: }
2975: for(i=1; i<=nlstate+ndeath; i++)
2976: for(j=1;j<=nlstate+ndeath;j++) {
2977: po[i][j][h]=newm[i][j];
2978: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2979: }
2980: /*printf("h=%d ",h);*/
2981: } /* end h */
2982: /* printf("\n H=%d \n",h); */
2983: return po;
2984: }
2985:
2986: /************* Higher Back Matrix Product ***************/
2987: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
2988: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
2989: {
2990: /* Computes the transition matrix starting at age 'age' over
2991: 'nhstepm*hstepm*stepm' months (i.e. until
2992: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2993: nhstepm*hstepm matrices.
2994: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2995: (typically every 2 years instead of every month which is too big
2996: for the memory).
2997: Model is determined by parameters x and covariates have to be
2998: included manually here.
2999:
3000: */
3001:
3002: int i, j, d, h, k;
3003: double **out, cov[NCOVMAX+1];
3004: double **newm;
3005: double agexact;
3006: double agebegin, ageend;
3007: double **oldm, **savm;
3008:
3009: oldm=oldms;savm=savms;
3010: /* Hstepm could be zero and should return the unit matrix */
3011: for (i=1;i<=nlstate+ndeath;i++)
3012: for (j=1;j<=nlstate+ndeath;j++){
3013: oldm[i][j]=(i==j ? 1.0 : 0.0);
3014: po[i][j][0]=(i==j ? 1.0 : 0.0);
3015: }
3016: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
3017: for(h=1; h <=nhstepm; h++){
3018: for(d=1; d <=hstepm; d++){
3019: newm=savm;
3020: /* Covariates have to be included here again */
3021: cov[1]=1.;
3022: agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
3023: /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
3024: cov[2]=agexact;
3025: if(nagesqr==1)
3026: cov[3]= agexact*agexact;
3027: for (k=1; k<=cptcovn;k++)
3028: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
3029: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
3030: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
3031: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
3032: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
3033: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
3034: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
3035: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
3036: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
3037:
3038:
3039: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
3040: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
3041: /* Careful transposed matrix */
3042: /* age is in cov[2] */
3043: /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
3044: /* 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
3045: out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
3046: 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
3047: /* if((int)age == 70){ */
3048: /* printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
3049: /* for(i=1; i<=nlstate+ndeath; i++) { */
3050: /* printf("%d pmmij ",i); */
3051: /* for(j=1;j<=nlstate+ndeath;j++) { */
3052: /* printf("%f ",pmmij[i][j]); */
3053: /* } */
3054: /* printf(" oldm "); */
3055: /* for(j=1;j<=nlstate+ndeath;j++) { */
3056: /* printf("%f ",oldm[i][j]); */
3057: /* } */
3058: /* printf("\n"); */
3059: /* } */
3060: /* } */
3061: savm=oldm;
3062: oldm=newm;
3063: }
3064: for(i=1; i<=nlstate+ndeath; i++)
3065: for(j=1;j<=nlstate+ndeath;j++) {
3066: po[i][j][h]=newm[i][j];
3067: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
3068: }
3069: /*printf("h=%d ",h);*/
3070: } /* end h */
3071: /* printf("\n H=%d \n",h); */
3072: return po;
3073: }
3074:
3075:
3076: #ifdef NLOPT
3077: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
3078: double fret;
3079: double *xt;
3080: int j;
3081: myfunc_data *d2 = (myfunc_data *) pd;
3082: /* xt = (p1-1); */
3083: xt=vector(1,n);
3084: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
3085:
3086: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
3087: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
3088: printf("Function = %.12lf ",fret);
3089: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
3090: printf("\n");
3091: free_vector(xt,1,n);
3092: return fret;
3093: }
3094: #endif
3095:
3096: /*************** log-likelihood *************/
3097: double func( double *x)
3098: {
3099: int i, ii, j, k, mi, d, kk;
3100: int ioffset=0;
3101: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
3102: double **out;
3103: double lli; /* Individual log likelihood */
3104: int s1, s2;
3105: int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
3106: double bbh, survp;
3107: long ipmx;
3108: double agexact;
3109: /*extern weight */
3110: /* We are differentiating ll according to initial status */
3111: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
3112: /*for(i=1;i<imx;i++)
3113: printf(" %d\n",s[4][i]);
3114: */
3115:
3116: ++countcallfunc;
3117:
3118: cov[1]=1.;
3119:
3120: for(k=1; k<=nlstate; k++) ll[k]=0.;
3121: ioffset=0;
3122: if(mle==1){
3123: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3124: /* Computes the values of the ncovmodel covariates of the model
3125: depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
3126: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
3127: to be observed in j being in i according to the model.
3128: */
3129: ioffset=2+nagesqr+cptcovage;
3130: /* Fixed */
3131: for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
3132: cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
3133: }
3134: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
3135: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
3136: has been calculated etc */
3137: /* For an individual i, wav[i] gives the number of effective waves */
3138: /* We compute the contribution to Likelihood of each effective transition
3139: mw[mi][i] is real wave of the mi th effectve wave */
3140: /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
3141: s2=s[mw[mi+1][i]][i];
3142: And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
3143: But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
3144: meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
3145: */
3146: for(mi=1; mi<= wav[i]-1; mi++){
3147: for(k=1; k <= ncovv ; k++){ /* Varying covariates (single and product but no age )*/
3148: cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
3149: }
3150: for (ii=1;ii<=nlstate+ndeath;ii++)
3151: for (j=1;j<=nlstate+ndeath;j++){
3152: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3153: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3154: }
3155: for(d=0; d<dh[mi][i]; d++){
3156: newm=savm;
3157: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3158: cov[2]=agexact;
3159: if(nagesqr==1)
3160: cov[3]= agexact*agexact; /* Should be changed here */
3161: for (kk=1; kk<=cptcovage;kk++) {
3162: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
3163: }
3164: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3165: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3166: savm=oldm;
3167: oldm=newm;
3168: } /* end mult */
3169:
3170: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
3171: /* But now since version 0.9 we anticipate for bias at large stepm.
3172: * If stepm is larger than one month (smallest stepm) and if the exact delay
3173: * (in months) between two waves is not a multiple of stepm, we rounded to
3174: * the nearest (and in case of equal distance, to the lowest) interval but now
3175: * we keep into memory the bias bh[mi][i] and also the previous matrix product
3176: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
3177: * probability in order to take into account the bias as a fraction of the way
3178: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
3179: * -stepm/2 to stepm/2 .
3180: * For stepm=1 the results are the same as for previous versions of Imach.
3181: * For stepm > 1 the results are less biased than in previous versions.
3182: */
3183: s1=s[mw[mi][i]][i];
3184: s2=s[mw[mi+1][i]][i];
3185: bbh=(double)bh[mi][i]/(double)stepm;
3186: /* bias bh is positive if real duration
3187: * is higher than the multiple of stepm and negative otherwise.
3188: */
3189: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
3190: if( s2 > nlstate){
3191: /* i.e. if s2 is a death state and if the date of death is known
3192: then the contribution to the likelihood is the probability to
3193: die between last step unit time and current step unit time,
3194: which is also equal to probability to die before dh
3195: minus probability to die before dh-stepm .
3196: In version up to 0.92 likelihood was computed
3197: as if date of death was unknown. Death was treated as any other
3198: health state: the date of the interview describes the actual state
3199: and not the date of a change in health state. The former idea was
3200: to consider that at each interview the state was recorded
3201: (healthy, disable or death) and IMaCh was corrected; but when we
3202: introduced the exact date of death then we should have modified
3203: the contribution of an exact death to the likelihood. This new
3204: contribution is smaller and very dependent of the step unit
3205: stepm. It is no more the probability to die between last interview
3206: and month of death but the probability to survive from last
3207: interview up to one month before death multiplied by the
3208: probability to die within a month. Thanks to Chris
3209: Jackson for correcting this bug. Former versions increased
3210: mortality artificially. The bad side is that we add another loop
3211: which slows down the processing. The difference can be up to 10%
3212: lower mortality.
3213: */
3214: /* If, at the beginning of the maximization mostly, the
3215: cumulative probability or probability to be dead is
3216: constant (ie = 1) over time d, the difference is equal to
3217: 0. out[s1][3] = savm[s1][3]: probability, being at state
3218: s1 at precedent wave, to be dead a month before current
3219: wave is equal to probability, being at state s1 at
3220: precedent wave, to be dead at mont of the current
3221: wave. Then the observed probability (that this person died)
3222: is null according to current estimated parameter. In fact,
3223: it should be very low but not zero otherwise the log go to
3224: infinity.
3225: */
3226: /* #ifdef INFINITYORIGINAL */
3227: /* lli=log(out[s1][s2] - savm[s1][s2]); */
3228: /* #else */
3229: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
3230: /* lli=log(mytinydouble); */
3231: /* else */
3232: /* lli=log(out[s1][s2] - savm[s1][s2]); */
3233: /* #endif */
3234: lli=log(out[s1][s2] - savm[s1][s2]);
3235:
3236: } else if ( s2==-1 ) { /* alive */
3237: for (j=1,survp=0. ; j<=nlstate; j++)
3238: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
3239: /*survp += out[s1][j]; */
3240: lli= log(survp);
3241: }
3242: else if (s2==-4) {
3243: for (j=3,survp=0. ; j<=nlstate; j++)
3244: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
3245: lli= log(survp);
3246: }
3247: else if (s2==-5) {
3248: for (j=1,survp=0. ; j<=2; j++)
3249: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
3250: lli= log(survp);
3251: }
3252: else{
3253: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
3254: /* 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 */
3255: }
3256: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
3257: /*if(lli ==000.0)*/
3258: /*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); */
3259: ipmx +=1;
3260: sw += weight[i];
3261: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3262: /* if (lli < log(mytinydouble)){ */
3263: /* 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); */
3264: /* 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]); */
3265: /* } */
3266: } /* end of wave */
3267: } /* end of individual */
3268: } else if(mle==2){
3269: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3270: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3271: for(mi=1; mi<= wav[i]-1; mi++){
3272: for (ii=1;ii<=nlstate+ndeath;ii++)
3273: for (j=1;j<=nlstate+ndeath;j++){
3274: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3275: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3276: }
3277: for(d=0; d<=dh[mi][i]; d++){
3278: newm=savm;
3279: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3280: cov[2]=agexact;
3281: if(nagesqr==1)
3282: cov[3]= agexact*agexact;
3283: for (kk=1; kk<=cptcovage;kk++) {
3284: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3285: }
3286: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3287: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3288: savm=oldm;
3289: oldm=newm;
3290: } /* end mult */
3291:
3292: s1=s[mw[mi][i]][i];
3293: s2=s[mw[mi+1][i]][i];
3294: bbh=(double)bh[mi][i]/(double)stepm;
3295: 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 */
3296: ipmx +=1;
3297: sw += weight[i];
3298: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3299: } /* end of wave */
3300: } /* end of individual */
3301: } else if(mle==3){ /* exponential inter-extrapolation */
3302: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3303: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3304: for(mi=1; mi<= wav[i]-1; mi++){
3305: for (ii=1;ii<=nlstate+ndeath;ii++)
3306: for (j=1;j<=nlstate+ndeath;j++){
3307: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3308: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3309: }
3310: for(d=0; d<dh[mi][i]; d++){
3311: newm=savm;
3312: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3313: cov[2]=agexact;
3314: if(nagesqr==1)
3315: cov[3]= agexact*agexact;
3316: for (kk=1; kk<=cptcovage;kk++) {
3317: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3318: }
3319: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3320: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3321: savm=oldm;
3322: oldm=newm;
3323: } /* end mult */
3324:
3325: s1=s[mw[mi][i]][i];
3326: s2=s[mw[mi+1][i]][i];
3327: bbh=(double)bh[mi][i]/(double)stepm;
3328: 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 */
3329: ipmx +=1;
3330: sw += weight[i];
3331: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3332: } /* end of wave */
3333: } /* end of individual */
3334: }else if (mle==4){ /* ml=4 no inter-extrapolation */
3335: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3336: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3337: for(mi=1; mi<= wav[i]-1; mi++){
3338: for (ii=1;ii<=nlstate+ndeath;ii++)
3339: for (j=1;j<=nlstate+ndeath;j++){
3340: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3341: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3342: }
3343: for(d=0; d<dh[mi][i]; d++){
3344: newm=savm;
3345: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3346: cov[2]=agexact;
3347: if(nagesqr==1)
3348: cov[3]= agexact*agexact;
3349: for (kk=1; kk<=cptcovage;kk++) {
3350: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3351: }
3352:
3353: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3354: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3355: savm=oldm;
3356: oldm=newm;
3357: } /* end mult */
3358:
3359: s1=s[mw[mi][i]][i];
3360: s2=s[mw[mi+1][i]][i];
3361: if( s2 > nlstate){
3362: lli=log(out[s1][s2] - savm[s1][s2]);
3363: } else if ( s2==-1 ) { /* alive */
3364: for (j=1,survp=0. ; j<=nlstate; j++)
3365: survp += out[s1][j];
3366: lli= log(survp);
3367: }else{
3368: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
3369: }
3370: ipmx +=1;
3371: sw += weight[i];
3372: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3373: /* 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]); */
3374: } /* end of wave */
3375: } /* end of individual */
3376: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
3377: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3378: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3379: for(mi=1; mi<= wav[i]-1; mi++){
3380: for (ii=1;ii<=nlstate+ndeath;ii++)
3381: for (j=1;j<=nlstate+ndeath;j++){
3382: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3383: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3384: }
3385: for(d=0; d<dh[mi][i]; d++){
3386: newm=savm;
3387: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3388: cov[2]=agexact;
3389: if(nagesqr==1)
3390: cov[3]= agexact*agexact;
3391: for (kk=1; kk<=cptcovage;kk++) {
3392: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3393: }
3394:
3395: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3396: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3397: savm=oldm;
3398: oldm=newm;
3399: } /* end mult */
3400:
3401: s1=s[mw[mi][i]][i];
3402: s2=s[mw[mi+1][i]][i];
3403: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
3404: ipmx +=1;
3405: sw += weight[i];
3406: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3407: /*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]);*/
3408: } /* end of wave */
3409: } /* end of individual */
3410: } /* End of if */
3411: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
3412: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
3413: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
3414: return -l;
3415: }
3416:
3417: /*************** log-likelihood *************/
3418: double funcone( double *x)
3419: {
3420: /* Same as func but slower because of a lot of printf and if */
3421: int i, ii, j, k, mi, d, kk;
3422: int ioffset=0;
3423: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
3424: double **out;
3425: double lli; /* Individual log likelihood */
3426: double llt;
3427: int s1, s2;
3428: int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
3429:
3430: double bbh, survp;
3431: double agexact;
3432: double agebegin, ageend;
3433: /*extern weight */
3434: /* We are differentiating ll according to initial status */
3435: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
3436: /*for(i=1;i<imx;i++)
3437: printf(" %d\n",s[4][i]);
3438: */
3439: cov[1]=1.;
3440:
3441: for(k=1; k<=nlstate; k++) ll[k]=0.;
3442: ioffset=0;
3443: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3444: ioffset=2+nagesqr+cptcovage;
3445: /* Fixed */
3446: /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
3447: /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
3448: for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
3449: cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
3450: /* cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i]; */
3451: /* cov[2+6]=covar[Tvar[6]][i]; */
3452: /* cov[2+6]=covar[2][i]; V2 */
3453: /* cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i]; */
3454: /* cov[2+7]=covar[Tvar[7]][i]; */
3455: /* cov[2+7]=covar[7][i]; V7=V1*V2 */
3456: /* cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i]; */
3457: /* cov[2+9]=covar[Tvar[9]][i]; */
3458: /* cov[2+9]=covar[1][i]; V1 */
3459: }
3460: /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
3461: /* cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
3462: /* } */
3463: /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
3464: /* cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
3465: /* } */
3466:
3467:
3468: for(mi=1; mi<= wav[i]-1; mi++){ /* Varying with waves */
3469: /* Wave varying (but not age varying) */
3470: for(k=1; k <= ncovv ; k++){ /* Varying covariates (single and product but no age )*/
3471: cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
3472: }
3473: /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
3474: /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
3475: /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
3476: /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
3477: /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
3478: /* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
3479: /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
3480: /* iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
3481: /* /\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
3482: /* cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
3483: /* } */
3484: for (ii=1;ii<=nlstate+ndeath;ii++)
3485: for (j=1;j<=nlstate+ndeath;j++){
3486: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3487: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3488: }
3489:
3490: agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
3491: ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
3492: for(d=0; d<dh[mi][i]; d++){ /* Delay between two effective waves */
3493: /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3494: and mw[mi+1][i]. dh depends on stepm.*/
3495: newm=savm;
3496: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3497: cov[2]=agexact;
3498: if(nagesqr==1)
3499: cov[3]= agexact*agexact;
3500: for (kk=1; kk<=cptcovage;kk++) {
3501: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3502: }
3503: /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
3504: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
3505: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3506: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3507: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
3508: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
3509: savm=oldm;
3510: oldm=newm;
3511: } /* end mult */
3512:
3513: s1=s[mw[mi][i]][i];
3514: s2=s[mw[mi+1][i]][i];
3515: /* if(s2==-1){ */
3516: /* printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
3517: /* /\* exit(1); *\/ */
3518: /* } */
3519: bbh=(double)bh[mi][i]/(double)stepm;
3520: /* bias is positive if real duration
3521: * is higher than the multiple of stepm and negative otherwise.
3522: */
3523: if( s2 > nlstate && (mle <5) ){ /* Jackson */
3524: lli=log(out[s1][s2] - savm[s1][s2]);
3525: } else if ( s2==-1 ) { /* alive */
3526: for (j=1,survp=0. ; j<=nlstate; j++)
3527: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
3528: lli= log(survp);
3529: }else if (mle==1){
3530: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
3531: } else if(mle==2){
3532: 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 */
3533: } else if(mle==3){ /* exponential inter-extrapolation */
3534: 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 */
3535: } else if (mle==4){ /* mle=4 no inter-extrapolation */
3536: lli=log(out[s1][s2]); /* Original formula */
3537: } else{ /* mle=0 back to 1 */
3538: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
3539: /*lli=log(out[s1][s2]); */ /* Original formula */
3540: } /* End of if */
3541: ipmx +=1;
3542: sw += weight[i];
3543: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3544: /*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]); */
3545: if(globpr){
3546: fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
3547: %11.6f %11.6f %11.6f ", \
3548: num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
3549: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
3550: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
3551: llt +=ll[k]*gipmx/gsw;
3552: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
3553: }
3554: fprintf(ficresilk," %10.6f\n", -llt);
3555: }
3556: } /* end of wave */
3557: } /* end of individual */
3558: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
3559: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
3560: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
3561: if(globpr==0){ /* First time we count the contributions and weights */
3562: gipmx=ipmx;
3563: gsw=sw;
3564: }
3565: return -l;
3566: }
3567:
3568:
3569: /*************** function likelione ***********/
3570: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
3571: {
3572: /* This routine should help understanding what is done with
3573: the selection of individuals/waves and
3574: to check the exact contribution to the likelihood.
3575: Plotting could be done.
3576: */
3577: int k;
3578:
3579: if(*globpri !=0){ /* Just counts and sums, no printings */
3580: strcpy(fileresilk,"ILK_");
3581: strcat(fileresilk,fileresu);
3582: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
3583: printf("Problem with resultfile: %s\n", fileresilk);
3584: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
3585: }
3586: 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");
3587: fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
3588: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
3589: for(k=1; k<=nlstate; k++)
3590: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
3591: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
3592: }
3593:
3594: *fretone=(*funcone)(p);
3595: if(*globpri !=0){
3596: fclose(ficresilk);
3597: if (mle ==0)
3598: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
3599: else if(mle >=1)
3600: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
3601: 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));
3602:
3603:
3604: for (k=1; k<= nlstate ; k++) {
3605: 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> \
3606: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
3607: }
3608: 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> \
3609: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
3610: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
3611: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
3612: fflush(fichtm);
3613: }
3614: return;
3615: }
3616:
3617:
3618: /*********** Maximum Likelihood Estimation ***************/
3619:
3620: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
3621: {
3622: int i,j, iter=0;
3623: double **xi;
3624: double fret;
3625: double fretone; /* Only one call to likelihood */
3626: /* char filerespow[FILENAMELENGTH];*/
3627:
3628: #ifdef NLOPT
3629: int creturn;
3630: nlopt_opt opt;
3631: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
3632: double *lb;
3633: double minf; /* the minimum objective value, upon return */
3634: double * p1; /* Shifted parameters from 0 instead of 1 */
3635: myfunc_data dinst, *d = &dinst;
3636: #endif
3637:
3638:
3639: xi=matrix(1,npar,1,npar);
3640: for (i=1;i<=npar;i++)
3641: for (j=1;j<=npar;j++)
3642: xi[i][j]=(i==j ? 1.0 : 0.0);
3643: printf("Powell\n"); fprintf(ficlog,"Powell\n");
3644: strcpy(filerespow,"POW_");
3645: strcat(filerespow,fileres);
3646: if((ficrespow=fopen(filerespow,"w"))==NULL) {
3647: printf("Problem with resultfile: %s\n", filerespow);
3648: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
3649: }
3650: fprintf(ficrespow,"# Powell\n# iter -2*LL");
3651: for (i=1;i<=nlstate;i++)
3652: for(j=1;j<=nlstate+ndeath;j++)
3653: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
3654: fprintf(ficrespow,"\n");
3655: #ifdef POWELL
3656: powell(p,xi,npar,ftol,&iter,&fret,func);
3657: #endif
3658:
3659: #ifdef NLOPT
3660: #ifdef NEWUOA
3661: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
3662: #else
3663: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
3664: #endif
3665: lb=vector(0,npar-1);
3666: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
3667: nlopt_set_lower_bounds(opt, lb);
3668: nlopt_set_initial_step1(opt, 0.1);
3669:
3670: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
3671: d->function = func;
3672: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
3673: nlopt_set_min_objective(opt, myfunc, d);
3674: nlopt_set_xtol_rel(opt, ftol);
3675: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
3676: printf("nlopt failed! %d\n",creturn);
3677: }
3678: else {
3679: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
3680: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
3681: iter=1; /* not equal */
3682: }
3683: nlopt_destroy(opt);
3684: #endif
3685: free_matrix(xi,1,npar,1,npar);
3686: fclose(ficrespow);
3687: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3688: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3689: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3690:
3691: }
3692:
3693: /**** Computes Hessian and covariance matrix ***/
3694: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
3695: {
3696: double **a,**y,*x,pd;
3697: /* double **hess; */
3698: int i, j;
3699: int *indx;
3700:
3701: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
3702: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
3703: void lubksb(double **a, int npar, int *indx, double b[]) ;
3704: void ludcmp(double **a, int npar, int *indx, double *d) ;
3705: double gompertz(double p[]);
3706: /* hess=matrix(1,npar,1,npar); */
3707:
3708: printf("\nCalculation of the hessian matrix. Wait...\n");
3709: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
3710: for (i=1;i<=npar;i++){
3711: printf("%d-",i);fflush(stdout);
3712: fprintf(ficlog,"%d-",i);fflush(ficlog);
3713:
3714: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
3715:
3716: /* printf(" %f ",p[i]);
3717: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
3718: }
3719:
3720: for (i=1;i<=npar;i++) {
3721: for (j=1;j<=npar;j++) {
3722: if (j>i) {
3723: printf(".%d-%d",i,j);fflush(stdout);
3724: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
3725: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
3726:
3727: hess[j][i]=hess[i][j];
3728: /*printf(" %lf ",hess[i][j]);*/
3729: }
3730: }
3731: }
3732: printf("\n");
3733: fprintf(ficlog,"\n");
3734:
3735: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
3736: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
3737:
3738: a=matrix(1,npar,1,npar);
3739: y=matrix(1,npar,1,npar);
3740: x=vector(1,npar);
3741: indx=ivector(1,npar);
3742: for (i=1;i<=npar;i++)
3743: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
3744: ludcmp(a,npar,indx,&pd);
3745:
3746: for (j=1;j<=npar;j++) {
3747: for (i=1;i<=npar;i++) x[i]=0;
3748: x[j]=1;
3749: lubksb(a,npar,indx,x);
3750: for (i=1;i<=npar;i++){
3751: matcov[i][j]=x[i];
3752: }
3753: }
3754:
3755: printf("\n#Hessian matrix#\n");
3756: fprintf(ficlog,"\n#Hessian matrix#\n");
3757: for (i=1;i<=npar;i++) {
3758: for (j=1;j<=npar;j++) {
3759: printf("%.6e ",hess[i][j]);
3760: fprintf(ficlog,"%.6e ",hess[i][j]);
3761: }
3762: printf("\n");
3763: fprintf(ficlog,"\n");
3764: }
3765:
3766: /* printf("\n#Covariance matrix#\n"); */
3767: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
3768: /* for (i=1;i<=npar;i++) { */
3769: /* for (j=1;j<=npar;j++) { */
3770: /* printf("%.6e ",matcov[i][j]); */
3771: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
3772: /* } */
3773: /* printf("\n"); */
3774: /* fprintf(ficlog,"\n"); */
3775: /* } */
3776:
3777: /* Recompute Inverse */
3778: /* for (i=1;i<=npar;i++) */
3779: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
3780: /* ludcmp(a,npar,indx,&pd); */
3781:
3782: /* printf("\n#Hessian matrix recomputed#\n"); */
3783:
3784: /* for (j=1;j<=npar;j++) { */
3785: /* for (i=1;i<=npar;i++) x[i]=0; */
3786: /* x[j]=1; */
3787: /* lubksb(a,npar,indx,x); */
3788: /* for (i=1;i<=npar;i++){ */
3789: /* y[i][j]=x[i]; */
3790: /* printf("%.3e ",y[i][j]); */
3791: /* fprintf(ficlog,"%.3e ",y[i][j]); */
3792: /* } */
3793: /* printf("\n"); */
3794: /* fprintf(ficlog,"\n"); */
3795: /* } */
3796:
3797: /* Verifying the inverse matrix */
3798: #ifdef DEBUGHESS
3799: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
3800:
3801: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
3802: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
3803:
3804: for (j=1;j<=npar;j++) {
3805: for (i=1;i<=npar;i++){
3806: printf("%.2f ",y[i][j]);
3807: fprintf(ficlog,"%.2f ",y[i][j]);
3808: }
3809: printf("\n");
3810: fprintf(ficlog,"\n");
3811: }
3812: #endif
3813:
3814: free_matrix(a,1,npar,1,npar);
3815: free_matrix(y,1,npar,1,npar);
3816: free_vector(x,1,npar);
3817: free_ivector(indx,1,npar);
3818: /* free_matrix(hess,1,npar,1,npar); */
3819:
3820:
3821: }
3822:
3823: /*************** hessian matrix ****************/
3824: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
3825: { /* Around values of x, computes the function func and returns the scales delti and hessian */
3826: int i;
3827: int l=1, lmax=20;
3828: double k1,k2, res, fx;
3829: double p2[MAXPARM+1]; /* identical to x */
3830: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
3831: int k=0,kmax=10;
3832: double l1;
3833:
3834: fx=func(x);
3835: for (i=1;i<=npar;i++) p2[i]=x[i];
3836: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
3837: l1=pow(10,l);
3838: delts=delt;
3839: for(k=1 ; k <kmax; k=k+1){
3840: delt = delta*(l1*k);
3841: p2[theta]=x[theta] +delt;
3842: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
3843: p2[theta]=x[theta]-delt;
3844: k2=func(p2)-fx;
3845: /*res= (k1-2.0*fx+k2)/delt/delt; */
3846: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
3847:
3848: #ifdef DEBUGHESSII
3849: 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);
3850: 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);
3851: #endif
3852: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3853: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3854: k=kmax;
3855: }
3856: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
3857: k=kmax; l=lmax*10;
3858: }
3859: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3860: delts=delt;
3861: }
3862: } /* End loop k */
3863: }
3864: delti[theta]=delts;
3865: return res;
3866:
3867: }
3868:
3869: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
3870: {
3871: int i;
3872: int l=1, lmax=20;
3873: double k1,k2,k3,k4,res,fx;
3874: double p2[MAXPARM+1];
3875: int k, kmax=1;
3876: double v1, v2, cv12, lc1, lc2;
3877:
3878: int firstime=0;
3879:
3880: fx=func(x);
3881: for (k=1; k<=kmax; k=k+10) {
3882: for (i=1;i<=npar;i++) p2[i]=x[i];
3883: p2[thetai]=x[thetai]+delti[thetai]*k;
3884: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3885: k1=func(p2)-fx;
3886:
3887: p2[thetai]=x[thetai]+delti[thetai]*k;
3888: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3889: k2=func(p2)-fx;
3890:
3891: p2[thetai]=x[thetai]-delti[thetai]*k;
3892: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3893: k3=func(p2)-fx;
3894:
3895: p2[thetai]=x[thetai]-delti[thetai]*k;
3896: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3897: k4=func(p2)-fx;
3898: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3899: if(k1*k2*k3*k4 <0.){
3900: firstime=1;
3901: kmax=kmax+10;
3902: }
3903: if(kmax >=10 || firstime ==1){
3904: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
3905: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
3906: 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);
3907: 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);
3908: }
3909: #ifdef DEBUGHESSIJ
3910: v1=hess[thetai][thetai];
3911: v2=hess[thetaj][thetaj];
3912: cv12=res;
3913: /* Computing eigen value of Hessian matrix */
3914: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3915: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3916: if ((lc2 <0) || (lc1 <0) ){
3917: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3918: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3919: 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);
3920: 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);
3921: }
3922: #endif
3923: }
3924: return res;
3925: }
3926:
3927: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3928: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3929: /* { */
3930: /* int i; */
3931: /* int l=1, lmax=20; */
3932: /* double k1,k2,k3,k4,res,fx; */
3933: /* double p2[MAXPARM+1]; */
3934: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3935: /* int k=0,kmax=10; */
3936: /* double l1; */
3937:
3938: /* fx=func(x); */
3939: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3940: /* l1=pow(10,l); */
3941: /* delts=delt; */
3942: /* for(k=1 ; k <kmax; k=k+1){ */
3943: /* delt = delti*(l1*k); */
3944: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3945: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3946: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3947: /* k1=func(p2)-fx; */
3948:
3949: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3950: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3951: /* k2=func(p2)-fx; */
3952:
3953: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3954: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3955: /* k3=func(p2)-fx; */
3956:
3957: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3958: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3959: /* k4=func(p2)-fx; */
3960: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3961: /* #ifdef DEBUGHESSIJ */
3962: /* 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); */
3963: /* 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); */
3964: /* #endif */
3965: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3966: /* k=kmax; */
3967: /* } */
3968: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3969: /* k=kmax; l=lmax*10; */
3970: /* } */
3971: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3972: /* delts=delt; */
3973: /* } */
3974: /* } /\* End loop k *\/ */
3975: /* } */
3976: /* delti[theta]=delts; */
3977: /* return res; */
3978: /* } */
3979:
3980:
3981: /************** Inverse of matrix **************/
3982: void ludcmp(double **a, int n, int *indx, double *d)
3983: {
3984: int i,imax,j,k;
3985: double big,dum,sum,temp;
3986: double *vv;
3987:
3988: vv=vector(1,n);
3989: *d=1.0;
3990: for (i=1;i<=n;i++) {
3991: big=0.0;
3992: for (j=1;j<=n;j++)
3993: if ((temp=fabs(a[i][j])) > big) big=temp;
3994: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3995: vv[i]=1.0/big;
3996: }
3997: for (j=1;j<=n;j++) {
3998: for (i=1;i<j;i++) {
3999: sum=a[i][j];
4000: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
4001: a[i][j]=sum;
4002: }
4003: big=0.0;
4004: for (i=j;i<=n;i++) {
4005: sum=a[i][j];
4006: for (k=1;k<j;k++)
4007: sum -= a[i][k]*a[k][j];
4008: a[i][j]=sum;
4009: if ( (dum=vv[i]*fabs(sum)) >= big) {
4010: big=dum;
4011: imax=i;
4012: }
4013: }
4014: if (j != imax) {
4015: for (k=1;k<=n;k++) {
4016: dum=a[imax][k];
4017: a[imax][k]=a[j][k];
4018: a[j][k]=dum;
4019: }
4020: *d = -(*d);
4021: vv[imax]=vv[j];
4022: }
4023: indx[j]=imax;
4024: if (a[j][j] == 0.0) a[j][j]=TINY;
4025: if (j != n) {
4026: dum=1.0/(a[j][j]);
4027: for (i=j+1;i<=n;i++) a[i][j] *= dum;
4028: }
4029: }
4030: free_vector(vv,1,n); /* Doesn't work */
4031: ;
4032: }
4033:
4034: void lubksb(double **a, int n, int *indx, double b[])
4035: {
4036: int i,ii=0,ip,j;
4037: double sum;
4038:
4039: for (i=1;i<=n;i++) {
4040: ip=indx[i];
4041: sum=b[ip];
4042: b[ip]=b[i];
4043: if (ii)
4044: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
4045: else if (sum) ii=i;
4046: b[i]=sum;
4047: }
4048: for (i=n;i>=1;i--) {
4049: sum=b[i];
4050: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
4051: b[i]=sum/a[i][i];
4052: }
4053: }
4054:
4055: void pstamp(FILE *fichier)
4056: {
4057: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
4058: }
4059:
4060: /************ Frequencies ********************/
4061: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
4062: int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
4063: int firstpass, int lastpass, int stepm, int weightopt, char model[])
4064: { /* Some frequencies */
4065:
4066: int i, m, jk, j1, bool, z1,j, k, iv;
4067: int iind=0, iage=0;
4068: int mi; /* Effective wave */
4069: int first;
4070: double ***freq; /* Frequencies */
4071: double *meanq;
4072: double **meanqt;
4073: double *pp, **prop, *posprop, *pospropt;
4074: double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
4075: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
4076: double agebegin, ageend;
4077:
4078: pp=vector(1,nlstate);
4079: prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
4080: posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */
4081: pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */
4082: /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
4083: meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
4084: meanqt=matrix(1,lastpass,1,nqtveff);
4085: strcpy(fileresp,"P_");
4086: strcat(fileresp,fileresu);
4087: /*strcat(fileresphtm,fileresu);*/
4088: if((ficresp=fopen(fileresp,"w"))==NULL) {
4089: printf("Problem with prevalence resultfile: %s\n", fileresp);
4090: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
4091: exit(0);
4092: }
4093:
4094: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
4095: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
4096: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
4097: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
4098: fflush(ficlog);
4099: exit(70);
4100: }
4101: else{
4102: fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
4103: <hr size=\"2\" color=\"#EC5E5E\"> \n\
4104: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
4105: fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
4106: }
4107: fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
4108:
4109: strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
4110: if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
4111: printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
4112: fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
4113: fflush(ficlog);
4114: exit(70);
4115: }
4116: else{
4117: fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
4118: <hr size=\"2\" color=\"#EC5E5E\"> \n\
4119: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
4120: fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
4121: }
4122: 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);
4123:
4124: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
4125: j1=0;
4126:
4127: /* j=ncoveff; /\* Only fixed dummy covariates *\/ */
4128: j=cptcoveff; /* Only dummy covariates of the model */
4129: if (cptcovn<1) {j=1;ncodemax[1]=1;}
4130:
4131: first=1;
4132:
4133: /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
4134: reference=low_education V1=0,V2=0
4135: med_educ V1=1 V2=0,
4136: high_educ V1=0 V2=1
4137: Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff
4138: */
4139:
4140: for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
4141: posproptt=0.;
4142: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
4143: scanf("%d", i);*/
4144: for (i=-5; i<=nlstate+ndeath; i++)
4145: for (jk=-5; jk<=nlstate+ndeath; jk++)
4146: for(m=iagemin; m <= iagemax+3; m++)
4147: freq[i][jk][m]=0;
4148:
4149: for (i=1; i<=nlstate; i++) {
4150: for(m=iagemin; m <= iagemax+3; m++)
4151: prop[i][m]=0;
4152: posprop[i]=0;
4153: pospropt[i]=0;
4154: }
4155: /* for (z1=1; z1<= nqfveff; z1++) { */
4156: /* meanq[z1]+=0.; */
4157: /* for(m=1;m<=lastpass;m++){ */
4158: /* meanqt[m][z1]=0.; */
4159: /* } */
4160: /* } */
4161:
4162: dateintsum=0;
4163: k2cpt=0;
4164: /* For that combination of covariate j1, we count and print the frequencies in one pass */
4165: for (iind=1; iind<=imx; iind++) { /* For each individual iind */
4166: bool=1;
4167: if(anyvaryingduminmodel==0){ /* If All fixed covariates */
4168: if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
4169: /* for (z1=1; z1<= nqfveff; z1++) { */
4170: /* meanq[z1]+=coqvar[Tvar[z1]][iind]; /\* Computes mean of quantitative with selected filter *\/ */
4171: /* } */
4172: for (z1=1; z1<=cptcoveff; z1++) {
4173: /* if(Tvaraff[z1] ==-20){ */
4174: /* /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
4175: /* }else if(Tvaraff[z1] ==-10){ */
4176: /* /\* sumnew+=coqvar[z1][iind]; *\/ */
4177: /* }else */
4178: if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
4179: /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
4180: bool=0;
4181: /* 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",
4182: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
4183: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
4184: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
4185: } /* Onlyf fixed */
4186: } /* end z1 */
4187: } /* cptcovn > 0 */
4188: } /* end any */
4189: if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
4190: /* for(m=firstpass; m<=lastpass; m++){ */
4191: for(mi=1; mi<wav[iind];mi++){ /* For that wave */
4192: m=mw[mi][iind];
4193: if(anyvaryingduminmodel==1){ /* Some are varying covariates */
4194: for (z1=1; z1<=cptcoveff; z1++) {
4195: if( Fixed[Tmodelind[z1]]==1){
4196: iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
4197: if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
4198: bool=0;
4199: }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
4200: if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
4201: bool=0;
4202: }
4203: }
4204: }
4205: }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop */
4206: /* bool =0 we keep that guy which corresponds to the combination of dummy values */
4207: if(bool==1){
4208: /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
4209: and mw[mi+1][iind]. dh depends on stepm. */
4210: agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
4211: ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
4212: if(m >=firstpass && m <=lastpass){
4213: k2=anint[m][iind]+(mint[m][iind]/12.);
4214: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
4215: if(agev[m][iind]==0) agev[m][iind]=iagemax+1; /* All ages equal to 0 are in iagemax+1 */
4216: if(agev[m][iind]==1) agev[m][iind]=iagemax+2; /* All ages equal to 1 are in iagemax+2 */
4217: if (s[m][iind]>0 && s[m][iind]<=nlstate) /* If status at wave m is known and a live state */
4218: prop[s[m][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
4219: if (m<lastpass) {
4220: /* if(s[m][iind]==4 && s[m+1][iind]==4) */
4221: /* printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
4222: if(s[m][iind]==-1)
4223: printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
4224: freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
4225: /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
4226: freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
4227: }
4228: } /* end if between passes */
4229: if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
4230: dateintsum=dateintsum+k2;
4231: k2cpt++;
4232: /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
4233: }
4234: } /* end bool 2 */
4235: } /* end m */
4236: } /* end bool */
4237: } /* end iind = 1 to imx */
4238: /* prop[s][age] is feeded for any initial and valid live state as well as
4239: freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
4240:
4241:
4242: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
4243: pstamp(ficresp);
4244: /* if (ncoveff>0) { */
4245: if (cptcoveff>0) {
4246: fprintf(ficresp, "\n#********** Variable ");
4247: fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable ");
4248: fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable ");
4249: for (z1=1; z1<=cptcoveff; z1++){
4250: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4251: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4252: fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4253: }
4254: fprintf(ficresp, "**********\n#");
4255: fprintf(ficresphtm, "**********</h3>\n");
4256: fprintf(ficresphtmfr, "**********</h3>\n");
4257: fprintf(ficlog, "\n#********** Variable ");
4258: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4259: fprintf(ficlog, "**********\n");
4260: }
4261: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
4262: for(i=1; i<=nlstate;i++) {
4263: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
4264: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
4265: }
4266: fprintf(ficresp, "\n");
4267: fprintf(ficresphtm, "\n");
4268:
4269: /* Header of frequency table by age */
4270: fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
4271: fprintf(ficresphtmfr,"<th>Age</th> ");
4272: for(jk=-1; jk <=nlstate+ndeath; jk++){
4273: for(m=-1; m <=nlstate+ndeath; m++){
4274: if(jk!=0 && m!=0)
4275: fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
4276: }
4277: }
4278: fprintf(ficresphtmfr, "\n");
4279:
4280: /* For each age */
4281: for(iage=iagemin; iage <= iagemax+3; iage++){
4282: fprintf(ficresphtm,"<tr>");
4283: if(iage==iagemax+1){
4284: fprintf(ficlog,"1");
4285: fprintf(ficresphtmfr,"<tr><th>0</th> ");
4286: }else if(iage==iagemax+2){
4287: fprintf(ficlog,"0");
4288: fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
4289: }else if(iage==iagemax+3){
4290: fprintf(ficlog,"Total");
4291: fprintf(ficresphtmfr,"<tr><th>Total</th> ");
4292: }else{
4293: if(first==1){
4294: first=0;
4295: printf("See log file for details...\n");
4296: }
4297: fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
4298: fprintf(ficlog,"Age %d", iage);
4299: }
4300: for(jk=1; jk <=nlstate ; jk++){
4301: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
4302: pp[jk] += freq[jk][m][iage];
4303: }
4304: for(jk=1; jk <=nlstate ; jk++){
4305: for(m=-1, pos=0; m <=0 ; m++)
4306: pos += freq[jk][m][iage];
4307: if(pp[jk]>=1.e-10){
4308: if(first==1){
4309: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
4310: }
4311: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
4312: }else{
4313: if(first==1)
4314: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
4315: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
4316: }
4317: }
4318:
4319: for(jk=1; jk <=nlstate ; jk++){
4320: /* posprop[jk]=0; */
4321: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
4322: pp[jk] += freq[jk][m][iage];
4323: } /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
4324:
4325: for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
4326: pos += pp[jk]; /* pos is the total number of transitions until this age */
4327: posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
4328: from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
4329: pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
4330: from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
4331: }
4332: for(jk=1; jk <=nlstate ; jk++){
4333: if(pos>=1.e-5){
4334: if(first==1)
4335: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
4336: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
4337: }else{
4338: if(first==1)
4339: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
4340: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
4341: }
4342: if( iage <= iagemax){
4343: if(pos>=1.e-5){
4344: fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
4345: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
4346: /*probs[iage][jk][j1]= pp[jk]/pos;*/
4347: /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
4348: }
4349: else{
4350: fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
4351: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
4352: }
4353: }
4354: pospropt[jk] +=posprop[jk];
4355: } /* end loop jk */
4356: /* pospropt=0.; */
4357: for(jk=-1; jk <=nlstate+ndeath; jk++){
4358: for(m=-1; m <=nlstate+ndeath; m++){
4359: if(freq[jk][m][iage] !=0 ) { /* minimizing output */
4360: if(first==1){
4361: printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
4362: }
4363: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
4364: }
4365: if(jk!=0 && m!=0)
4366: fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
4367: }
4368: } /* end loop jk */
4369: posproptt=0.;
4370: for(jk=1; jk <=nlstate; jk++){
4371: posproptt += pospropt[jk];
4372: }
4373: fprintf(ficresphtmfr,"</tr>\n ");
4374: if(iage <= iagemax){
4375: fprintf(ficresp,"\n");
4376: fprintf(ficresphtm,"</tr>\n");
4377: }
4378: if(first==1)
4379: printf("Others in log...\n");
4380: fprintf(ficlog,"\n");
4381: } /* end loop age iage */
4382: fprintf(ficresphtm,"<tr><th>Tot</th>");
4383: for(jk=1; jk <=nlstate ; jk++){
4384: if(posproptt < 1.e-5){
4385: fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);
4386: }else{
4387: fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);
4388: }
4389: }
4390: fprintf(ficresphtm,"</tr>\n");
4391: fprintf(ficresphtm,"</table>\n");
4392: fprintf(ficresphtmfr,"</table>\n");
4393: if(posproptt < 1.e-5){
4394: fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
4395: fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
4396: fprintf(ficres,"\n This combination (%d) is not valid and no result will be produced\n\n",j1);
4397: invalidvarcomb[j1]=1;
4398: }else{
4399: fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
4400: invalidvarcomb[j1]=0;
4401: }
4402: fprintf(ficresphtmfr,"</table>\n");
4403: } /* end selected combination of covariate j1 */
4404: dateintmean=dateintsum/k2cpt;
4405:
4406: fclose(ficresp);
4407: fclose(ficresphtm);
4408: fclose(ficresphtmfr);
4409: free_vector(meanq,1,nqfveff);
4410: free_matrix(meanqt,1,lastpass,1,nqtveff);
4411: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
4412: free_vector(pospropt,1,nlstate);
4413: free_vector(posprop,1,nlstate);
4414: free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
4415: free_vector(pp,1,nlstate);
4416: /* End of freqsummary */
4417: }
4418:
4419: /************ Prevalence ********************/
4420: 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)
4421: {
4422: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
4423: in each health status at the date of interview (if between dateprev1 and dateprev2).
4424: We still use firstpass and lastpass as another selection.
4425: */
4426:
4427: int i, m, jk, j1, bool, z1,j, iv;
4428: int mi; /* Effective wave */
4429: int iage;
4430: double agebegin, ageend;
4431:
4432: double **prop;
4433: double posprop;
4434: double y2; /* in fractional years */
4435: int iagemin, iagemax;
4436: int first; /** to stop verbosity which is redirected to log file */
4437:
4438: iagemin= (int) agemin;
4439: iagemax= (int) agemax;
4440: /*pp=vector(1,nlstate);*/
4441: prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
4442: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
4443: j1=0;
4444:
4445: /*j=cptcoveff;*/
4446: if (cptcovn<1) {j=1;ncodemax[1]=1;}
4447:
4448: first=1;
4449: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
4450: for (i=1; i<=nlstate; i++)
4451: for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
4452: prop[i][iage]=0.0;
4453: printf("Prevalence combination of varying and fixed dummies %d\n",j1);
4454: /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
4455: fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
4456:
4457: for (i=1; i<=imx; i++) { /* Each individual */
4458: bool=1;
4459: /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
4460: for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
4461: m=mw[mi][i];
4462: /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
4463: /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
4464: for (z1=1; z1<=cptcoveff; z1++){
4465: if( Fixed[Tmodelind[z1]]==1){
4466: iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
4467: if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
4468: bool=0;
4469: }else if( Fixed[Tmodelind[z1]]== 0) /* fixed */
4470: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
4471: bool=0;
4472: }
4473: }
4474: if(bool==1){ /* Otherwise we skip that wave/person */
4475: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
4476: /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
4477: if(m >=firstpass && m <=lastpass){
4478: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
4479: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
4480: if(agev[m][i]==0) agev[m][i]=iagemax+1;
4481: if(agev[m][i]==1) agev[m][i]=iagemax+2;
4482: if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
4483: printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m);
4484: exit(1);
4485: }
4486: if (s[m][i]>0 && s[m][i]<=nlstate) {
4487: /*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]]);*/
4488: prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
4489: prop[s[m][i]][iagemax+3] += weight[i];
4490: } /* end valid statuses */
4491: } /* end selection of dates */
4492: } /* end selection of waves */
4493: } /* end bool */
4494: } /* end wave */
4495: } /* end individual */
4496: for(i=iagemin; i <= iagemax+3; i++){
4497: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
4498: posprop += prop[jk][i];
4499: }
4500:
4501: for(jk=1; jk <=nlstate ; jk++){
4502: if( i <= iagemax){
4503: if(posprop>=1.e-5){
4504: probs[i][jk][j1]= prop[jk][i]/posprop;
4505: } else{
4506: if(first==1){
4507: first=0;
4508: printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
4509: }
4510: }
4511: }
4512: }/* end jk */
4513: }/* end i */
4514: /*} *//* end i1 */
4515: } /* end j1 */
4516:
4517: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
4518: /*free_vector(pp,1,nlstate);*/
4519: free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
4520: } /* End of prevalence */
4521:
4522: /************* Waves Concatenation ***************/
4523:
4524: 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)
4525: {
4526: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
4527: Death is a valid wave (if date is known).
4528: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
4529: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
4530: and mw[mi+1][i]. dh depends on stepm.
4531: */
4532:
4533: int i=0, mi=0, m=0, mli=0;
4534: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
4535: double sum=0., jmean=0.;*/
4536: int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
4537: int j, k=0,jk, ju, jl;
4538: double sum=0.;
4539: first=0;
4540: firstwo=0;
4541: firsthree=0;
4542: firstfour=0;
4543: jmin=100000;
4544: jmax=-1;
4545: jmean=0.;
4546:
4547: /* Treating live states */
4548: for(i=1; i<=imx; i++){ /* For simple cases and if state is death */
4549: mi=0; /* First valid wave */
4550: mli=0; /* Last valid wave */
4551: m=firstpass;
4552: while(s[m][i] <= nlstate){ /* a live state */
4553: if(m >firstpass && s[m][i]==s[m-1][i] && mint[m][i]==mint[m-1][i] && anint[m][i]==anint[m-1][i]){/* Two succesive identical information on wave m */
4554: mli=m-1;/* mw[++mi][i]=m-1; */
4555: }else if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
4556: mw[++mi][i]=m;
4557: mli=m;
4558: } /* else might be a useless wave -1 and mi is not incremented and mw[mi] not updated */
4559: if(m < lastpass){ /* m < lastpass, standard case */
4560: m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
4561: }
4562: else{ /* m >= lastpass, eventual special issue with warning */
4563: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
4564: break;
4565: #else
4566: if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
4567: if(firsthree == 0){
4568: printf("Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
4569: firsthree=1;
4570: }
4571: fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
4572: mw[++mi][i]=m;
4573: mli=m;
4574: }
4575: if(s[m][i]==-2){ /* Vital status is really unknown */
4576: nbwarn++;
4577: if((int)anint[m][i] == 9999){ /* Has the vital status really been verified? */
4578: printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
4579: fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
4580: }
4581: break;
4582: }
4583: break;
4584: #endif
4585: }/* End m >= lastpass */
4586: }/* end while */
4587:
4588: /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
4589: /* After last pass */
4590: /* Treating death states */
4591: if (s[m][i] > nlstate){ /* In a death state */
4592: /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
4593: /* } */
4594: mi++; /* Death is another wave */
4595: /* if(mi==0) never been interviewed correctly before death */
4596: /* Only death is a correct wave */
4597: mw[mi][i]=m;
4598: }
4599: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
4600: else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
4601: /* m++; */
4602: /* mi++; */
4603: /* s[m][i]=nlstate+1; /\* We are setting the status to the last of non live state *\/ */
4604: /* mw[mi][i]=m; */
4605: if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
4606: if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
4607: nbwarn++;
4608: if(firstfiv==0){
4609: printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
4610: firstfiv=1;
4611: }else{
4612: fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
4613: }
4614: }else{ /* Death occured afer last wave potential bias */
4615: nberr++;
4616: if(firstwo==0){
4617: printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4618: firstwo=1;
4619: }
4620: fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4621: }
4622: }else{ /* end date of interview is known */
4623: /* death is known but not confirmed by death status at any wave */
4624: if(firstfour==0){
4625: printf("Error! Death for individual %ld line=%d occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4626: firstfour=1;
4627: }
4628: fprintf(ficlog,"Error! Death for individual %ld line=%d occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4629: }
4630: } /* end if date of death is known */
4631: #endif
4632: wav[i]=mi; /* mi should be the last effective wave (or mli) */
4633: /* wav[i]=mw[mi][i]; */
4634: if(mi==0){
4635: nbwarn++;
4636: if(first==0){
4637: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
4638: first=1;
4639: }
4640: if(first==1){
4641: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
4642: }
4643: } /* end mi==0 */
4644: } /* End individuals */
4645: /* wav and mw are no more changed */
4646:
4647:
4648: for(i=1; i<=imx; i++){
4649: for(mi=1; mi<wav[i];mi++){
4650: if (stepm <=0)
4651: dh[mi][i]=1;
4652: else{
4653: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
4654: if (agedc[i] < 2*AGESUP) {
4655: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
4656: if(j==0) j=1; /* Survives at least one month after exam */
4657: else if(j<0){
4658: nberr++;
4659: 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]);
4660: j=1; /* Temporary Dangerous patch */
4661: 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);
4662: 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]);
4663: 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);
4664: }
4665: k=k+1;
4666: if (j >= jmax){
4667: jmax=j;
4668: ijmax=i;
4669: }
4670: if (j <= jmin){
4671: jmin=j;
4672: ijmin=i;
4673: }
4674: sum=sum+j;
4675: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
4676: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
4677: }
4678: }
4679: else{
4680: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
4681: /* 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]); */
4682:
4683: k=k+1;
4684: if (j >= jmax) {
4685: jmax=j;
4686: ijmax=i;
4687: }
4688: else if (j <= jmin){
4689: jmin=j;
4690: ijmin=i;
4691: }
4692: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
4693: /*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]);*/
4694: if(j<0){
4695: nberr++;
4696: 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]);
4697: 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]);
4698: }
4699: sum=sum+j;
4700: }
4701: jk= j/stepm;
4702: jl= j -jk*stepm;
4703: ju= j -(jk+1)*stepm;
4704: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
4705: if(jl==0){
4706: dh[mi][i]=jk;
4707: bh[mi][i]=0;
4708: }else{ /* We want a negative bias in order to only have interpolation ie
4709: * to avoid the price of an extra matrix product in likelihood */
4710: dh[mi][i]=jk+1;
4711: bh[mi][i]=ju;
4712: }
4713: }else{
4714: if(jl <= -ju){
4715: dh[mi][i]=jk;
4716: bh[mi][i]=jl; /* bias is positive if real duration
4717: * is higher than the multiple of stepm and negative otherwise.
4718: */
4719: }
4720: else{
4721: dh[mi][i]=jk+1;
4722: bh[mi][i]=ju;
4723: }
4724: if(dh[mi][i]==0){
4725: dh[mi][i]=1; /* At least one step */
4726: bh[mi][i]=ju; /* At least one step */
4727: /* 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);*/
4728: }
4729: } /* end if mle */
4730: }
4731: } /* end wave */
4732: }
4733: jmean=sum/k;
4734: 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);
4735: 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);
4736: }
4737:
4738: /*********** Tricode ****************************/
4739: void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
4740: {
4741: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
4742: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
4743: * Boring subroutine which should only output nbcode[Tvar[j]][k]
4744: * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
4745: * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
4746: */
4747:
4748: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
4749: int modmaxcovj=0; /* Modality max of covariates j */
4750: int cptcode=0; /* Modality max of covariates j */
4751: int modmincovj=0; /* Modality min of covariates j */
4752:
4753:
4754: /* cptcoveff=0; */
4755: /* *cptcov=0; */
4756:
4757: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
4758:
4759: /* Loop on covariates without age and products and no quantitative variable */
4760: /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
4761: for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
4762: for (j=-1; (j < maxncov); j++) Ndum[j]=0;
4763: if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */
4764: switch(Fixed[k]) {
4765: case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
4766: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the modality of this covariate Vj*/
4767: ij=(int)(covar[Tvar[k]][i]);
4768: /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
4769: * If product of Vn*Vm, still boolean *:
4770: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
4771: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
4772: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
4773: modality of the nth covariate of individual i. */
4774: if (ij > modmaxcovj)
4775: modmaxcovj=ij;
4776: else if (ij < modmincovj)
4777: modmincovj=ij;
4778: if ((ij < -1) && (ij > NCOVMAX)){
4779: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
4780: exit(1);
4781: }else
4782: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
4783: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
4784: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
4785: /* getting the maximum value of the modality of the covariate
4786: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
4787: female ies 1, then modmaxcovj=1.
4788: */
4789: } /* end for loop on individuals i */
4790: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
4791: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
4792: cptcode=modmaxcovj;
4793: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
4794: /*for (i=0; i<=cptcode; i++) {*/
4795: for (j=modmincovj; j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
4796: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
4797: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
4798: if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
4799: if( j != -1){
4800: ncodemax[k]++; /* ncodemax[k]= Number of modalities of the k th
4801: covariate for which somebody answered excluding
4802: undefined. Usually 2: 0 and 1. */
4803: }
4804: ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
4805: covariate for which somebody answered including
4806: undefined. Usually 3: -1, 0 and 1. */
4807: } /* In fact ncodemax[k]=2 (dichotom. variables only) but it could be more for
4808: * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
4809: } /* Ndum[-1] number of undefined modalities */
4810:
4811: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
4812: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
4813: /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
4814: /* modmincovj=3; modmaxcovj = 7; */
4815: /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
4816: /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
4817: /* defining two dummy variables: variables V1_1 and V1_2.*/
4818: /* nbcode[Tvar[j]][ij]=k; */
4819: /* nbcode[Tvar[j]][1]=0; */
4820: /* nbcode[Tvar[j]][2]=1; */
4821: /* nbcode[Tvar[j]][3]=2; */
4822: /* To be continued (not working yet). */
4823: ij=0; /* ij is similar to i but can jump over null modalities */
4824: 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*/
4825: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
4826: break;
4827: }
4828: ij++;
4829: nbcode[Tvar[k]][ij]=i; /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1*/
4830: cptcode = ij; /* New max modality for covar j */
4831: } /* end of loop on modality i=-1 to 1 or more */
4832: break;
4833: case 1: /* Testing on varying covariate, could be simple and
4834: * should look at waves or product of fixed *
4835: * varying. No time to test -1, assuming 0 and 1 only */
4836: ij=0;
4837: for(i=0; i<=1;i++){
4838: nbcode[Tvar[k]][++ij]=i;
4839: }
4840: break;
4841: default:
4842: break;
4843: } /* end switch */
4844: } /* end dummy test */
4845:
4846: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
4847: /* /\*recode from 0 *\/ */
4848: /* k is a modality. If we have model=V1+V1*sex */
4849: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
4850: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
4851: /* } */
4852: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
4853: /* if (ij > ncodemax[j]) { */
4854: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
4855: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
4856: /* break; */
4857: /* } */
4858: /* } /\* end of loop on modality k *\/ */
4859: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
4860:
4861: for (k=-1; k< maxncov; k++) Ndum[k]=0;
4862: /* Look at fixed dummy (single or product) covariates to check empty modalities */
4863: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
4864: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
4865: ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */
4866: Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
4867: /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, {2, 1, 1, 1, 2, 1, 1, 0, 0} */
4868: } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
4869:
4870: ij=0;
4871: /* for (i=0; i<= maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
4872: for (k=1; k<= cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
4873: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
4874: /* if((Ndum[i]!=0) && (i<=ncovcol)){ /\* Tvar[i] <= ncovmodel ? *\/ */
4875: if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){ /* Only Dummy and non empty in the model */
4876: /* If product not in single variable we don't print results */
4877: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
4878: ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
4879: Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
4880: Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
4881: TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
4882: if(Fixed[k]!=0)
4883: anyvaryingduminmodel=1;
4884: /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
4885: /* Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
4886: /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
4887: /* Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
4888: /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
4889: /* Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
4890: }
4891: } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
4892: /* ij--; */
4893: /* cptcoveff=ij; /\*Number of total covariates*\/ */
4894: *cptcov=ij; /*Number of total real effective covariates: effective
4895: * because they can be excluded from the model and real
4896: * if in the model but excluded because missing values, but how to get k from ij?*/
4897: for(j=ij+1; j<= cptcovt; j++){
4898: Tvaraff[j]=0;
4899: Tmodelind[j]=0;
4900: }
4901: for(j=ntveff+1; j<= cptcovt; j++){
4902: TmodelInvind[j]=0;
4903: }
4904: /* To be sorted */
4905: ;
4906: }
4907:
4908:
4909: /*********** Health Expectancies ****************/
4910:
4911: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
4912:
4913: {
4914: /* Health expectancies, no variances */
4915: int i, j, nhstepm, hstepm, h, nstepm;
4916: int nhstepma, nstepma; /* Decreasing with age */
4917: double age, agelim, hf;
4918: double ***p3mat;
4919: double eip;
4920:
4921: pstamp(ficreseij);
4922: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
4923: fprintf(ficreseij,"# Age");
4924: for(i=1; i<=nlstate;i++){
4925: for(j=1; j<=nlstate;j++){
4926: fprintf(ficreseij," e%1d%1d ",i,j);
4927: }
4928: fprintf(ficreseij," e%1d. ",i);
4929: }
4930: fprintf(ficreseij,"\n");
4931:
4932:
4933: if(estepm < stepm){
4934: printf ("Problem %d lower than %d\n",estepm, stepm);
4935: }
4936: else hstepm=estepm;
4937: /* We compute the life expectancy from trapezoids spaced every estepm months
4938: * This is mainly to measure the difference between two models: for example
4939: * if stepm=24 months pijx are given only every 2 years and by summing them
4940: * we are calculating an estimate of the Life Expectancy assuming a linear
4941: * progression in between and thus overestimating or underestimating according
4942: * to the curvature of the survival function. If, for the same date, we
4943: * estimate the model with stepm=1 month, we can keep estepm to 24 months
4944: * to compare the new estimate of Life expectancy with the same linear
4945: * hypothesis. A more precise result, taking into account a more precise
4946: * curvature will be obtained if estepm is as small as stepm. */
4947:
4948: /* For example we decided to compute the life expectancy with the smallest unit */
4949: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4950: nhstepm is the number of hstepm from age to agelim
4951: nstepm is the number of stepm from age to agelin.
4952: Look at hpijx to understand the reason of that which relies in memory size
4953: and note for a fixed period like estepm months */
4954: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4955: survival function given by stepm (the optimization length). Unfortunately it
4956: means that if the survival funtion is printed only each two years of age and if
4957: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4958: results. So we changed our mind and took the option of the best precision.
4959: */
4960: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4961:
4962: agelim=AGESUP;
4963: /* If stepm=6 months */
4964: /* Computed by stepm unit matrices, product of hstepm matrices, stored
4965: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
4966:
4967: /* nhstepm age range expressed in number of stepm */
4968: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4969: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4970: /* if (stepm >= YEARM) hstepm=1;*/
4971: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4972: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4973:
4974: for (age=bage; age<=fage; age ++){
4975: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4976: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4977: /* if (stepm >= YEARM) hstepm=1;*/
4978: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
4979:
4980: /* If stepm=6 months */
4981: /* Computed by stepm unit matrices, product of hstepma matrices, stored
4982: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
4983:
4984: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);
4985:
4986: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4987:
4988: printf("%d|",(int)age);fflush(stdout);
4989: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4990:
4991: /* Computing expectancies */
4992: for(i=1; i<=nlstate;i++)
4993: for(j=1; j<=nlstate;j++)
4994: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4995: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
4996:
4997: /* 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]);*/
4998:
4999: }
5000:
5001: fprintf(ficreseij,"%3.0f",age );
5002: for(i=1; i<=nlstate;i++){
5003: eip=0;
5004: for(j=1; j<=nlstate;j++){
5005: eip +=eij[i][j][(int)age];
5006: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
5007: }
5008: fprintf(ficreseij,"%9.4f", eip );
5009: }
5010: fprintf(ficreseij,"\n");
5011:
5012: }
5013: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5014: printf("\n");
5015: fprintf(ficlog,"\n");
5016:
5017: }
5018:
5019: 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[], int nres )
5020:
5021: {
5022: /* Covariances of health expectancies eij and of total life expectancies according
5023: to initial status i, ei. .
5024: */
5025: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
5026: int nhstepma, nstepma; /* Decreasing with age */
5027: double age, agelim, hf;
5028: double ***p3matp, ***p3matm, ***varhe;
5029: double **dnewm,**doldm;
5030: double *xp, *xm;
5031: double **gp, **gm;
5032: double ***gradg, ***trgradg;
5033: int theta;
5034:
5035: double eip, vip;
5036:
5037: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
5038: xp=vector(1,npar);
5039: xm=vector(1,npar);
5040: dnewm=matrix(1,nlstate*nlstate,1,npar);
5041: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
5042:
5043: pstamp(ficresstdeij);
5044: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
5045: fprintf(ficresstdeij,"# Age");
5046: for(i=1; i<=nlstate;i++){
5047: for(j=1; j<=nlstate;j++)
5048: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
5049: fprintf(ficresstdeij," e%1d. ",i);
5050: }
5051: fprintf(ficresstdeij,"\n");
5052:
5053: pstamp(ficrescveij);
5054: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
5055: fprintf(ficrescveij,"# Age");
5056: for(i=1; i<=nlstate;i++)
5057: for(j=1; j<=nlstate;j++){
5058: cptj= (j-1)*nlstate+i;
5059: for(i2=1; i2<=nlstate;i2++)
5060: for(j2=1; j2<=nlstate;j2++){
5061: cptj2= (j2-1)*nlstate+i2;
5062: if(cptj2 <= cptj)
5063: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
5064: }
5065: }
5066: fprintf(ficrescveij,"\n");
5067:
5068: if(estepm < stepm){
5069: printf ("Problem %d lower than %d\n",estepm, stepm);
5070: }
5071: else hstepm=estepm;
5072: /* We compute the life expectancy from trapezoids spaced every estepm months
5073: * This is mainly to measure the difference between two models: for example
5074: * if stepm=24 months pijx are given only every 2 years and by summing them
5075: * we are calculating an estimate of the Life Expectancy assuming a linear
5076: * progression in between and thus overestimating or underestimating according
5077: * to the curvature of the survival function. If, for the same date, we
5078: * estimate the model with stepm=1 month, we can keep estepm to 24 months
5079: * to compare the new estimate of Life expectancy with the same linear
5080: * hypothesis. A more precise result, taking into account a more precise
5081: * curvature will be obtained if estepm is as small as stepm. */
5082:
5083: /* For example we decided to compute the life expectancy with the smallest unit */
5084: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
5085: nhstepm is the number of hstepm from age to agelim
5086: nstepm is the number of stepm from age to agelin.
5087: Look at hpijx to understand the reason of that which relies in memory size
5088: and note for a fixed period like estepm months */
5089: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
5090: survival function given by stepm (the optimization length). Unfortunately it
5091: means that if the survival funtion is printed only each two years of age and if
5092: you sum them up and add 1 year (area under the trapezoids) you won't get the same
5093: results. So we changed our mind and took the option of the best precision.
5094: */
5095: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
5096:
5097: /* If stepm=6 months */
5098: /* nhstepm age range expressed in number of stepm */
5099: agelim=AGESUP;
5100: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
5101: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
5102: /* if (stepm >= YEARM) hstepm=1;*/
5103: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
5104:
5105: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5106: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5107: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
5108: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
5109: gp=matrix(0,nhstepm,1,nlstate*nlstate);
5110: gm=matrix(0,nhstepm,1,nlstate*nlstate);
5111:
5112: for (age=bage; age<=fage; age ++){
5113: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
5114: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
5115: /* if (stepm >= YEARM) hstepm=1;*/
5116: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
5117:
5118: /* If stepm=6 months */
5119: /* Computed by stepm unit matrices, product of hstepma matrices, stored
5120: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
5121:
5122: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
5123:
5124: /* Computing Variances of health expectancies */
5125: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
5126: decrease memory allocation */
5127: for(theta=1; theta <=npar; theta++){
5128: for(i=1; i<=npar; i++){
5129: xp[i] = x[i] + (i==theta ?delti[theta]:0);
5130: xm[i] = x[i] - (i==theta ?delti[theta]:0);
5131: }
5132: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);
5133: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);
5134:
5135: for(j=1; j<= nlstate; j++){
5136: for(i=1; i<=nlstate; i++){
5137: for(h=0; h<=nhstepm-1; h++){
5138: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
5139: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
5140: }
5141: }
5142: }
5143:
5144: for(ij=1; ij<= nlstate*nlstate; ij++)
5145: for(h=0; h<=nhstepm-1; h++){
5146: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
5147: }
5148: }/* End theta */
5149:
5150:
5151: for(h=0; h<=nhstepm-1; h++)
5152: for(j=1; j<=nlstate*nlstate;j++)
5153: for(theta=1; theta <=npar; theta++)
5154: trgradg[h][j][theta]=gradg[h][theta][j];
5155:
5156:
5157: for(ij=1;ij<=nlstate*nlstate;ij++)
5158: for(ji=1;ji<=nlstate*nlstate;ji++)
5159: varhe[ij][ji][(int)age] =0.;
5160:
5161: printf("%d|",(int)age);fflush(stdout);
5162: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
5163: for(h=0;h<=nhstepm-1;h++){
5164: for(k=0;k<=nhstepm-1;k++){
5165: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
5166: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
5167: for(ij=1;ij<=nlstate*nlstate;ij++)
5168: for(ji=1;ji<=nlstate*nlstate;ji++)
5169: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
5170: }
5171: }
5172:
5173: /* Computing expectancies */
5174: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);
5175: for(i=1; i<=nlstate;i++)
5176: for(j=1; j<=nlstate;j++)
5177: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
5178: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
5179:
5180: /* 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]);*/
5181:
5182: }
5183:
5184: fprintf(ficresstdeij,"%3.0f",age );
5185: for(i=1; i<=nlstate;i++){
5186: eip=0.;
5187: vip=0.;
5188: for(j=1; j<=nlstate;j++){
5189: eip += eij[i][j][(int)age];
5190: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
5191: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
5192: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
5193: }
5194: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
5195: }
5196: fprintf(ficresstdeij,"\n");
5197:
5198: fprintf(ficrescveij,"%3.0f",age );
5199: for(i=1; i<=nlstate;i++)
5200: for(j=1; j<=nlstate;j++){
5201: cptj= (j-1)*nlstate+i;
5202: for(i2=1; i2<=nlstate;i2++)
5203: for(j2=1; j2<=nlstate;j2++){
5204: cptj2= (j2-1)*nlstate+i2;
5205: if(cptj2 <= cptj)
5206: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
5207: }
5208: }
5209: fprintf(ficrescveij,"\n");
5210:
5211: }
5212: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
5213: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
5214: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
5215: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
5216: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5217: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5218: printf("\n");
5219: fprintf(ficlog,"\n");
5220:
5221: free_vector(xm,1,npar);
5222: free_vector(xp,1,npar);
5223: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
5224: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
5225: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
5226: }
5227:
5228: /************ Variance ******************/
5229: 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[], int nres)
5230: {
5231: /* Variance of health expectancies */
5232: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
5233: /* double **newm;*/
5234: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
5235:
5236: /* int movingaverage(); */
5237: double **dnewm,**doldm;
5238: double **dnewmp,**doldmp;
5239: int i, j, nhstepm, hstepm, h, nstepm ;
5240: int k;
5241: double *xp;
5242: double **gp, **gm; /* for var eij */
5243: double ***gradg, ***trgradg; /*for var eij */
5244: double **gradgp, **trgradgp; /* for var p point j */
5245: double *gpp, *gmp; /* for var p point j */
5246: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
5247: double ***p3mat;
5248: double age,agelim, hf;
5249: /* double ***mobaverage; */
5250: int theta;
5251: char digit[4];
5252: char digitp[25];
5253:
5254: char fileresprobmorprev[FILENAMELENGTH];
5255:
5256: if(popbased==1){
5257: if(mobilav!=0)
5258: strcpy(digitp,"-POPULBASED-MOBILAV_");
5259: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
5260: }
5261: else
5262: strcpy(digitp,"-STABLBASED_");
5263:
5264: /* if (mobilav!=0) { */
5265: /* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
5266: /* if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
5267: /* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
5268: /* printf(" Error in movingaverage mobilav=%d\n",mobilav); */
5269: /* } */
5270: /* } */
5271:
5272: strcpy(fileresprobmorprev,"PRMORPREV-");
5273: sprintf(digit,"%-d",ij);
5274: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
5275: strcat(fileresprobmorprev,digit); /* Tvar to be done */
5276: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
5277: strcat(fileresprobmorprev,fileresu);
5278: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
5279: printf("Problem with resultfile: %s\n", fileresprobmorprev);
5280: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
5281: }
5282: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
5283: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
5284: pstamp(ficresprobmorprev);
5285: 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);
5286: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
5287: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
5288: fprintf(ficresprobmorprev," p.%-d SE",j);
5289: for(i=1; i<=nlstate;i++)
5290: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
5291: }
5292: fprintf(ficresprobmorprev,"\n");
5293:
5294: fprintf(ficgp,"\n# Routine varevsij");
5295: fprintf(ficgp,"\nunset title \n");
5296: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
5297: 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");
5298: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
5299: /* } */
5300: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
5301: pstamp(ficresvij);
5302: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
5303: if(popbased==1)
5304: 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);
5305: else
5306: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
5307: fprintf(ficresvij,"# Age");
5308: for(i=1; i<=nlstate;i++)
5309: for(j=1; j<=nlstate;j++)
5310: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
5311: fprintf(ficresvij,"\n");
5312:
5313: xp=vector(1,npar);
5314: dnewm=matrix(1,nlstate,1,npar);
5315: doldm=matrix(1,nlstate,1,nlstate);
5316: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
5317: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
5318:
5319: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
5320: gpp=vector(nlstate+1,nlstate+ndeath);
5321: gmp=vector(nlstate+1,nlstate+ndeath);
5322: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
5323:
5324: if(estepm < stepm){
5325: printf ("Problem %d lower than %d\n",estepm, stepm);
5326: }
5327: else hstepm=estepm;
5328: /* For example we decided to compute the life expectancy with the smallest unit */
5329: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
5330: nhstepm is the number of hstepm from age to agelim
5331: nstepm is the number of stepm from age to agelim.
5332: Look at function hpijx to understand why because of memory size limitations,
5333: we decided (b) to get a life expectancy respecting the most precise curvature of the
5334: survival function given by stepm (the optimization length). Unfortunately it
5335: means that if the survival funtion is printed every two years of age and if
5336: you sum them up and add 1 year (area under the trapezoids) you won't get the same
5337: results. So we changed our mind and took the option of the best precision.
5338: */
5339: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
5340: agelim = AGESUP;
5341: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
5342: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5343: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
5344: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5345: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
5346: gp=matrix(0,nhstepm,1,nlstate);
5347: gm=matrix(0,nhstepm,1,nlstate);
5348:
5349:
5350: for(theta=1; theta <=npar; theta++){
5351: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
5352: xp[i] = x[i] + (i==theta ?delti[theta]:0);
5353: }
5354:
5355: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
5356:
5357: if (popbased==1) {
5358: if(mobilav ==0){
5359: for(i=1; i<=nlstate;i++)
5360: prlim[i][i]=probs[(int)age][i][ij];
5361: }else{ /* mobilav */
5362: for(i=1; i<=nlstate;i++)
5363: prlim[i][i]=mobaverage[(int)age][i][ij];
5364: }
5365: }
5366:
5367: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
5368: for(j=1; j<= nlstate; j++){
5369: for(h=0; h<=nhstepm; h++){
5370: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
5371: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
5372: }
5373: }
5374: /* Next for computing probability of death (h=1 means
5375: computed over hstepm matrices product = hstepm*stepm months)
5376: as a weighted average of prlim.
5377: */
5378: for(j=nlstate+1;j<=nlstate+ndeath;j++){
5379: for(i=1,gpp[j]=0.; i<= nlstate; i++)
5380: gpp[j] += prlim[i][i]*p3mat[i][j][1];
5381: }
5382: /* end probability of death */
5383:
5384: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
5385: xp[i] = x[i] - (i==theta ?delti[theta]:0);
5386:
5387: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nresult);
5388:
5389: if (popbased==1) {
5390: if(mobilav ==0){
5391: for(i=1; i<=nlstate;i++)
5392: prlim[i][i]=probs[(int)age][i][ij];
5393: }else{ /* mobilav */
5394: for(i=1; i<=nlstate;i++)
5395: prlim[i][i]=mobaverage[(int)age][i][ij];
5396: }
5397: }
5398:
5399: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);
5400:
5401: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
5402: for(h=0; h<=nhstepm; h++){
5403: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
5404: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
5405: }
5406: }
5407: /* This for computing probability of death (h=1 means
5408: computed over hstepm matrices product = hstepm*stepm months)
5409: as a weighted average of prlim.
5410: */
5411: for(j=nlstate+1;j<=nlstate+ndeath;j++){
5412: for(i=1,gmp[j]=0.; i<= nlstate; i++)
5413: gmp[j] += prlim[i][i]*p3mat[i][j][1];
5414: }
5415: /* end probability of death */
5416:
5417: for(j=1; j<= nlstate; j++) /* vareij */
5418: for(h=0; h<=nhstepm; h++){
5419: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
5420: }
5421:
5422: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
5423: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
5424: }
5425:
5426: } /* End theta */
5427:
5428: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
5429:
5430: for(h=0; h<=nhstepm; h++) /* veij */
5431: for(j=1; j<=nlstate;j++)
5432: for(theta=1; theta <=npar; theta++)
5433: trgradg[h][j][theta]=gradg[h][theta][j];
5434:
5435: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
5436: for(theta=1; theta <=npar; theta++)
5437: trgradgp[j][theta]=gradgp[theta][j];
5438:
5439:
5440: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
5441: for(i=1;i<=nlstate;i++)
5442: for(j=1;j<=nlstate;j++)
5443: vareij[i][j][(int)age] =0.;
5444:
5445: for(h=0;h<=nhstepm;h++){
5446: for(k=0;k<=nhstepm;k++){
5447: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
5448: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
5449: for(i=1;i<=nlstate;i++)
5450: for(j=1;j<=nlstate;j++)
5451: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
5452: }
5453: }
5454:
5455: /* pptj */
5456: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
5457: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
5458: for(j=nlstate+1;j<=nlstate+ndeath;j++)
5459: for(i=nlstate+1;i<=nlstate+ndeath;i++)
5460: varppt[j][i]=doldmp[j][i];
5461: /* end ppptj */
5462: /* x centered again */
5463:
5464: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
5465:
5466: if (popbased==1) {
5467: if(mobilav ==0){
5468: for(i=1; i<=nlstate;i++)
5469: prlim[i][i]=probs[(int)age][i][ij];
5470: }else{ /* mobilav */
5471: for(i=1; i<=nlstate;i++)
5472: prlim[i][i]=mobaverage[(int)age][i][ij];
5473: }
5474: }
5475:
5476: /* This for computing probability of death (h=1 means
5477: computed over hstepm (estepm) matrices product = hstepm*stepm months)
5478: as a weighted average of prlim.
5479: */
5480: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);
5481: for(j=nlstate+1;j<=nlstate+ndeath;j++){
5482: for(i=1,gmp[j]=0.;i<= nlstate; i++)
5483: gmp[j] += prlim[i][i]*p3mat[i][j][1];
5484: }
5485: /* end probability of death */
5486:
5487: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
5488: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
5489: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
5490: for(i=1; i<=nlstate;i++){
5491: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
5492: }
5493: }
5494: fprintf(ficresprobmorprev,"\n");
5495:
5496: fprintf(ficresvij,"%.0f ",age );
5497: for(i=1; i<=nlstate;i++)
5498: for(j=1; j<=nlstate;j++){
5499: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
5500: }
5501: fprintf(ficresvij,"\n");
5502: free_matrix(gp,0,nhstepm,1,nlstate);
5503: free_matrix(gm,0,nhstepm,1,nlstate);
5504: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
5505: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
5506: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5507: } /* End age */
5508: free_vector(gpp,nlstate+1,nlstate+ndeath);
5509: free_vector(gmp,nlstate+1,nlstate+ndeath);
5510: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
5511: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
5512: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
5513: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
5514: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
5515: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
5516: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
5517: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
5518: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
5519: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
5520: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
5521: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
5522: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
5523: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
5524: 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);
5525: /* 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);
5526: */
5527: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
5528: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
5529:
5530: free_vector(xp,1,npar);
5531: free_matrix(doldm,1,nlstate,1,nlstate);
5532: free_matrix(dnewm,1,nlstate,1,npar);
5533: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
5534: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
5535: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
5536: /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
5537: fclose(ficresprobmorprev);
5538: fflush(ficgp);
5539: fflush(fichtm);
5540: } /* end varevsij */
5541:
5542: /************ Variance of prevlim ******************/
5543: 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[], int nres)
5544: {
5545: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
5546: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
5547:
5548: double **dnewm,**doldm;
5549: int i, j, nhstepm, hstepm;
5550: double *xp;
5551: double *gp, *gm;
5552: double **gradg, **trgradg;
5553: double **mgm, **mgp;
5554: double age,agelim;
5555: int theta;
5556:
5557: pstamp(ficresvpl);
5558: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
5559: fprintf(ficresvpl,"# Age");
5560: for(i=1; i<=nlstate;i++)
5561: fprintf(ficresvpl," %1d-%1d",i,i);
5562: fprintf(ficresvpl,"\n");
5563:
5564: xp=vector(1,npar);
5565: dnewm=matrix(1,nlstate,1,npar);
5566: doldm=matrix(1,nlstate,1,nlstate);
5567:
5568: hstepm=1*YEARM; /* Every year of age */
5569: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
5570: agelim = AGESUP;
5571: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
5572: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5573: if (stepm >= YEARM) hstepm=1;
5574: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5575: gradg=matrix(1,npar,1,nlstate);
5576: mgp=matrix(1,npar,1,nlstate);
5577: mgm=matrix(1,npar,1,nlstate);
5578: gp=vector(1,nlstate);
5579: gm=vector(1,nlstate);
5580:
5581: for(theta=1; theta <=npar; theta++){
5582: for(i=1; i<=npar; i++){ /* Computes gradient */
5583: xp[i] = x[i] + (i==theta ?delti[theta]:0);
5584: }
5585: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
5586: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
5587: else
5588: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
5589: for(i=1;i<=nlstate;i++){
5590: gp[i] = prlim[i][i];
5591: mgp[theta][i] = prlim[i][i];
5592: }
5593: for(i=1; i<=npar; i++) /* Computes gradient */
5594: xp[i] = x[i] - (i==theta ?delti[theta]:0);
5595: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
5596: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
5597: else
5598: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
5599: for(i=1;i<=nlstate;i++){
5600: gm[i] = prlim[i][i];
5601: mgm[theta][i] = prlim[i][i];
5602: }
5603: for(i=1;i<=nlstate;i++)
5604: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
5605: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
5606: } /* End theta */
5607:
5608: trgradg =matrix(1,nlstate,1,npar);
5609:
5610: for(j=1; j<=nlstate;j++)
5611: for(theta=1; theta <=npar; theta++)
5612: trgradg[j][theta]=gradg[theta][j];
5613: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
5614: /* printf("\nmgm mgp %d ",(int)age); */
5615: /* for(j=1; j<=nlstate;j++){ */
5616: /* printf(" %d ",j); */
5617: /* for(theta=1; theta <=npar; theta++) */
5618: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
5619: /* printf("\n "); */
5620: /* } */
5621: /* } */
5622: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
5623: /* printf("\n gradg %d ",(int)age); */
5624: /* for(j=1; j<=nlstate;j++){ */
5625: /* printf("%d ",j); */
5626: /* for(theta=1; theta <=npar; theta++) */
5627: /* printf("%d %lf ",theta,gradg[theta][j]); */
5628: /* printf("\n "); */
5629: /* } */
5630: /* } */
5631:
5632: for(i=1;i<=nlstate;i++)
5633: varpl[i][(int)age] =0.;
5634: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
5635: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
5636: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
5637: }else{
5638: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
5639: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
5640: }
5641: for(i=1;i<=nlstate;i++)
5642: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
5643:
5644: fprintf(ficresvpl,"%.0f ",age );
5645: for(i=1; i<=nlstate;i++)
5646: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
5647: fprintf(ficresvpl,"\n");
5648: free_vector(gp,1,nlstate);
5649: free_vector(gm,1,nlstate);
5650: free_matrix(mgm,1,npar,1,nlstate);
5651: free_matrix(mgp,1,npar,1,nlstate);
5652: free_matrix(gradg,1,npar,1,nlstate);
5653: free_matrix(trgradg,1,nlstate,1,npar);
5654: } /* End age */
5655:
5656: free_vector(xp,1,npar);
5657: free_matrix(doldm,1,nlstate,1,npar);
5658: free_matrix(dnewm,1,nlstate,1,nlstate);
5659:
5660: }
5661:
5662: /************ Variance of one-step probabilities ******************/
5663: 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[])
5664: {
5665: int i, j=0, k1, l1, tj;
5666: int k2, l2, j1, z1;
5667: int k=0, l;
5668: int first=1, first1, first2;
5669: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
5670: double **dnewm,**doldm;
5671: double *xp;
5672: double *gp, *gm;
5673: double **gradg, **trgradg;
5674: double **mu;
5675: double age, cov[NCOVMAX+1];
5676: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
5677: int theta;
5678: char fileresprob[FILENAMELENGTH];
5679: char fileresprobcov[FILENAMELENGTH];
5680: char fileresprobcor[FILENAMELENGTH];
5681: double ***varpij;
5682:
5683: strcpy(fileresprob,"PROB_");
5684: strcat(fileresprob,fileres);
5685: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
5686: printf("Problem with resultfile: %s\n", fileresprob);
5687: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
5688: }
5689: strcpy(fileresprobcov,"PROBCOV_");
5690: strcat(fileresprobcov,fileresu);
5691: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
5692: printf("Problem with resultfile: %s\n", fileresprobcov);
5693: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
5694: }
5695: strcpy(fileresprobcor,"PROBCOR_");
5696: strcat(fileresprobcor,fileresu);
5697: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
5698: printf("Problem with resultfile: %s\n", fileresprobcor);
5699: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
5700: }
5701: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
5702: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
5703: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
5704: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
5705: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
5706: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
5707: pstamp(ficresprob);
5708: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
5709: fprintf(ficresprob,"# Age");
5710: pstamp(ficresprobcov);
5711: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
5712: fprintf(ficresprobcov,"# Age");
5713: pstamp(ficresprobcor);
5714: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
5715: fprintf(ficresprobcor,"# Age");
5716:
5717:
5718: for(i=1; i<=nlstate;i++)
5719: for(j=1; j<=(nlstate+ndeath);j++){
5720: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
5721: fprintf(ficresprobcov," p%1d-%1d ",i,j);
5722: fprintf(ficresprobcor," p%1d-%1d ",i,j);
5723: }
5724: /* fprintf(ficresprob,"\n");
5725: fprintf(ficresprobcov,"\n");
5726: fprintf(ficresprobcor,"\n");
5727: */
5728: xp=vector(1,npar);
5729: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
5730: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
5731: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
5732: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
5733: first=1;
5734: fprintf(ficgp,"\n# Routine varprob");
5735: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
5736: fprintf(fichtm,"\n");
5737:
5738: 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);
5739: 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);
5740: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
5741: and drawn. It helps understanding how is the covariance between two incidences.\
5742: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
5743: 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. \
5744: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
5745: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
5746: standard deviations wide on each axis. <br>\
5747: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
5748: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
5749: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
5750:
5751: cov[1]=1;
5752: /* tj=cptcoveff; */
5753: tj = (int) pow(2,cptcoveff);
5754: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
5755: j1=0;
5756: for(j1=1; j1<=tj;j1++){ /* For each valid combination of covariates or only once*/
5757: if (cptcovn>0) {
5758: fprintf(ficresprob, "\n#********** Variable ");
5759: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5760: fprintf(ficresprob, "**********\n#\n");
5761: fprintf(ficresprobcov, "\n#********** Variable ");
5762: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5763: fprintf(ficresprobcov, "**********\n#\n");
5764:
5765: fprintf(ficgp, "\n#********** Variable ");
5766: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5767: fprintf(ficgp, "**********\n#\n");
5768:
5769:
5770: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
5771: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5772: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
5773:
5774: fprintf(ficresprobcor, "\n#********** Variable ");
5775: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5776: fprintf(ficresprobcor, "**********\n#");
5777: if(invalidvarcomb[j1]){
5778: fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1);
5779: fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1);
5780: continue;
5781: }
5782: }
5783: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
5784: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
5785: gp=vector(1,(nlstate)*(nlstate+ndeath));
5786: gm=vector(1,(nlstate)*(nlstate+ndeath));
5787: for (age=bage; age<=fage; age ++){
5788: cov[2]=age;
5789: if(nagesqr==1)
5790: cov[3]= age*age;
5791: for (k=1; k<=cptcovn;k++) {
5792: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
5793: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
5794: * 1 1 1 1 1
5795: * 2 2 1 1 1
5796: * 3 1 2 1 1
5797: */
5798: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
5799: }
5800: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5801: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
5802: for (k=1; k<=cptcovprod;k++)
5803: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
5804:
5805:
5806: for(theta=1; theta <=npar; theta++){
5807: for(i=1; i<=npar; i++)
5808: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
5809:
5810: pmij(pmmij,cov,ncovmodel,xp,nlstate);
5811:
5812: k=0;
5813: for(i=1; i<= (nlstate); i++){
5814: for(j=1; j<=(nlstate+ndeath);j++){
5815: k=k+1;
5816: gp[k]=pmmij[i][j];
5817: }
5818: }
5819:
5820: for(i=1; i<=npar; i++)
5821: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
5822:
5823: pmij(pmmij,cov,ncovmodel,xp,nlstate);
5824: k=0;
5825: for(i=1; i<=(nlstate); i++){
5826: for(j=1; j<=(nlstate+ndeath);j++){
5827: k=k+1;
5828: gm[k]=pmmij[i][j];
5829: }
5830: }
5831:
5832: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
5833: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
5834: }
5835:
5836: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
5837: for(theta=1; theta <=npar; theta++)
5838: trgradg[j][theta]=gradg[theta][j];
5839:
5840: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
5841: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
5842:
5843: pmij(pmmij,cov,ncovmodel,x,nlstate);
5844:
5845: k=0;
5846: for(i=1; i<=(nlstate); i++){
5847: for(j=1; j<=(nlstate+ndeath);j++){
5848: k=k+1;
5849: mu[k][(int) age]=pmmij[i][j];
5850: }
5851: }
5852: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
5853: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
5854: varpij[i][j][(int)age] = doldm[i][j];
5855:
5856: /*printf("\n%d ",(int)age);
5857: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
5858: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
5859: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
5860: }*/
5861:
5862: fprintf(ficresprob,"\n%d ",(int)age);
5863: fprintf(ficresprobcov,"\n%d ",(int)age);
5864: fprintf(ficresprobcor,"\n%d ",(int)age);
5865:
5866: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
5867: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
5868: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
5869: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
5870: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
5871: }
5872: i=0;
5873: for (k=1; k<=(nlstate);k++){
5874: for (l=1; l<=(nlstate+ndeath);l++){
5875: i++;
5876: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
5877: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
5878: for (j=1; j<=i;j++){
5879: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
5880: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
5881: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
5882: }
5883: }
5884: }/* end of loop for state */
5885: } /* end of loop for age */
5886: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
5887: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
5888: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
5889: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
5890:
5891: /* Confidence intervalle of pij */
5892: /*
5893: fprintf(ficgp,"\nunset parametric;unset label");
5894: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
5895: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
5896: 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);
5897: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
5898: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
5899: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
5900: */
5901:
5902: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
5903: first1=1;first2=2;
5904: for (k2=1; k2<=(nlstate);k2++){
5905: for (l2=1; l2<=(nlstate+ndeath);l2++){
5906: if(l2==k2) continue;
5907: j=(k2-1)*(nlstate+ndeath)+l2;
5908: for (k1=1; k1<=(nlstate);k1++){
5909: for (l1=1; l1<=(nlstate+ndeath);l1++){
5910: if(l1==k1) continue;
5911: i=(k1-1)*(nlstate+ndeath)+l1;
5912: if(i<=j) continue;
5913: for (age=bage; age<=fage; age ++){
5914: if ((int)age %5==0){
5915: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
5916: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
5917: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
5918: mu1=mu[i][(int) age]/stepm*YEARM ;
5919: mu2=mu[j][(int) age]/stepm*YEARM;
5920: c12=cv12/sqrt(v1*v2);
5921: /* Computing eigen value of matrix of covariance */
5922: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
5923: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
5924: if ((lc2 <0) || (lc1 <0) ){
5925: if(first2==1){
5926: first1=0;
5927: 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);
5928: }
5929: 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);
5930: /* lc1=fabs(lc1); */ /* If we want to have them positive */
5931: /* lc2=fabs(lc2); */
5932: }
5933:
5934: /* Eigen vectors */
5935: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
5936: /*v21=sqrt(1.-v11*v11); *//* error */
5937: v21=(lc1-v1)/cv12*v11;
5938: v12=-v21;
5939: v22=v11;
5940: tnalp=v21/v11;
5941: if(first1==1){
5942: first1=0;
5943: 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);
5944: }
5945: 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);
5946: /*printf(fignu*/
5947: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
5948: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
5949: if(first==1){
5950: first=0;
5951: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
5952: fprintf(ficgp,"\nset parametric;unset label");
5953: 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);
5954: fprintf(ficgp,"\nset ter svg size 640, 480");
5955: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
5956: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\"> \
5957: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
5958: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2, \
5959: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5960: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5961: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
5962: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5963: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
5964: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
5965: 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", \
5966: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2), \
5967: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
5968: }else{
5969: first=0;
5970: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
5971: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
5972: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
5973: 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", \
5974: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2), \
5975: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
5976: }/* if first */
5977: } /* age mod 5 */
5978: } /* end loop age */
5979: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5980: first=1;
5981: } /*l12 */
5982: } /* k12 */
5983: } /*l1 */
5984: }/* k1 */
5985: } /* loop on combination of covariates j1 */
5986: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
5987: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
5988: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
5989: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
5990: free_vector(xp,1,npar);
5991: fclose(ficresprob);
5992: fclose(ficresprobcov);
5993: fclose(ficresprobcor);
5994: fflush(ficgp);
5995: fflush(fichtmcov);
5996: }
5997:
5998:
5999: /******************* Printing html file ***********/
6000: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
6001: int lastpass, int stepm, int weightopt, char model[],\
6002: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
6003: int popforecast, int prevfcast, int backcast, int estepm , \
6004: double jprev1, double mprev1,double anprev1, double dateprev1, \
6005: double jprev2, double mprev2,double anprev2, double dateprev2){
6006: int jj1, k1, i1, cpt, k4, nres;
6007:
6008: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
6009: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
6010: </ul>");
6011: fprintf(fichtm,"<ul><li> model=1+age+%s\n \
6012: </ul>", model);
6013: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
6014: 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",
6015: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
6016: 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) ",
6017: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
6018: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
6019: fprintf(fichtm,"\
6020: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
6021: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
6022: fprintf(fichtm,"\
6023: - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
6024: stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
6025: fprintf(fichtm,"\
6026: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
6027: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
6028: fprintf(fichtm,"\
6029: - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
6030: subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
6031: fprintf(fichtm,"\
6032: - (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): \
6033: <a href=\"%s\">%s</a> <br>\n",
6034: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
6035: if(prevfcast==1){
6036: fprintf(fichtm,"\
6037: - Prevalence projections by age and states: \
6038: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
6039: }
6040:
6041: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
6042:
6043: m=pow(2,cptcoveff);
6044: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
6045:
6046: jj1=0;
6047:
6048: for(nres=1; nres <= nresult; nres++) /* For each resultline */
6049: for(k1=1; k1<=m;k1++){
6050: if(TKresult[nres]!= k1)
6051: continue;
6052:
6053: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
6054: jj1++;
6055: if (cptcovn > 0) {
6056: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
6057: for (cpt=1; cpt<=cptcoveff;cpt++){
6058: fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
6059: printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
6060: /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
6061: /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
6062: }
6063: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6064: fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6065: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
6066: }
6067:
6068: /* if(nqfveff+nqtveff 0) */ /* Test to be done */
6069: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
6070: if(invalidvarcomb[k1]){
6071: fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1);
6072: printf("\nCombination (%d) ignored because no cases \n",k1);
6073: continue;
6074: }
6075: }
6076: /* aij, bij */
6077: 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> \
6078: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
6079: /* Pij */
6080: 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> \
6081: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
6082: /* Quasi-incidences */
6083: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
6084: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
6085: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
6086: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
6087: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
6088: /* Survival functions (period) in state j */
6089: for(cpt=1; cpt<=nlstate;cpt++){
6090: 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> \
6091: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
6092: }
6093: /* State specific survival functions (period) */
6094: for(cpt=1; cpt<=nlstate;cpt++){
6095: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
6096: Or probability to survive in various states (1 to %d) being in state %d at different ages. \
6097: <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);
6098: }
6099: /* Period (stable) prevalence in each health state */
6100: for(cpt=1; cpt<=nlstate;cpt++){
6101: 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> \
6102: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
6103: }
6104: if(backcast==1){
6105: /* Period (stable) back prevalence in each health state */
6106: for(cpt=1; cpt<=nlstate;cpt++){
6107: fprintf(fichtm,"<br>\n- Convergence to period (stable) back 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> \
6108: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
6109: }
6110: }
6111: if(prevfcast==1){
6112: /* Projection of prevalence up to period (stable) prevalence in each health state */
6113: for(cpt=1; cpt<=nlstate;cpt++){
6114: 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> \
6115: <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);
6116: }
6117: }
6118:
6119: for(cpt=1; cpt<=nlstate;cpt++) {
6120: 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> \
6121: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
6122: }
6123: /* } /\* end i1 *\/ */
6124: }/* End k1 */
6125: fprintf(fichtm,"</ul>");
6126:
6127: fprintf(fichtm,"\
6128: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
6129: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
6130: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
6131: But because parameters are usually highly correlated (a higher incidence of disability \
6132: and a higher incidence of recovery can give very close observed transition) it might \
6133: be very useful to look not only at linear confidence intervals estimated from the \
6134: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
6135: (parameters) of the logistic regression, it might be more meaningful to visualize the \
6136: covariance matrix of the one-step probabilities. \
6137: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
6138:
6139: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
6140: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
6141: fprintf(fichtm,"\
6142: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
6143: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
6144:
6145: fprintf(fichtm,"\
6146: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
6147: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
6148: fprintf(fichtm,"\
6149: - 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): \
6150: <a href=\"%s\">%s</a> <br>\n</li>",
6151: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
6152: fprintf(fichtm,"\
6153: - (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): \
6154: <a href=\"%s\">%s</a> <br>\n</li>",
6155: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
6156: fprintf(fichtm,"\
6157: - 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",
6158: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
6159: fprintf(fichtm,"\
6160: - 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",
6161: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
6162: fprintf(fichtm,"\
6163: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
6164: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
6165:
6166: /* if(popforecast==1) fprintf(fichtm,"\n */
6167: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
6168: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
6169: /* <br>",fileres,fileres,fileres,fileres); */
6170: /* else */
6171: /* 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); */
6172: fflush(fichtm);
6173: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
6174:
6175: m=pow(2,cptcoveff);
6176: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
6177:
6178: jj1=0;
6179:
6180: for(nres=1; nres <= nresult; nres++) /* For each resultline */
6181: for(k1=1; k1<=m;k1++){
6182: if(TKresult[nres]!= k1)
6183: continue;
6184: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
6185: jj1++;
6186: if (cptcovn > 0) {
6187: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
6188: for (cpt=1; cpt<=cptcoveff;cpt++) /**< cptcoveff number of variables */
6189: fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
6190: /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
6191: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6192: fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6193: }
6194:
6195: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
6196:
6197: if(invalidvarcomb[k1]){
6198: fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1);
6199: continue;
6200: }
6201: }
6202: for(cpt=1; cpt<=nlstate;cpt++) {
6203: fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
6204: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
6205: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
6206: }
6207: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
6208: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
6209: true period expectancies (those weighted with period prevalences are also\
6210: drawn in addition to the population based expectancies computed using\
6211: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
6212: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
6213: /* } /\* end i1 *\/ */
6214: }/* End k1 */
6215: fprintf(fichtm,"</ul>");
6216: fflush(fichtm);
6217: }
6218:
6219: /******************* Gnuplot file **************/
6220: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
6221:
6222: char dirfileres[132],optfileres[132];
6223: char gplotcondition[132];
6224: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
6225: int lv=0, vlv=0, kl=0;
6226: int ng=0;
6227: int vpopbased;
6228: int ioffset; /* variable offset for columns */
6229: int nres=0; /* Index of resultline */
6230:
6231: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
6232: /* printf("Problem with file %s",optionfilegnuplot); */
6233: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
6234: /* } */
6235:
6236: /*#ifdef windows */
6237: fprintf(ficgp,"cd \"%s\" \n",pathc);
6238: /*#endif */
6239: m=pow(2,cptcoveff);
6240:
6241: /* Contribution to likelihood */
6242: /* Plot the probability implied in the likelihood */
6243: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
6244: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
6245: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
6246: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
6247: /* nice for mle=4 plot by number of matrix products.
6248: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
6249: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
6250: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
6251: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
6252: 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));
6253: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
6254: 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));
6255: for (i=1; i<= nlstate ; i ++) {
6256: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
6257: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
6258: 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);
6259: for (j=2; j<= nlstate+ndeath ; j ++) {
6260: 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);
6261: }
6262: fprintf(ficgp,";\nset out; unset ylabel;\n");
6263: }
6264: /* 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 */
6265: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
6266: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
6267: fprintf(ficgp,"\nset out;unset log\n");
6268: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
6269:
6270: strcpy(dirfileres,optionfilefiname);
6271: strcpy(optfileres,"vpl");
6272: /* 1eme*/
6273: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
6274: for (k1=1; k1<= m ; k1 ++) /* For each valid combination of covariate */
6275: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6276: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
6277: if(TKresult[nres]!= k1)
6278: continue;
6279: /* We are interested in selected combination by the resultline */
6280: printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
6281: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
6282: for (k=1; k<=cptcoveff; k++){ /* For each covariate k get corresponding value lv for combination k1 */
6283: lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
6284: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6285: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6286: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6287: vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
6288: /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
6289: printf(" V%d=%d ",Tvaraff[k],vlv);
6290: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6291: }
6292: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6293: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6294: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6295: }
6296: printf("\n#\n");
6297: fprintf(ficgp,"\n#\n");
6298: if(invalidvarcomb[k1]){
6299: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6300: continue;
6301: }
6302:
6303: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
6304: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
6305: fprintf(ficgp,"set xlabel \"Age\" \n\
6306: set ylabel \"Probability\" \n \
6307: set ter svg size 640, 480\n \
6308: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
6309:
6310: for (i=1; i<= nlstate ; i ++) {
6311: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
6312: else fprintf(ficgp," %%*lf (%%*lf)");
6313: }
6314: 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);
6315: for (i=1; i<= nlstate ; i ++) {
6316: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
6317: else fprintf(ficgp," %%*lf (%%*lf)");
6318: }
6319: 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);
6320: for (i=1; i<= nlstate ; i ++) {
6321: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
6322: else fprintf(ficgp," %%*lf (%%*lf)");
6323: }
6324: 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));
6325: if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
6326: /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
6327: fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
6328: if(cptcoveff ==0){
6329: fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ", 2+(cpt-1), cpt );
6330: }else{
6331: kl=0;
6332: for (k=1; k<=cptcoveff; k++){ /* For each combination of covariate */
6333: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
6334: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6335: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6336: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6337: vlv= nbcode[Tvaraff[k]][lv];
6338: kl++;
6339: /* 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 *\/ */
6340: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
6341: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
6342: /* '' 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*/
6343: if(k==cptcoveff){
6344: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
6345: 4+(cpt-1), cpt ); /* 4 or 6 ?*/
6346: }else{
6347: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
6348: kl++;
6349: }
6350: } /* end covariate */
6351: } /* end if no covariate */
6352: } /* end if backcast */
6353: fprintf(ficgp,"\nset out \n");
6354: } /* k1 */
6355: } /* cpt */
6356:
6357:
6358: /*2 eme*/
6359: for (k1=1; k1<= m ; k1 ++)
6360: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6361: if(TKresult[nres]!= k1)
6362: continue;
6363: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
6364: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
6365: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6366: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6367: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6368: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6369: vlv= nbcode[Tvaraff[k]][lv];
6370: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6371: }
6372: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6373: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6374: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6375: }
6376: fprintf(ficgp,"\n#\n");
6377: if(invalidvarcomb[k1]){
6378: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6379: continue;
6380: }
6381:
6382: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
6383: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
6384: if(vpopbased==0)
6385: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
6386: else
6387: fprintf(ficgp,"\nreplot ");
6388: for (i=1; i<= nlstate+1 ; i ++) {
6389: k=2*i;
6390: 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);
6391: for (j=1; j<= nlstate+1 ; j ++) {
6392: if (j==i) fprintf(ficgp," %%lf (%%lf)");
6393: else fprintf(ficgp," %%*lf (%%*lf)");
6394: }
6395: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
6396: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
6397: 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);
6398: for (j=1; j<= nlstate+1 ; j ++) {
6399: if (j==i) fprintf(ficgp," %%lf (%%lf)");
6400: else fprintf(ficgp," %%*lf (%%*lf)");
6401: }
6402: fprintf(ficgp,"\" t\"\" w l lt 0,");
6403: 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);
6404: for (j=1; j<= nlstate+1 ; j ++) {
6405: if (j==i) fprintf(ficgp," %%lf (%%lf)");
6406: else fprintf(ficgp," %%*lf (%%*lf)");
6407: }
6408: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
6409: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
6410: } /* state */
6411: } /* vpopbased */
6412: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
6413: } /* k1 end 2 eme*/
6414:
6415:
6416: /*3eme*/
6417: for (k1=1; k1<= m ; k1 ++)
6418: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6419: if(TKresult[nres]!= k)
6420: continue;
6421:
6422: for (cpt=1; cpt<= nlstate ; cpt ++) {
6423: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: combination=%d state=%d",k1, cpt);
6424: for (k=1; k<=cptcoveff; k++){ /* For each covariate dummy combination and each value */
6425: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6426: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6427: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6428: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6429: vlv= nbcode[Tvaraff[k]][lv];
6430: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6431: }
6432: /* for(k=1; k <= ncovds; k++){ */
6433: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6434: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6435: }
6436: fprintf(ficgp,"\n#\n");
6437: if(invalidvarcomb[k1]){
6438: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6439: continue;
6440: }
6441:
6442: /* k=2+nlstate*(2*cpt-2); */
6443: k=2+(nlstate+1)*(cpt-1);
6444: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
6445: fprintf(ficgp,"set ter svg size 640, 480\n\
6446: 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);
6447: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
6448: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
6449: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
6450: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
6451: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
6452: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
6453:
6454: */
6455: for (i=1; i< nlstate ; i ++) {
6456: 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);
6457: /* 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);*/
6458:
6459: }
6460: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
6461: }
6462: }
6463:
6464: /* 4eme */
6465: /* Survival functions (period) from state i in state j by initial state i */
6466: for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
6467: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6468: if(TKresult[nres]!= k1)
6469: continue;
6470:
6471: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
6472: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
6473: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
6474: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6475: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6476: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6477: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6478: vlv= nbcode[Tvaraff[k]][lv];
6479: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6480: }
6481: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6482: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6483: }
6484: fprintf(ficgp,"\n#\n");
6485: if(invalidvarcomb[k1]){
6486: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6487: continue;
6488: }
6489:
6490: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
6491: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
6492: set ter svg size 640, 480\n \
6493: unset log y\n \
6494: plot [%.f:%.f] ", ageminpar, agemaxpar);
6495: k=3;
6496: for (i=1; i<= nlstate ; i ++){
6497: if(i==1){
6498: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
6499: }else{
6500: fprintf(ficgp,", '' ");
6501: }
6502: l=(nlstate+ndeath)*(i-1)+1;
6503: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
6504: for (j=2; j<= nlstate+ndeath ; j ++)
6505: fprintf(ficgp,"+$%d",k+l+j-1);
6506: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
6507: } /* nlstate */
6508: fprintf(ficgp,"\nset out\n");
6509: } /* end cpt state*/
6510: } /* end covariate */
6511:
6512: /* 5eme */
6513: /* Survival functions (period) from state i in state j by final state j */
6514: for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
6515: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6516: if(TKresult[nres]!= k1)
6517: continue;
6518: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
6519:
6520: 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);
6521: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
6522: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6523: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6524: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6525: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6526: vlv= nbcode[Tvaraff[k]][lv];
6527: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6528: }
6529: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6530: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6531: }
6532: fprintf(ficgp,"\n#\n");
6533: if(invalidvarcomb[k1]){
6534: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6535: continue;
6536: }
6537:
6538: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
6539: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
6540: set ter svg size 640, 480\n \
6541: unset log y\n \
6542: plot [%.f:%.f] ", ageminpar, agemaxpar);
6543: k=3;
6544: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
6545: if(j==1)
6546: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
6547: else
6548: fprintf(ficgp,", '' ");
6549: l=(nlstate+ndeath)*(cpt-1) +j;
6550: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
6551: /* for (i=2; i<= nlstate+ndeath ; i ++) */
6552: /* fprintf(ficgp,"+$%d",k+l+i-1); */
6553: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
6554: } /* nlstate */
6555: fprintf(ficgp,", '' ");
6556: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
6557: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
6558: l=(nlstate+ndeath)*(cpt-1) +j;
6559: if(j < nlstate)
6560: fprintf(ficgp,"$%d +",k+l);
6561: else
6562: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
6563: }
6564: fprintf(ficgp,"\nset out\n");
6565: } /* end cpt state*/
6566: } /* end covariate */
6567:
6568: /* 6eme */
6569: /* CV preval stable (period) for each covariate */
6570: for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
6571: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6572: if(TKresult[nres]!= k1)
6573: continue;
6574: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
6575:
6576: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
6577: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
6578: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6579: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6580: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6581: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6582: vlv= nbcode[Tvaraff[k]][lv];
6583: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6584: }
6585: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6586: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6587: }
6588: fprintf(ficgp,"\n#\n");
6589: if(invalidvarcomb[k1]){
6590: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6591: continue;
6592: }
6593:
6594: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
6595: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
6596: set ter svg size 640, 480\n \
6597: unset log y\n \
6598: plot [%.f:%.f] ", ageminpar, agemaxpar);
6599: k=3; /* Offset */
6600: for (i=1; i<= nlstate ; i ++){
6601: if(i==1)
6602: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
6603: else
6604: fprintf(ficgp,", '' ");
6605: l=(nlstate+ndeath)*(i-1)+1;
6606: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
6607: for (j=2; j<= nlstate ; j ++)
6608: fprintf(ficgp,"+$%d",k+l+j-1);
6609: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
6610: } /* nlstate */
6611: fprintf(ficgp,"\nset out\n");
6612: } /* end cpt state*/
6613: } /* end covariate */
6614:
6615:
6616: /* 7eme */
6617: if(backcast == 1){
6618: /* CV back preval stable (period) for each covariate */
6619: for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
6620: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6621: if(TKresult[nres]!= k1)
6622: continue;
6623: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
6624: fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
6625: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
6626: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
6627: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6628: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6629: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6630: vlv= nbcode[Tvaraff[k]][lv];
6631: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6632: }
6633: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6634: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6635: }
6636: fprintf(ficgp,"\n#\n");
6637: if(invalidvarcomb[k1]){
6638: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6639: continue;
6640: }
6641:
6642: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
6643: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
6644: set ter svg size 640, 480\n \
6645: unset log y\n \
6646: plot [%.f:%.f] ", ageminpar, agemaxpar);
6647: k=3; /* Offset */
6648: for (i=1; i<= nlstate ; i ++){
6649: if(i==1)
6650: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
6651: else
6652: fprintf(ficgp,", '' ");
6653: /* l=(nlstate+ndeath)*(i-1)+1; */
6654: l=(nlstate+ndeath)*(cpt-1)+1;
6655: /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
6656: /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
6657: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
6658: /* for (j=2; j<= nlstate ; j ++) */
6659: /* fprintf(ficgp,"+$%d",k+l+j-1); */
6660: /* /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
6661: fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
6662: } /* nlstate */
6663: fprintf(ficgp,"\nset out\n");
6664: } /* end cpt state*/
6665: } /* end covariate */
6666: } /* End if backcast */
6667:
6668: /* 8eme */
6669: if(prevfcast==1){
6670: /* Projection from cross-sectional to stable (period) for each covariate */
6671:
6672: for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
6673: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6674: if(TKresult[nres]!= k1)
6675: continue;
6676: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
6677: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
6678: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
6679: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
6680: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6681: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6682: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6683: vlv= nbcode[Tvaraff[k]][lv];
6684: fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
6685: }
6686: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6687: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6688: }
6689: fprintf(ficgp,"\n#\n");
6690: if(invalidvarcomb[k1]){
6691: fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1);
6692: continue;
6693: }
6694:
6695: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
6696: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
6697: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
6698: set ter svg size 640, 480\n \
6699: unset log y\n \
6700: plot [%.f:%.f] ", ageminpar, agemaxpar);
6701: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
6702: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6703: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6704: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6705: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6706: if(i==1){
6707: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
6708: }else{
6709: fprintf(ficgp,",\\\n '' ");
6710: }
6711: if(cptcoveff ==0){ /* No covariate */
6712: ioffset=2; /* Age is in 2 */
6713: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
6714: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
6715: /*# V1 = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
6716: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
6717: fprintf(ficgp," u %d:(", ioffset);
6718: if(i==nlstate+1)
6719: fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ", \
6720: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
6721: else
6722: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
6723: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
6724: }else{ /* more than 2 covariates */
6725: if(cptcoveff ==1){
6726: ioffset=4; /* Age is in 4 */
6727: }else{
6728: ioffset=6; /* Age is in 6 */
6729: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6730: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6731: }
6732: fprintf(ficgp," u %d:(",ioffset);
6733: kl=0;
6734: strcpy(gplotcondition,"(");
6735: for (k=1; k<=cptcoveff; k++){ /* For each covariate writing the chain of conditions */
6736: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
6737: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6738: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6739: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6740: vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
6741: kl++;
6742: sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
6743: kl++;
6744: if(k <cptcoveff && cptcoveff>1)
6745: sprintf(gplotcondition+strlen(gplotcondition)," && ");
6746: }
6747: strcpy(gplotcondition+strlen(gplotcondition),")");
6748: /* 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 *\/ */
6749: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
6750: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
6751: /* '' 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*/
6752: if(i==nlstate+1){
6753: fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
6754: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
6755: }else{
6756: fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
6757: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
6758: }
6759: } /* end if covariate */
6760: } /* nlstate */
6761: fprintf(ficgp,"\nset out\n");
6762: } /* end cpt state*/
6763: } /* end covariate */
6764: } /* End if prevfcast */
6765:
6766:
6767: /* proba elementaires */
6768: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
6769: for(i=1,jk=1; i <=nlstate; i++){
6770: fprintf(ficgp,"# initial state %d\n",i);
6771: for(k=1; k <=(nlstate+ndeath); k++){
6772: if (k != i) {
6773: fprintf(ficgp,"# current state %d\n",k);
6774: for(j=1; j <=ncovmodel; j++){
6775: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
6776: jk++;
6777: }
6778: fprintf(ficgp,"\n");
6779: }
6780: }
6781: }
6782: fprintf(ficgp,"##############\n#\n");
6783:
6784: /*goto avoid;*/
6785: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
6786: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
6787: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
6788: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
6789: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
6790: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6791: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
6792: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6793: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
6794: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
6795: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6796: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
6797: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
6798: fprintf(ficgp,"#\n");
6799: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
6800: fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year \n");
6801: fprintf(ficgp,"#model=%s \n",model);
6802: fprintf(ficgp,"# ng=%d\n",ng);
6803: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
6804: for(jk=1; jk <=m; jk++) /* For each combination of covariate */
6805: for(nres=1; nres <= nresult; nres++){ /* For each resultline */
6806: if(TKresult[nres]!= jk)
6807: continue;
6808: fprintf(ficgp,"# Combination of dummy jk=%d and ",jk);
6809: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
6810: fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
6811: }
6812: fprintf(ficgp,"\n#\n");
6813: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
6814: fprintf(ficgp,"\nset ter svg size 640, 480 ");
6815: if (ng==1){
6816: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
6817: fprintf(ficgp,"\nunset log y");
6818: }else if (ng==2){
6819: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
6820: fprintf(ficgp,"\nset log y");
6821: }else if (ng==3){
6822: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
6823: fprintf(ficgp,"\nset log y");
6824: }else
6825: fprintf(ficgp,"\nunset title ");
6826: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
6827: i=1;
6828: for(k2=1; k2<=nlstate; k2++) {
6829: k3=i;
6830: for(k=1; k<=(nlstate+ndeath); k++) {
6831: if (k != k2){
6832: switch( ng) {
6833: case 1:
6834: if(nagesqr==0)
6835: fprintf(ficgp," p%d+p%d*x",i,i+1);
6836: else /* nagesqr =1 */
6837: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
6838: break;
6839: case 2: /* ng=2 */
6840: if(nagesqr==0)
6841: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
6842: else /* nagesqr =1 */
6843: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
6844: break;
6845: case 3:
6846: if(nagesqr==0)
6847: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
6848: else /* nagesqr =1 */
6849: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
6850: break;
6851: }
6852: ij=1;/* To be checked else nbcode[0][0] wrong */
6853: ijp=1; /* product no age */
6854: /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
6855: for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
6856: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
6857: if(j==Tage[ij]) { /* Product by age */
6858: if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
6859: if(Dummy[j]==0){
6860: fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
6861: }else{ /* quantitative */
6862: fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
6863: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
6864: }
6865: ij++;
6866: }
6867: }else if(j==Tprod[ijp]) { /* */
6868: /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
6869: if(ijp <=cptcovprod) { /* Product */
6870: if(Dummy[Tvard[ijp][1]]==0){/* Vn is dummy */
6871: if(Dummy[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
6872: /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
6873: fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
6874: }else{ /* Vn is dummy and Vm is quanti */
6875: /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
6876: fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
6877: }
6878: }else{ /* Vn*Vm Vn is quanti */
6879: if(Dummy[Tvard[ijp][2]]==0){
6880: fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
6881: }else{ /* Both quanti */
6882: fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
6883: }
6884: }
6885: }
6886: } else{ /* simple covariate */
6887: /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
6888: if(Dummy[j]==0){
6889: fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /* */
6890: }else{ /* quantitative */
6891: fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
6892: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
6893: }
6894: } /* end simple */
6895: } /* end j */
6896: }else{
6897: i=i-ncovmodel;
6898: if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
6899: fprintf(ficgp," (1.");
6900: }
6901:
6902: if(ng != 1){
6903: fprintf(ficgp,")/(1");
6904:
6905: for(k1=1; k1 <=nlstate; k1++){
6906: if(nagesqr==0)
6907: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
6908: else /* nagesqr =1 */
6909: 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);
6910:
6911: ij=1;
6912: for(j=3; j <=ncovmodel-nagesqr; j++){
6913: if((j-2)==Tage[ij]) { /* Bug valgrind */
6914: if(ij <=cptcovage) { /* Bug valgrind */
6915: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
6916: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
6917: ij++;
6918: }
6919: }
6920: else
6921: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
6922: }
6923: fprintf(ficgp,")");
6924: }
6925: fprintf(ficgp,")");
6926: if(ng ==2)
6927: fprintf(ficgp," t \"p%d%d\" ", k2,k);
6928: else /* ng= 3 */
6929: fprintf(ficgp," t \"i%d%d\" ", k2,k);
6930: }else{ /* end ng <> 1 */
6931: if( k !=k2) /* logit p11 is hard to draw */
6932: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
6933: }
6934: if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
6935: fprintf(ficgp,",");
6936: if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
6937: fprintf(ficgp,",");
6938: i=i+ncovmodel;
6939: } /* end k */
6940: } /* end k2 */
6941: fprintf(ficgp,"\n set out\n");
6942: } /* end jk */
6943: } /* end ng */
6944: /* avoid: */
6945: fflush(ficgp);
6946: } /* end gnuplot */
6947:
6948:
6949: /*************** Moving average **************/
6950: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
6951: int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
6952:
6953: int i, cpt, cptcod;
6954: int modcovmax =1;
6955: int mobilavrange, mob;
6956: int iage=0;
6957:
6958: double sum=0.;
6959: double age;
6960: double *sumnewp, *sumnewm;
6961: double *agemingood, *agemaxgood; /* Currently identical for all covariates */
6962:
6963:
6964: /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose */
6965: /* a covariate has 2 modalities, should be equal to ncovcombmax *\/ */
6966:
6967: sumnewp = vector(1,ncovcombmax);
6968: sumnewm = vector(1,ncovcombmax);
6969: agemingood = vector(1,ncovcombmax);
6970: agemaxgood = vector(1,ncovcombmax);
6971:
6972: for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
6973: sumnewm[cptcod]=0.;
6974: sumnewp[cptcod]=0.;
6975: agemingood[cptcod]=0;
6976: agemaxgood[cptcod]=0;
6977: }
6978: if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
6979:
6980: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
6981: if(mobilav==1) mobilavrange=5; /* default */
6982: else mobilavrange=mobilav;
6983: for (age=bage; age<=fage; age++)
6984: for (i=1; i<=nlstate;i++)
6985: for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
6986: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
6987: /* We keep the original values on the extreme ages bage, fage and for
6988: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
6989: we use a 5 terms etc. until the borders are no more concerned.
6990: */
6991: for (mob=3;mob <=mobilavrange;mob=mob+2){
6992: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
6993: for (i=1; i<=nlstate;i++){
6994: for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
6995: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
6996: for (cpt=1;cpt<=(mob-1)/2;cpt++){
6997: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
6998: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
6999: }
7000: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
7001: }
7002: }
7003: }/* end age */
7004: }/* end mob */
7005: }else
7006: return -1;
7007: for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
7008: /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
7009: if(invalidvarcomb[cptcod]){
7010: printf("\nCombination (%d) ignored because no cases \n",cptcod);
7011: continue;
7012: }
7013:
7014: agemingood[cptcod]=fage-(mob-1)/2;
7015: for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
7016: sumnewm[cptcod]=0.;
7017: for (i=1; i<=nlstate;i++){
7018: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
7019: }
7020: if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
7021: agemingood[cptcod]=age;
7022: }else{ /* bad */
7023: for (i=1; i<=nlstate;i++){
7024: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
7025: } /* i */
7026: } /* end bad */
7027: }/* age */
7028: sum=0.;
7029: for (i=1; i<=nlstate;i++){
7030: sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
7031: }
7032: if(fabs(sum - 1.) > 1.e-3) { /* bad */
7033: printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
7034: /* for (i=1; i<=nlstate;i++){ */
7035: /* mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
7036: /* } /\* i *\/ */
7037: } /* end bad */
7038: /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
7039: /* From youngest, finding the oldest wrong */
7040: agemaxgood[cptcod]=bage+(mob-1)/2;
7041: for (age=bage+(mob-1)/2; age<=fage; age++){
7042: sumnewm[cptcod]=0.;
7043: for (i=1; i<=nlstate;i++){
7044: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
7045: }
7046: if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
7047: agemaxgood[cptcod]=age;
7048: }else{ /* bad */
7049: for (i=1; i<=nlstate;i++){
7050: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
7051: } /* i */
7052: } /* end bad */
7053: }/* age */
7054: sum=0.;
7055: for (i=1; i<=nlstate;i++){
7056: sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
7057: }
7058: if(fabs(sum - 1.) > 1.e-3) { /* bad */
7059: printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
7060: /* for (i=1; i<=nlstate;i++){ */
7061: /* mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
7062: /* } /\* i *\/ */
7063: } /* end bad */
7064:
7065: for (age=bage; age<=fage; age++){
7066: /* printf("%d %d ", cptcod, (int)age); */
7067: sumnewp[cptcod]=0.;
7068: sumnewm[cptcod]=0.;
7069: for (i=1; i<=nlstate;i++){
7070: sumnewp[cptcod]+=probs[(int)age][i][cptcod];
7071: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
7072: /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
7073: }
7074: /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
7075: }
7076: /* printf("\n"); */
7077: /* } */
7078: /* brutal averaging */
7079: for (i=1; i<=nlstate;i++){
7080: for (age=1; age<=bage; age++){
7081: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
7082: /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
7083: }
7084: for (age=fage; age<=AGESUP; age++){
7085: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
7086: /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
7087: }
7088: } /* end i status */
7089: for (i=nlstate+1; i<=nlstate+ndeath;i++){
7090: for (age=1; age<=AGESUP; age++){
7091: /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
7092: mobaverage[(int)age][i][cptcod]=0.;
7093: }
7094: }
7095: }/* end cptcod */
7096: free_vector(sumnewm,1, ncovcombmax);
7097: free_vector(sumnewp,1, ncovcombmax);
7098: free_vector(agemaxgood,1, ncovcombmax);
7099: free_vector(agemingood,1, ncovcombmax);
7100: return 0;
7101: }/* End movingaverage */
7102:
7103:
7104: /************** Forecasting ******************/
7105: 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){
7106: /* proj1, year, month, day of starting projection
7107: agemin, agemax range of age
7108: dateprev1 dateprev2 range of dates during which prevalence is computed
7109: anproj2 year of en of projection (same day and month as proj1).
7110: */
7111: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
7112: double agec; /* generic age */
7113: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
7114: double *popeffectif,*popcount;
7115: double ***p3mat;
7116: /* double ***mobaverage; */
7117: char fileresf[FILENAMELENGTH];
7118:
7119: agelim=AGESUP;
7120: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
7121: in each health status at the date of interview (if between dateprev1 and dateprev2).
7122: We still use firstpass and lastpass as another selection.
7123: */
7124: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
7125: /* firstpass, lastpass, stepm, weightopt, model); */
7126:
7127: strcpy(fileresf,"F_");
7128: strcat(fileresf,fileresu);
7129: if((ficresf=fopen(fileresf,"w"))==NULL) {
7130: printf("Problem with forecast resultfile: %s\n", fileresf);
7131: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
7132: }
7133: printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
7134: fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
7135:
7136: if (cptcoveff==0) ncodemax[cptcoveff]=1;
7137:
7138:
7139: stepsize=(int) (stepm+YEARM-1)/YEARM;
7140: if (stepm<=12) stepsize=1;
7141: if(estepm < stepm){
7142: printf ("Problem %d lower than %d\n",estepm, stepm);
7143: }
7144: else hstepm=estepm;
7145:
7146: hstepm=hstepm/stepm;
7147: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
7148: fractional in yp1 */
7149: anprojmean=yp;
7150: yp2=modf((yp1*12),&yp);
7151: mprojmean=yp;
7152: yp1=modf((yp2*30.5),&yp);
7153: jprojmean=yp;
7154: if(jprojmean==0) jprojmean=1;
7155: if(mprojmean==0) jprojmean=1;
7156:
7157: i1=pow(2,cptcoveff);
7158: if (cptcovn < 1){i1=1;}
7159:
7160: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
7161:
7162: fprintf(ficresf,"#****** Routine prevforecast **\n");
7163:
7164: /* if (h==(int)(YEARM*yearp)){ */
7165: for(nres=1; nres <= nresult; nres++) /* For each resultline */
7166: for(k=1; k<=i1;k++){
7167: if(TKresult[nres]!= k)
7168: continue;
7169: if(invalidvarcomb[k]){
7170: printf("\nCombination (%d) projection ignored because no cases \n",k);
7171: continue;
7172: }
7173: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
7174: for(j=1;j<=cptcoveff;j++) {
7175: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7176: }
7177: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
7178: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
7179: fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
7180: }
7181: fprintf(ficresf," yearproj age");
7182: for(j=1; j<=nlstate+ndeath;j++){
7183: for(i=1; i<=nlstate;i++)
7184: fprintf(ficresf," p%d%d",i,j);
7185: fprintf(ficresf," wp.%d",j);
7186: }
7187: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
7188: fprintf(ficresf,"\n");
7189: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
7190: for (agec=fage; agec>=(ageminpar-1); agec--){
7191: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
7192: nhstepm = nhstepm/hstepm;
7193: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7194: oldm=oldms;savm=savms;
7195: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
7196:
7197: for (h=0; h<=nhstepm; h++){
7198: if (h*hstepm/YEARM*stepm ==yearp) {
7199: fprintf(ficresf,"\n");
7200: for(j=1;j<=cptcoveff;j++)
7201: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7202: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
7203: }
7204: for(j=1; j<=nlstate+ndeath;j++) {
7205: ppij=0.;
7206: for(i=1; i<=nlstate;i++) {
7207: if (mobilav==1)
7208: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
7209: else {
7210: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
7211: }
7212: if (h*hstepm/YEARM*stepm== yearp) {
7213: fprintf(ficresf," %.3f", p3mat[i][j][h]);
7214: }
7215: } /* end i */
7216: if (h*hstepm/YEARM*stepm==yearp) {
7217: fprintf(ficresf," %.3f", ppij);
7218: }
7219: }/* end j */
7220: } /* end h */
7221: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7222: } /* end agec */
7223: } /* end yearp */
7224: } /* end k */
7225:
7226: fclose(ficresf);
7227: printf("End of Computing forecasting \n");
7228: fprintf(ficlog,"End of Computing forecasting\n");
7229:
7230: }
7231:
7232: /* /\************** Back Forecasting ******************\/ */
7233: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
7234: /* /\* back1, year, month, day of starting backection */
7235: /* agemin, agemax range of age */
7236: /* dateprev1 dateprev2 range of dates during which prevalence is computed */
7237: /* anback2 year of en of backection (same day and month as back1). */
7238: /* *\/ */
7239: /* int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
7240: /* double agec; /\* generic age *\/ */
7241: /* double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
7242: /* double *popeffectif,*popcount; */
7243: /* double ***p3mat; */
7244: /* /\* double ***mobaverage; *\/ */
7245: /* char fileresfb[FILENAMELENGTH]; */
7246:
7247: /* agelim=AGESUP; */
7248: /* /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
7249: /* in each health status at the date of interview (if between dateprev1 and dateprev2). */
7250: /* We still use firstpass and lastpass as another selection. */
7251: /* *\/ */
7252: /* /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
7253: /* /\* firstpass, lastpass, stepm, weightopt, model); *\/ */
7254: /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
7255:
7256: /* strcpy(fileresfb,"FB_"); */
7257: /* strcat(fileresfb,fileresu); */
7258: /* if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
7259: /* printf("Problem with back forecast resultfile: %s\n", fileresfb); */
7260: /* fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
7261: /* } */
7262: /* printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
7263: /* fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
7264:
7265: /* if (cptcoveff==0) ncodemax[cptcoveff]=1; */
7266:
7267: /* /\* if (mobilav!=0) { *\/ */
7268: /* /\* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
7269: /* /\* if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
7270: /* /\* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
7271: /* /\* printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
7272: /* /\* } *\/ */
7273: /* /\* } *\/ */
7274:
7275: /* stepsize=(int) (stepm+YEARM-1)/YEARM; */
7276: /* if (stepm<=12) stepsize=1; */
7277: /* if(estepm < stepm){ */
7278: /* printf ("Problem %d lower than %d\n",estepm, stepm); */
7279: /* } */
7280: /* else hstepm=estepm; */
7281:
7282: /* hstepm=hstepm/stepm; */
7283: /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp and */
7284: /* fractional in yp1 *\/ */
7285: /* anprojmean=yp; */
7286: /* yp2=modf((yp1*12),&yp); */
7287: /* mprojmean=yp; */
7288: /* yp1=modf((yp2*30.5),&yp); */
7289: /* jprojmean=yp; */
7290: /* if(jprojmean==0) jprojmean=1; */
7291: /* if(mprojmean==0) jprojmean=1; */
7292:
7293: /* i1=cptcoveff; */
7294: /* if (cptcovn < 1){i1=1;} */
7295:
7296: /* fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); */
7297:
7298: /* fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
7299:
7300: /* /\* if (h==(int)(YEARM*yearp)){ *\/ */
7301: /* for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
7302: /* for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
7303: /* k=k+1; */
7304: /* fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
7305: /* for(j=1;j<=cptcoveff;j++) { */
7306: /* fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
7307: /* } */
7308: /* fprintf(ficresfb," yearbproj age"); */
7309: /* for(j=1; j<=nlstate+ndeath;j++){ */
7310: /* for(i=1; i<=nlstate;i++) */
7311: /* fprintf(ficresfb," p%d%d",i,j); */
7312: /* fprintf(ficresfb," p.%d",j); */
7313: /* } */
7314: /* for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) { */
7315: /* /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { *\/ */
7316: /* fprintf(ficresfb,"\n"); */
7317: /* fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
7318: /* for (agec=fage; agec>=(ageminpar-1); agec--){ */
7319: /* nhstepm=(int) rint((agelim-agec)*YEARM/stepm); */
7320: /* nhstepm = nhstepm/hstepm; */
7321: /* p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7322: /* oldm=oldms;savm=savms; */
7323: /* hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); */
7324: /* for (h=0; h<=nhstepm; h++){ */
7325: /* if (h*hstepm/YEARM*stepm ==yearp) { */
7326: /* fprintf(ficresfb,"\n"); */
7327: /* for(j=1;j<=cptcoveff;j++) */
7328: /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
7329: /* fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
7330: /* } */
7331: /* for(j=1; j<=nlstate+ndeath;j++) { */
7332: /* ppij=0.; */
7333: /* for(i=1; i<=nlstate;i++) { */
7334: /* if (mobilav==1) */
7335: /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
7336: /* else { */
7337: /* ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
7338: /* } */
7339: /* if (h*hstepm/YEARM*stepm== yearp) { */
7340: /* fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
7341: /* } */
7342: /* } /\* end i *\/ */
7343: /* if (h*hstepm/YEARM*stepm==yearp) { */
7344: /* fprintf(ficresfb," %.3f", ppij); */
7345: /* } */
7346: /* }/\* end j *\/ */
7347: /* } /\* end h *\/ */
7348: /* free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7349: /* } /\* end agec *\/ */
7350: /* } /\* end yearp *\/ */
7351: /* } /\* end cptcod *\/ */
7352: /* } /\* end cptcov *\/ */
7353:
7354: /* /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
7355:
7356: /* fclose(ficresfb); */
7357: /* printf("End of Computing Back forecasting \n"); */
7358: /* fprintf(ficlog,"End of Computing Back forecasting\n"); */
7359:
7360: /* } */
7361:
7362: /************** Forecasting *****not tested NB*************/
7363: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
7364:
7365: /* int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
7366: /* int *popage; */
7367: /* double calagedatem, agelim, kk1, kk2; */
7368: /* double *popeffectif,*popcount; */
7369: /* double ***p3mat,***tabpop,***tabpopprev; */
7370: /* /\* double ***mobaverage; *\/ */
7371: /* char filerespop[FILENAMELENGTH]; */
7372:
7373: /* tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
7374: /* tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
7375: /* agelim=AGESUP; */
7376: /* calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
7377:
7378: /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
7379:
7380:
7381: /* strcpy(filerespop,"POP_"); */
7382: /* strcat(filerespop,fileresu); */
7383: /* if((ficrespop=fopen(filerespop,"w"))==NULL) { */
7384: /* printf("Problem with forecast resultfile: %s\n", filerespop); */
7385: /* fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
7386: /* } */
7387: /* printf("Computing forecasting: result on file '%s' \n", filerespop); */
7388: /* fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
7389:
7390: /* if (cptcoveff==0) ncodemax[cptcoveff]=1; */
7391:
7392: /* /\* if (mobilav!=0) { *\/ */
7393: /* /\* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
7394: /* /\* if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
7395: /* /\* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
7396: /* /\* printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
7397: /* /\* } *\/ */
7398: /* /\* } *\/ */
7399:
7400: /* stepsize=(int) (stepm+YEARM-1)/YEARM; */
7401: /* if (stepm<=12) stepsize=1; */
7402:
7403: /* agelim=AGESUP; */
7404:
7405: /* hstepm=1; */
7406: /* hstepm=hstepm/stepm; */
7407:
7408: /* if (popforecast==1) { */
7409: /* if((ficpop=fopen(popfile,"r"))==NULL) { */
7410: /* printf("Problem with population file : %s\n",popfile);exit(0); */
7411: /* fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
7412: /* } */
7413: /* popage=ivector(0,AGESUP); */
7414: /* popeffectif=vector(0,AGESUP); */
7415: /* popcount=vector(0,AGESUP); */
7416:
7417: /* i=1; */
7418: /* while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
7419:
7420: /* imx=i; */
7421: /* for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
7422: /* } */
7423:
7424: /* for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
7425: /* for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
7426: /* k=k+1; */
7427: /* fprintf(ficrespop,"\n#******"); */
7428: /* for(j=1;j<=cptcoveff;j++) { */
7429: /* fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
7430: /* } */
7431: /* fprintf(ficrespop,"******\n"); */
7432: /* fprintf(ficrespop,"# Age"); */
7433: /* for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
7434: /* if (popforecast==1) fprintf(ficrespop," [Population]"); */
7435:
7436: /* for (cpt=0; cpt<=0;cpt++) { */
7437: /* fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt); */
7438:
7439: /* for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ */
7440: /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); */
7441: /* nhstepm = nhstepm/hstepm; */
7442:
7443: /* p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7444: /* oldm=oldms;savm=savms; */
7445: /* hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); */
7446:
7447: /* for (h=0; h<=nhstepm; h++){ */
7448: /* if (h==(int) (calagedatem+YEARM*cpt)) { */
7449: /* fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
7450: /* } */
7451: /* for(j=1; j<=nlstate+ndeath;j++) { */
7452: /* kk1=0.;kk2=0; */
7453: /* for(i=1; i<=nlstate;i++) { */
7454: /* if (mobilav==1) */
7455: /* kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
7456: /* else { */
7457: /* kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
7458: /* } */
7459: /* } */
7460: /* if (h==(int)(calagedatem+12*cpt)){ */
7461: /* tabpop[(int)(agedeb)][j][cptcod]=kk1; */
7462: /* /\*fprintf(ficrespop," %.3f", kk1); */
7463: /* if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
7464: /* } */
7465: /* } */
7466: /* for(i=1; i<=nlstate;i++){ */
7467: /* kk1=0.; */
7468: /* for(j=1; j<=nlstate;j++){ */
7469: /* kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; */
7470: /* } */
7471: /* tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
7472: /* } */
7473:
7474: /* if (h==(int)(calagedatem+12*cpt)) */
7475: /* for(j=1; j<=nlstate;j++) */
7476: /* fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
7477: /* } */
7478: /* free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7479: /* } */
7480: /* } */
7481:
7482: /* /\******\/ */
7483:
7484: /* for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { */
7485: /* fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt); */
7486: /* for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ */
7487: /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); */
7488: /* nhstepm = nhstepm/hstepm; */
7489:
7490: /* p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7491: /* oldm=oldms;savm=savms; */
7492: /* hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); */
7493: /* for (h=0; h<=nhstepm; h++){ */
7494: /* if (h==(int) (calagedatem+YEARM*cpt)) { */
7495: /* fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
7496: /* } */
7497: /* for(j=1; j<=nlstate+ndeath;j++) { */
7498: /* kk1=0.;kk2=0; */
7499: /* for(i=1; i<=nlstate;i++) { */
7500: /* kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod]; */
7501: /* } */
7502: /* if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1); */
7503: /* } */
7504: /* } */
7505: /* free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
7506: /* } */
7507: /* } */
7508: /* } */
7509: /* } */
7510:
7511: /* /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
7512:
7513: /* if (popforecast==1) { */
7514: /* free_ivector(popage,0,AGESUP); */
7515: /* free_vector(popeffectif,0,AGESUP); */
7516: /* free_vector(popcount,0,AGESUP); */
7517: /* } */
7518: /* free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
7519: /* free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
7520: /* fclose(ficrespop); */
7521: /* } /\* End of popforecast *\/ */
7522:
7523: int fileappend(FILE *fichier, char *optionfich)
7524: {
7525: if((fichier=fopen(optionfich,"a"))==NULL) {
7526: printf("Problem with file: %s\n", optionfich);
7527: fprintf(ficlog,"Problem with file: %s\n", optionfich);
7528: return (0);
7529: }
7530: fflush(fichier);
7531: return (1);
7532: }
7533:
7534:
7535: /**************** function prwizard **********************/
7536: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
7537: {
7538:
7539: /* Wizard to print covariance matrix template */
7540:
7541: char ca[32], cb[32];
7542: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
7543: int numlinepar;
7544:
7545: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7546: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7547: for(i=1; i <=nlstate; i++){
7548: jj=0;
7549: for(j=1; j <=nlstate+ndeath; j++){
7550: if(j==i) continue;
7551: jj++;
7552: /*ca[0]= k+'a'-1;ca[1]='\0';*/
7553: printf("%1d%1d",i,j);
7554: fprintf(ficparo,"%1d%1d",i,j);
7555: for(k=1; k<=ncovmodel;k++){
7556: /* printf(" %lf",param[i][j][k]); */
7557: /* fprintf(ficparo," %lf",param[i][j][k]); */
7558: printf(" 0.");
7559: fprintf(ficparo," 0.");
7560: }
7561: printf("\n");
7562: fprintf(ficparo,"\n");
7563: }
7564: }
7565: printf("# Scales (for hessian or gradient estimation)\n");
7566: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
7567: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
7568: for(i=1; i <=nlstate; i++){
7569: jj=0;
7570: for(j=1; j <=nlstate+ndeath; j++){
7571: if(j==i) continue;
7572: jj++;
7573: fprintf(ficparo,"%1d%1d",i,j);
7574: printf("%1d%1d",i,j);
7575: fflush(stdout);
7576: for(k=1; k<=ncovmodel;k++){
7577: /* printf(" %le",delti3[i][j][k]); */
7578: /* fprintf(ficparo," %le",delti3[i][j][k]); */
7579: printf(" 0.");
7580: fprintf(ficparo," 0.");
7581: }
7582: numlinepar++;
7583: printf("\n");
7584: fprintf(ficparo,"\n");
7585: }
7586: }
7587: printf("# Covariance matrix\n");
7588: /* # 121 Var(a12)\n\ */
7589: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7590: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7591: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7592: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7593: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7594: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7595: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7596: fflush(stdout);
7597: fprintf(ficparo,"# Covariance matrix\n");
7598: /* # 121 Var(a12)\n\ */
7599: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7600: /* # ...\n\ */
7601: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7602:
7603: for(itimes=1;itimes<=2;itimes++){
7604: jj=0;
7605: for(i=1; i <=nlstate; i++){
7606: for(j=1; j <=nlstate+ndeath; j++){
7607: if(j==i) continue;
7608: for(k=1; k<=ncovmodel;k++){
7609: jj++;
7610: ca[0]= k+'a'-1;ca[1]='\0';
7611: if(itimes==1){
7612: printf("#%1d%1d%d",i,j,k);
7613: fprintf(ficparo,"#%1d%1d%d",i,j,k);
7614: }else{
7615: printf("%1d%1d%d",i,j,k);
7616: fprintf(ficparo,"%1d%1d%d",i,j,k);
7617: /* printf(" %.5le",matcov[i][j]); */
7618: }
7619: ll=0;
7620: for(li=1;li <=nlstate; li++){
7621: for(lj=1;lj <=nlstate+ndeath; lj++){
7622: if(lj==li) continue;
7623: for(lk=1;lk<=ncovmodel;lk++){
7624: ll++;
7625: if(ll<=jj){
7626: cb[0]= lk +'a'-1;cb[1]='\0';
7627: if(ll<jj){
7628: if(itimes==1){
7629: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7630: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7631: }else{
7632: printf(" 0.");
7633: fprintf(ficparo," 0.");
7634: }
7635: }else{
7636: if(itimes==1){
7637: printf(" Var(%s%1d%1d)",ca,i,j);
7638: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
7639: }else{
7640: printf(" 0.");
7641: fprintf(ficparo," 0.");
7642: }
7643: }
7644: }
7645: } /* end lk */
7646: } /* end lj */
7647: } /* end li */
7648: printf("\n");
7649: fprintf(ficparo,"\n");
7650: numlinepar++;
7651: } /* end k*/
7652: } /*end j */
7653: } /* end i */
7654: } /* end itimes */
7655:
7656: } /* end of prwizard */
7657: /******************* Gompertz Likelihood ******************************/
7658: double gompertz(double x[])
7659: {
7660: double A,B,L=0.0,sump=0.,num=0.;
7661: int i,n=0; /* n is the size of the sample */
7662:
7663: for (i=1;i<=imx ; i++) {
7664: sump=sump+weight[i];
7665: /* sump=sump+1;*/
7666: num=num+1;
7667: }
7668:
7669:
7670: /* for (i=0; i<=imx; i++)
7671: 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]);*/
7672:
7673: for (i=1;i<=imx ; i++)
7674: {
7675: if (cens[i] == 1 && wav[i]>1)
7676: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
7677:
7678: if (cens[i] == 0 && wav[i]>1)
7679: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
7680: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
7681:
7682: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
7683: if (wav[i] > 1 ) { /* ??? */
7684: L=L+A*weight[i];
7685: /* 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]);*/
7686: }
7687: }
7688:
7689: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
7690:
7691: return -2*L*num/sump;
7692: }
7693:
7694: #ifdef GSL
7695: /******************* Gompertz_f Likelihood ******************************/
7696: double gompertz_f(const gsl_vector *v, void *params)
7697: {
7698: double A,B,LL=0.0,sump=0.,num=0.;
7699: double *x= (double *) v->data;
7700: int i,n=0; /* n is the size of the sample */
7701:
7702: for (i=0;i<=imx-1 ; i++) {
7703: sump=sump+weight[i];
7704: /* sump=sump+1;*/
7705: num=num+1;
7706: }
7707:
7708:
7709: /* for (i=0; i<=imx; i++)
7710: 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]);*/
7711: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
7712: for (i=1;i<=imx ; i++)
7713: {
7714: if (cens[i] == 1 && wav[i]>1)
7715: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
7716:
7717: if (cens[i] == 0 && wav[i]>1)
7718: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
7719: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
7720:
7721: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
7722: if (wav[i] > 1 ) { /* ??? */
7723: LL=LL+A*weight[i];
7724: /* 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]);*/
7725: }
7726: }
7727:
7728: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
7729: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
7730:
7731: return -2*LL*num/sump;
7732: }
7733: #endif
7734:
7735: /******************* Printing html file ***********/
7736: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
7737: int lastpass, int stepm, int weightopt, char model[],\
7738: int imx, double p[],double **matcov,double agemortsup){
7739: int i,k;
7740:
7741: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
7742: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
7743: for (i=1;i<=2;i++)
7744: 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]));
7745: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
7746: fprintf(fichtm,"</ul>");
7747:
7748: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
7749:
7750: 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>");
7751:
7752: for (k=agegomp;k<(agemortsup-2);k++)
7753: 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]);
7754:
7755:
7756: fflush(fichtm);
7757: }
7758:
7759: /******************* Gnuplot file **************/
7760: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
7761:
7762: char dirfileres[132],optfileres[132];
7763:
7764: int ng;
7765:
7766:
7767: /*#ifdef windows */
7768: fprintf(ficgp,"cd \"%s\" \n",pathc);
7769: /*#endif */
7770:
7771:
7772: strcpy(dirfileres,optionfilefiname);
7773: strcpy(optfileres,"vpl");
7774: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
7775: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
7776: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
7777: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
7778: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
7779:
7780: }
7781:
7782: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
7783: {
7784:
7785: /*-------- data file ----------*/
7786: FILE *fic;
7787: char dummy[]=" ";
7788: int i=0, j=0, n=0, iv=0;
7789: int lstra;
7790: int linei, month, year,iout;
7791: char line[MAXLINE], linetmp[MAXLINE];
7792: char stra[MAXLINE], strb[MAXLINE];
7793: char *stratrunc;
7794:
7795:
7796:
7797: if((fic=fopen(datafile,"r"))==NULL) {
7798: printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
7799: fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
7800: }
7801:
7802: i=1;
7803: linei=0;
7804: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
7805: linei=linei+1;
7806: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
7807: if(line[j] == '\t')
7808: line[j] = ' ';
7809: }
7810: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
7811: ;
7812: };
7813: line[j+1]=0; /* Trims blanks at end of line */
7814: if(line[0]=='#'){
7815: fprintf(ficlog,"Comment line\n%s\n",line);
7816: printf("Comment line\n%s\n",line);
7817: continue;
7818: }
7819: trimbb(linetmp,line); /* Trims multiple blanks in line */
7820: strcpy(line, linetmp);
7821:
7822: /* Loops on waves */
7823: for (j=maxwav;j>=1;j--){
7824: for (iv=nqtv;iv>=1;iv--){ /* Loop on time varying quantitative variables */
7825: cutv(stra, strb, line, ' ');
7826: if(strb[0]=='.') { /* Missing value */
7827: lval=-1;
7828: cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
7829: cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
7830: if(isalpha(strb[1])) { /* .m or .d Really Missing value */
7831: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value. Exiting.\n", strb, linei,i,line,iv, nqtv, j);
7832: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value. Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
7833: return 1;
7834: }
7835: }else{
7836: errno=0;
7837: /* what_kind_of_number(strb); */
7838: dval=strtod(strb,&endptr);
7839: /* if( strb[0]=='\0' || (*endptr != '\0')){ */
7840: /* if(strb != endptr && *endptr == '\0') */
7841: /* dval=dlval; */
7842: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
7843: if( strb[0]=='\0' || (*endptr != '\0')){
7844: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
7845: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
7846: return 1;
7847: }
7848: cotqvar[j][iv][i]=dval;
7849: cotvar[j][ntv+iv][i]=dval;
7850: }
7851: strcpy(line,stra);
7852: }/* end loop ntqv */
7853:
7854: for (iv=ntv;iv>=1;iv--){ /* Loop on time varying dummies */
7855: cutv(stra, strb, line, ' ');
7856: if(strb[0]=='.') { /* Missing value */
7857: lval=-1;
7858: }else{
7859: errno=0;
7860: lval=strtol(strb,&endptr,10);
7861: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
7862: if( strb[0]=='\0' || (*endptr != '\0')){
7863: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
7864: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
7865: return 1;
7866: }
7867: }
7868: if(lval <-1 || lval >1){
7869: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
7870: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
7871: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
7872: For example, for multinomial values like 1, 2 and 3,\n \
7873: build V1=0 V2=0 for the reference value (1),\n \
7874: V1=1 V2=0 for (2) \n \
7875: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
7876: output of IMaCh is often meaningless.\n \
7877: Exiting.\n",lval,linei, i,line,j);
7878: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
7879: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
7880: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
7881: For example, for multinomial values like 1, 2 and 3,\n \
7882: build V1=0 V2=0 for the reference value (1),\n \
7883: V1=1 V2=0 for (2) \n \
7884: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
7885: output of IMaCh is often meaningless.\n \
7886: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
7887: return 1;
7888: }
7889: cotvar[j][iv][i]=(double)(lval);
7890: strcpy(line,stra);
7891: }/* end loop ntv */
7892:
7893: /* Statuses at wave */
7894: cutv(stra, strb, line, ' ');
7895: if(strb[0]=='.') { /* Missing value */
7896: lval=-1;
7897: }else{
7898: errno=0;
7899: lval=strtol(strb,&endptr,10);
7900: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
7901: if( strb[0]=='\0' || (*endptr != '\0')){
7902: 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);
7903: 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);
7904: return 1;
7905: }
7906: }
7907:
7908: s[j][i]=lval;
7909:
7910: /* Date of Interview */
7911: strcpy(line,stra);
7912: cutv(stra, strb,line,' ');
7913: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7914: }
7915: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
7916: month=99;
7917: year=9999;
7918: }else{
7919: 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);
7920: 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);
7921: return 1;
7922: }
7923: anint[j][i]= (double) year;
7924: mint[j][i]= (double)month;
7925: strcpy(line,stra);
7926: } /* End loop on waves */
7927:
7928: /* Date of death */
7929: cutv(stra, strb,line,' ');
7930: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7931: }
7932: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
7933: month=99;
7934: year=9999;
7935: }else{
7936: 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);
7937: 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);
7938: return 1;
7939: }
7940: andc[i]=(double) year;
7941: moisdc[i]=(double) month;
7942: strcpy(line,stra);
7943:
7944: /* Date of birth */
7945: cutv(stra, strb,line,' ');
7946: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7947: }
7948: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
7949: month=99;
7950: year=9999;
7951: }else{
7952: 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);
7953: 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);
7954: return 1;
7955: }
7956: if (year==9999) {
7957: 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);
7958: 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);
7959: return 1;
7960:
7961: }
7962: annais[i]=(double)(year);
7963: moisnais[i]=(double)(month);
7964: strcpy(line,stra);
7965:
7966: /* Sample weight */
7967: cutv(stra, strb,line,' ');
7968: errno=0;
7969: dval=strtod(strb,&endptr);
7970: if( strb[0]=='\0' || (*endptr != '\0')){
7971: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
7972: 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);
7973: fflush(ficlog);
7974: return 1;
7975: }
7976: weight[i]=dval;
7977: strcpy(line,stra);
7978:
7979: for (iv=nqv;iv>=1;iv--){ /* Loop on fixed quantitative variables */
7980: cutv(stra, strb, line, ' ');
7981: if(strb[0]=='.') { /* Missing value */
7982: lval=-1;
7983: }else{
7984: errno=0;
7985: /* what_kind_of_number(strb); */
7986: dval=strtod(strb,&endptr);
7987: /* if(strb != endptr && *endptr == '\0') */
7988: /* dval=dlval; */
7989: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
7990: if( strb[0]=='\0' || (*endptr != '\0')){
7991: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
7992: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong. Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
7993: return 1;
7994: }
7995: coqvar[iv][i]=dval;
7996: covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */
7997: }
7998: strcpy(line,stra);
7999: }/* end loop nqv */
8000:
8001: /* Covariate values */
8002: for (j=ncovcol;j>=1;j--){
8003: cutv(stra, strb,line,' ');
8004: if(strb[0]=='.') { /* Missing covariate value */
8005: lval=-1;
8006: }else{
8007: errno=0;
8008: lval=strtol(strb,&endptr,10);
8009: if( strb[0]=='\0' || (*endptr != '\0')){
8010: 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);
8011: 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);
8012: return 1;
8013: }
8014: }
8015: if(lval <-1 || lval >1){
8016: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
8017: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
8018: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
8019: For example, for multinomial values like 1, 2 and 3,\n \
8020: build V1=0 V2=0 for the reference value (1),\n \
8021: V1=1 V2=0 for (2) \n \
8022: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
8023: output of IMaCh is often meaningless.\n \
8024: Exiting.\n",lval,linei, i,line,j);
8025: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
8026: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
8027: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
8028: For example, for multinomial values like 1, 2 and 3,\n \
8029: build V1=0 V2=0 for the reference value (1),\n \
8030: V1=1 V2=0 for (2) \n \
8031: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
8032: output of IMaCh is often meaningless.\n \
8033: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
8034: return 1;
8035: }
8036: covar[j][i]=(double)(lval);
8037: strcpy(line,stra);
8038: }
8039: lstra=strlen(stra);
8040:
8041: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
8042: stratrunc = &(stra[lstra-9]);
8043: num[i]=atol(stratrunc);
8044: }
8045: else
8046: num[i]=atol(stra);
8047: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
8048: 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;}*/
8049:
8050: i=i+1;
8051: } /* End loop reading data */
8052:
8053: *imax=i-1; /* Number of individuals */
8054: fclose(fic);
8055:
8056: return (0);
8057: /* endread: */
8058: printf("Exiting readdata: ");
8059: fclose(fic);
8060: return (1);
8061: }
8062:
8063: void removefirstspace(char **stri){/*, char stro[]) {*/
8064: char *p1 = *stri, *p2 = *stri;
8065: while (*p2 == ' ')
8066: p2++;
8067: /* while ((*p1++ = *p2++) !=0) */
8068: /* ; */
8069: /* do */
8070: /* while (*p2 == ' ') */
8071: /* p2++; */
8072: /* while (*p1++ == *p2++); */
8073: *stri=p2;
8074: }
8075:
8076: int decoderesult ( char resultline[], int nres)
8077: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
8078: {
8079: int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
8080: char resultsav[MAXLINE];
8081: int resultmodel[MAXLINE];
8082: int modelresult[MAXLINE];
8083: char stra[80], strb[80], strc[80], strd[80],stre[80];
8084:
8085: removefirstspace(&resultline);
8086: printf("decoderesult:%s\n",resultline);
8087:
8088: if (strstr(resultline,"v") !=0){
8089: printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
8090: fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
8091: return 1;
8092: }
8093: trimbb(resultsav, resultline);
8094: if (strlen(resultsav) >1){
8095: j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
8096: }
8097: if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
8098: printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
8099: fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
8100: }
8101: for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
8102: if(nbocc(resultsav,'=') >1){
8103: cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' '
8104: resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
8105: cutl(strc,strd,strb,'='); /* strb:V4=1 strc=1 strd=V4 */
8106: }else
8107: cutl(strc,strd,resultsav,'=');
8108: Tvalsel[k]=atof(strc); /* 1 */
8109:
8110: cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
8111: Tvarsel[k]=atoi(strc);
8112: /* Typevarsel[k]=1; /\* 1 for age product *\/ */
8113: /* cptcovsel++; */
8114: if (nbocc(stra,'=') >0)
8115: strcpy(resultsav,stra); /* and analyzes it */
8116: }
8117: /* Checking for missing or useless values in comparison of current model needs */
8118: for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8119: if(Typevar[k1]==0){ /* Single covariate in model */
8120: match=0;
8121: for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1 V2=8 V1=0 */
8122: if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5 */
8123: modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2 modelresult[3]=3 modelresult[6]=4 modelresult[9]=5 */
8124: match=1;
8125: break;
8126: }
8127: }
8128: if(match == 0){
8129: printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
8130: }
8131: }
8132: }
8133: /* Checking for missing or useless values in comparison of current model needs */
8134: for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1 V2=8 V1=0 */
8135: match=0;
8136: for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8137: if(Typevar[k1]==0){ /* Single */
8138: if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4 */
8139: resultmodel[k1]=k2; /* resultmodel[2]=1 resultmodel[1]=2 resultmodel[3]=3 resultmodel[6]=4 resultmodel[9]=5 */
8140: ++match;
8141: }
8142: }
8143: }
8144: if(match == 0){
8145: printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
8146: }else if(match > 1){
8147: printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
8148: }
8149: }
8150:
8151: /* We need to deduce which combination number is chosen and save quantitative values */
8152: /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8153: /* result line V4=1 V5=25.1 V3=0 V2=8 V1=1 */
8154: /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
8155: /* result line V4=1 V5=24.1 V3=1 V2=8 V1=0 */
8156: /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
8157: /* 1 0 0 0 */
8158: /* 2 1 0 0 */
8159: /* 3 0 1 0 */
8160: /* 4 1 1 0 */ /* V4=1, V3=1, V1=0 */
8161: /* 5 0 0 1 */
8162: /* 6 1 0 1 */ /* V4=1, V3=0, V1=1 */
8163: /* 7 0 1 1 */
8164: /* 8 1 1 1 */
8165: /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
8166: /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
8167: /* V5*age V5 known which value for nres? */
8168: /* Tqinvresult[2]=8 Tqinvresult[1]=25.1 */
8169: for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
8170: if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
8171: k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
8172: k2=(int)Tvarsel[k3]; /* Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
8173: k+=Tvalsel[k3]*pow(2,k4); /* Tvalsel[1]=1 */
8174: Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1) Tresult[nres][2]=0(V3=0) */
8175: Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
8176: Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
8177: printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
8178: k4++;;
8179: } else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
8180: k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
8181: k2q=(int)Tvarsel[k3q]; /* Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
8182: Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
8183: Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
8184: Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
8185: printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
8186: k4q++;;
8187: }
8188: }
8189:
8190: TKresult[nres]=++k; /* Combination for the nresult and the model */
8191: return (0);
8192: }
8193:
8194: int decodemodel( char model[], int lastobs)
8195: /**< This routine decodes the model and returns:
8196: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
8197: * - nagesqr = 1 if age*age in the model, otherwise 0.
8198: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
8199: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
8200: * - cptcovage number of covariates with age*products =2
8201: * - cptcovs number of simple covariates
8202: * - 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
8203: * which is a new column after the 9 (ncovcol) variables.
8204: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
8205: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
8206: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
8207: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
8208: */
8209: {
8210: int i, j, k, ks;
8211: int j1, k1, k2, k3, k4;
8212: char modelsav[80];
8213: char stra[80], strb[80], strc[80], strd[80],stre[80];
8214: char *strpt;
8215:
8216: /*removespace(model);*/
8217: if (strlen(model) >1){ /* If there is at least 1 covariate */
8218: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
8219: if (strstr(model,"AGE") !=0){
8220: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
8221: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
8222: return 1;
8223: }
8224: if (strstr(model,"v") !=0){
8225: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
8226: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
8227: return 1;
8228: }
8229: strcpy(modelsav,model);
8230: if ((strpt=strstr(model,"age*age")) !=0){
8231: printf(" strpt=%s, model=%s\n",strpt, model);
8232: if(strpt != model){
8233: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
8234: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
8235: corresponding column of parameters.\n",model);
8236: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
8237: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
8238: corresponding column of parameters.\n",model); fflush(ficlog);
8239: return 1;
8240: }
8241: nagesqr=1;
8242: if (strstr(model,"+age*age") !=0)
8243: substrchaine(modelsav, model, "+age*age");
8244: else if (strstr(model,"age*age+") !=0)
8245: substrchaine(modelsav, model, "age*age+");
8246: else
8247: substrchaine(modelsav, model, "age*age");
8248: }else
8249: nagesqr=0;
8250: if (strlen(modelsav) >1){
8251: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
8252: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
8253: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2 */
8254: cptcovt= j+1; /* Number of total covariates in the model, not including
8255: * cst, age and age*age
8256: * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
8257: /* including age products which are counted in cptcovage.
8258: * but the covariates which are products must be treated
8259: * separately: ncovn=4- 2=2 (V1+V3). */
8260: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
8261: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
8262:
8263:
8264: /* Design
8265: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
8266: * < ncovcol=8 >
8267: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
8268: * k= 1 2 3 4 5 6 7 8
8269: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
8270: * covar[k,i], value of kth covariate if not including age for individual i:
8271: * covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
8272: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
8273: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
8274: * Tage[++cptcovage]=k
8275: * if products, new covar are created after ncovcol with k1
8276: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
8277: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
8278: * 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
8279: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
8280: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
8281: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
8282: * < ncovcol=8 >
8283: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
8284: * k= 1 2 3 4 5 6 7 8 9 10 11 12
8285: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
8286: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
8287: * p Tprod[1]@2={ 6, 5}
8288: *p Tvard[1][1]@4= {7, 8, 5, 6}
8289: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
8290: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
8291: *How to reorganize?
8292: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
8293: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
8294: * {2, 1, 4, 8, 5, 6, 3, 7}
8295: * Struct []
8296: */
8297:
8298: /* This loop fills the array Tvar from the string 'model'.*/
8299: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
8300: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
8301: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
8302: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
8303: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
8304: /* k=1 Tvar[1]=2 (from V2) */
8305: /* k=5 Tvar[5] */
8306: /* for (k=1; k<=cptcovn;k++) { */
8307: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
8308: /* } */
8309: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
8310: /*
8311: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
8312: for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
8313: Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
8314: }
8315: cptcovage=0;
8316: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
8317: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
8318: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
8319: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
8320: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
8321: /*scanf("%d",i);*/
8322: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
8323: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
8324: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
8325: /* covar is not filled and then is empty */
8326: cptcovprod--;
8327: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
8328: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
8329: Typevar[k]=1; /* 1 for age product */
8330: cptcovage++; /* Sums the number of covariates which include age as a product */
8331: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
8332: /*printf("stre=%s ", stre);*/
8333: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
8334: cptcovprod--;
8335: cutl(stre,strb,strc,'V');
8336: Tvar[k]=atoi(stre);
8337: Typevar[k]=1; /* 1 for age product */
8338: cptcovage++;
8339: Tage[cptcovage]=k;
8340: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
8341: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
8342: cptcovn++;
8343: cptcovprodnoage++;k1++;
8344: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
8345: Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
8346: because this model-covariate is a construction we invent a new column
8347: which is after existing variables ncovcol+nqv+ntv+nqtv + k1
8348: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
8349: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
8350: Typevar[k]=2; /* 2 for double fixed dummy covariates */
8351: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
8352: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
8353: Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
8354: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
8355: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
8356: k2=k2+2; /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
8357: /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
8358: /* Tvar[cptcovt+k2+1]=Tvard[k1][2]; /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
8359: /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
8360: /* 1 2 3 4 5 | Tvar[5+1)=1, Tvar[7]=2 */
8361: for (i=1; i<=lastobs;i++){
8362: /* Computes the new covariate which is a product of
8363: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
8364: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
8365: }
8366: } /* End age is not in the model */
8367: } /* End if model includes a product */
8368: else { /* no more sum */
8369: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
8370: /* scanf("%d",i);*/
8371: cutl(strd,strc,strb,'V');
8372: ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
8373: cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
8374: Tvar[k]=atoi(strd);
8375: Typevar[k]=0; /* 0 for simple covariates */
8376: }
8377: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
8378: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
8379: scanf("%d",i);*/
8380: } /* end of loop + on total covariates */
8381: } /* end if strlen(modelsave == 0) age*age might exist */
8382: } /* end if strlen(model == 0) */
8383:
8384: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
8385: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
8386:
8387: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
8388: printf("cptcovprod=%d ", cptcovprod);
8389: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
8390: scanf("%d ",i);*/
8391:
8392:
8393: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
8394: of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
8395: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1 = 5 possible variables data: 2 fixed 3, varying
8396: model= V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
8397: k = 1 2 3 4 5 6 7 8 9
8398: Tvar[k]= 5 4 3 1+1+2+1+1=6 5 2 7 1 5
8399: Typevar[k]= 0 0 0 2 1 0 2 1 1
8400: Fixed[k] 1 1 1 1 3 0 0 or 2 2 3
8401: Dummy[k] 1 0 0 0 3 1 1 2 3
8402: Tmodelind[combination of covar]=k;
8403: */
8404: /* Dispatching between quantitative and time varying covariates */
8405: /* If Tvar[k] >ncovcol it is a product */
8406: /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p Vp=Vn*Vm for product */
8407: /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
8408: printf("Model=%s\n\
8409: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product \n\
8410: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
8411: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
8412: fprintf(ficlog,"Model=%s\n\
8413: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product \n\
8414: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
8415: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
8416:
8417: for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
8418: if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
8419: Fixed[k]= 0;
8420: Dummy[k]= 0;
8421: ncoveff++;
8422: ncovf++;
8423: nsd++;
8424: modell[k].maintype= FTYPE;
8425: TvarsD[nsd]=Tvar[k];
8426: TvarsDind[nsd]=k;
8427: TvarF[ncovf]=Tvar[k];
8428: TvarFind[ncovf]=k;
8429: TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8430: TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8431: }else if( Tvar[k] <=ncovcol && Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
8432: Fixed[k]= 0;
8433: Dummy[k]= 0;
8434: ncoveff++;
8435: ncovf++;
8436: modell[k].maintype= FTYPE;
8437: TvarF[ncovf]=Tvar[k];
8438: TvarFind[ncovf]=k;
8439: TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8440: TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
8441: }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){ /* Remind that product Vn*Vm are added in k*/ /* Only simple fixed quantitative variable */
8442: Fixed[k]= 0;
8443: Dummy[k]= 1;
8444: nqfveff++;
8445: modell[k].maintype= FTYPE;
8446: modell[k].subtype= FQ;
8447: nsq++;
8448: TvarsQ[nsq]=Tvar[k];
8449: TvarsQind[nsq]=k;
8450: ncovf++;
8451: TvarF[ncovf]=Tvar[k];
8452: TvarFind[ncovf]=k;
8453: TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
8454: TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
8455: }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying variables */
8456: Fixed[k]= 1;
8457: Dummy[k]= 0;
8458: ntveff++; /* Only simple time varying dummy variable */
8459: modell[k].maintype= VTYPE;
8460: modell[k].subtype= VD;
8461: nsd++;
8462: TvarsD[nsd]=Tvar[k];
8463: TvarsDind[nsd]=k;
8464: ncovv++; /* Only simple time varying variables */
8465: TvarV[ncovv]=Tvar[k];
8466: TvarVind[ncovv]=k;
8467: TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4 TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
8468: TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
8469: printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
8470: printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
8471: }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
8472: Fixed[k]= 1;
8473: Dummy[k]= 1;
8474: nqtveff++;
8475: modell[k].maintype= VTYPE;
8476: modell[k].subtype= VQ;
8477: ncovv++; /* Only simple time varying variables */
8478: nsq++;
8479: TvarsQ[nsq]=Tvar[k];
8480: TvarsQind[nsq]=k;
8481: TvarV[ncovv]=Tvar[k];
8482: TvarVind[ncovv]=k;
8483: TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
8484: TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
8485: TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
8486: /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
8487: printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
8488: printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
8489: }else if (Typevar[k] == 1) { /* product with age */
8490: ncova++;
8491: TvarA[ncova]=Tvar[k];
8492: TvarAind[ncova]=k;
8493: if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
8494: Fixed[k]= 2;
8495: Dummy[k]= 2;
8496: modell[k].maintype= ATYPE;
8497: modell[k].subtype= APFD;
8498: /* ncoveff++; */
8499: }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
8500: Fixed[k]= 2;
8501: Dummy[k]= 3;
8502: modell[k].maintype= ATYPE;
8503: modell[k].subtype= APFQ; /* Product age * fixed quantitative */
8504: /* nqfveff++; /\* Only simple fixed quantitative variable *\/ */
8505: }else if( Tvar[k] <=ncovcol+nqv+ntv ){
8506: Fixed[k]= 3;
8507: Dummy[k]= 2;
8508: modell[k].maintype= ATYPE;
8509: modell[k].subtype= APVD; /* Product age * varying dummy */
8510: /* ntveff++; /\* Only simple time varying dummy variable *\/ */
8511: }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
8512: Fixed[k]= 3;
8513: Dummy[k]= 3;
8514: modell[k].maintype= ATYPE;
8515: modell[k].subtype= APVQ; /* Product age * varying quantitative */
8516: /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
8517: }
8518: }else if (Typevar[k] == 2) { /* product without age */
8519: k1=Tposprod[k];
8520: if(Tvard[k1][1] <=ncovcol){
8521: if(Tvard[k1][2] <=ncovcol){
8522: Fixed[k]= 1;
8523: Dummy[k]= 0;
8524: modell[k].maintype= FTYPE;
8525: modell[k].subtype= FPDD; /* Product fixed dummy * fixed dummy */
8526: ncovf++; /* Fixed variables without age */
8527: TvarF[ncovf]=Tvar[k];
8528: TvarFind[ncovf]=k;
8529: }else if(Tvard[k1][2] <=ncovcol+nqv){
8530: Fixed[k]= 0; /* or 2 ?*/
8531: Dummy[k]= 1;
8532: modell[k].maintype= FTYPE;
8533: modell[k].subtype= FPDQ; /* Product fixed dummy * fixed quantitative */
8534: ncovf++; /* Varying variables without age */
8535: TvarF[ncovf]=Tvar[k];
8536: TvarFind[ncovf]=k;
8537: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
8538: Fixed[k]= 1;
8539: Dummy[k]= 0;
8540: modell[k].maintype= VTYPE;
8541: modell[k].subtype= VPDD; /* Product fixed dummy * varying dummy */
8542: ncovv++; /* Varying variables without age */
8543: TvarV[ncovv]=Tvar[k];
8544: TvarVind[ncovv]=k;
8545: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
8546: Fixed[k]= 1;
8547: Dummy[k]= 1;
8548: modell[k].maintype= VTYPE;
8549: modell[k].subtype= VPDQ; /* Product fixed dummy * varying quantitative */
8550: ncovv++; /* Varying variables without age */
8551: TvarV[ncovv]=Tvar[k];
8552: TvarVind[ncovv]=k;
8553: }
8554: }else if(Tvard[k1][1] <=ncovcol+nqv){
8555: if(Tvard[k1][2] <=ncovcol){
8556: Fixed[k]= 0; /* or 2 ?*/
8557: Dummy[k]= 1;
8558: modell[k].maintype= FTYPE;
8559: modell[k].subtype= FPDQ; /* Product fixed quantitative * fixed dummy */
8560: ncovf++; /* Fixed variables without age */
8561: TvarF[ncovf]=Tvar[k];
8562: TvarFind[ncovf]=k;
8563: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
8564: Fixed[k]= 1;
8565: Dummy[k]= 1;
8566: modell[k].maintype= VTYPE;
8567: modell[k].subtype= VPDQ; /* Product fixed quantitative * varying dummy */
8568: ncovv++; /* Varying variables without age */
8569: TvarV[ncovv]=Tvar[k];
8570: TvarVind[ncovv]=k;
8571: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
8572: Fixed[k]= 1;
8573: Dummy[k]= 1;
8574: modell[k].maintype= VTYPE;
8575: modell[k].subtype= VPQQ; /* Product fixed quantitative * varying quantitative */
8576: ncovv++; /* Varying variables without age */
8577: TvarV[ncovv]=Tvar[k];
8578: TvarVind[ncovv]=k;
8579: ncovv++; /* Varying variables without age */
8580: TvarV[ncovv]=Tvar[k];
8581: TvarVind[ncovv]=k;
8582: }
8583: }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
8584: if(Tvard[k1][2] <=ncovcol){
8585: Fixed[k]= 1;
8586: Dummy[k]= 1;
8587: modell[k].maintype= VTYPE;
8588: modell[k].subtype= VPDD; /* Product time varying dummy * fixed dummy */
8589: ncovv++; /* Varying variables without age */
8590: TvarV[ncovv]=Tvar[k];
8591: TvarVind[ncovv]=k;
8592: }else if(Tvard[k1][2] <=ncovcol+nqv){
8593: Fixed[k]= 1;
8594: Dummy[k]= 1;
8595: modell[k].maintype= VTYPE;
8596: modell[k].subtype= VPDQ; /* Product time varying dummy * fixed quantitative */
8597: ncovv++; /* Varying variables without age */
8598: TvarV[ncovv]=Tvar[k];
8599: TvarVind[ncovv]=k;
8600: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
8601: Fixed[k]= 1;
8602: Dummy[k]= 0;
8603: modell[k].maintype= VTYPE;
8604: modell[k].subtype= VPDD; /* Product time varying dummy * time varying dummy */
8605: ncovv++; /* Varying variables without age */
8606: TvarV[ncovv]=Tvar[k];
8607: TvarVind[ncovv]=k;
8608: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
8609: Fixed[k]= 1;
8610: Dummy[k]= 1;
8611: modell[k].maintype= VTYPE;
8612: modell[k].subtype= VPDQ; /* Product time varying dummy * time varying quantitative */
8613: ncovv++; /* Varying variables without age */
8614: TvarV[ncovv]=Tvar[k];
8615: TvarVind[ncovv]=k;
8616: }
8617: }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
8618: if(Tvard[k1][2] <=ncovcol){
8619: Fixed[k]= 1;
8620: Dummy[k]= 1;
8621: modell[k].maintype= VTYPE;
8622: modell[k].subtype= VPDQ; /* Product time varying quantitative * fixed dummy */
8623: ncovv++; /* Varying variables without age */
8624: TvarV[ncovv]=Tvar[k];
8625: TvarVind[ncovv]=k;
8626: }else if(Tvard[k1][2] <=ncovcol+nqv){
8627: Fixed[k]= 1;
8628: Dummy[k]= 1;
8629: modell[k].maintype= VTYPE;
8630: modell[k].subtype= VPQQ; /* Product time varying quantitative * fixed quantitative */
8631: ncovv++; /* Varying variables without age */
8632: TvarV[ncovv]=Tvar[k];
8633: TvarVind[ncovv]=k;
8634: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
8635: Fixed[k]= 1;
8636: Dummy[k]= 1;
8637: modell[k].maintype= VTYPE;
8638: modell[k].subtype= VPDQ; /* Product time varying quantitative * time varying dummy */
8639: ncovv++; /* Varying variables without age */
8640: TvarV[ncovv]=Tvar[k];
8641: TvarVind[ncovv]=k;
8642: }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
8643: Fixed[k]= 1;
8644: Dummy[k]= 1;
8645: modell[k].maintype= VTYPE;
8646: modell[k].subtype= VPQQ; /* Product time varying quantitative * time varying quantitative */
8647: ncovv++; /* Varying variables without age */
8648: TvarV[ncovv]=Tvar[k];
8649: TvarVind[ncovv]=k;
8650: }
8651: }else{
8652: printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
8653: fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
8654: } /* end k1 */
8655: }else{
8656: printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
8657: fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
8658: }
8659: printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
8660: printf(" modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
8661: fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
8662: }
8663: /* Searching for doublons in the model */
8664: for(k1=1; k1<= cptcovt;k1++){
8665: for(k2=1; k2 <k1;k2++){
8666: if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
8667: if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
8668: if(Tvar[k1]==Tvar[k2]){
8669: printf("Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
8670: fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
8671: return(1);
8672: }
8673: }else if (Typevar[k1] ==2){
8674: k3=Tposprod[k1];
8675: k4=Tposprod[k2];
8676: if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
8677: printf("Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
8678: fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
8679: return(1);
8680: }
8681: }
8682: }
8683: }
8684: }
8685: printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
8686: fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
8687: printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
8688: fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
8689: return (0); /* with covar[new additional covariate if product] and Tage if age */
8690: /*endread:*/
8691: printf("Exiting decodemodel: ");
8692: return (1);
8693: }
8694:
8695: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
8696: {
8697: int i, m;
8698: int firstone=0;
8699:
8700: for (i=1; i<=imx; i++) {
8701: for(m=2; (m<= maxwav); m++) {
8702: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
8703: anint[m][i]=9999;
8704: if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
8705: s[m][i]=-1;
8706: }
8707: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
8708: *nberr = *nberr + 1;
8709: if(firstone == 0){
8710: firstone=1;
8711: 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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
8712: }
8713: 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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
8714: s[m][i]=-1;
8715: }
8716: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
8717: (*nberr)++;
8718: 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]);
8719: 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]);
8720: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
8721: }
8722: }
8723: }
8724:
8725: for (i=1; i<=imx; i++) {
8726: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
8727: for(m=firstpass; (m<= lastpass); m++){
8728: 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 */
8729: if (s[m][i] >= nlstate+1) {
8730: if(agedc[i]>0){
8731: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
8732: agev[m][i]=agedc[i];
8733: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
8734: }else {
8735: if ((int)andc[i]!=9999){
8736: nbwarn++;
8737: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
8738: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
8739: agev[m][i]=-1;
8740: }
8741: }
8742: } /* agedc > 0 */
8743: } /* end if */
8744: else if(s[m][i] !=9){ /* Standard case, age in fractional
8745: years but with the precision of a month */
8746: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
8747: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
8748: agev[m][i]=1;
8749: else if(agev[m][i] < *agemin){
8750: *agemin=agev[m][i];
8751: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
8752: }
8753: else if(agev[m][i] >*agemax){
8754: *agemax=agev[m][i];
8755: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
8756: }
8757: /*agev[m][i]=anint[m][i]-annais[i];*/
8758: /* agev[m][i] = age[i]+2*m;*/
8759: } /* en if 9*/
8760: else { /* =9 */
8761: /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
8762: agev[m][i]=1;
8763: s[m][i]=-1;
8764: }
8765: }
8766: else if(s[m][i]==0) /*= 0 Unknown */
8767: agev[m][i]=1;
8768: else{
8769: printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
8770: fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
8771: agev[m][i]=0;
8772: }
8773: } /* End for lastpass */
8774: }
8775:
8776: for (i=1; i<=imx; i++) {
8777: for(m=firstpass; (m<=lastpass); m++){
8778: if (s[m][i] > (nlstate+ndeath)) {
8779: (*nberr)++;
8780: 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);
8781: 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);
8782: return 1;
8783: }
8784: }
8785: }
8786:
8787: /*for (i=1; i<=imx; i++){
8788: for (m=firstpass; (m<lastpass); m++){
8789: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
8790: }
8791:
8792: }*/
8793:
8794:
8795: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
8796: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
8797:
8798: return (0);
8799: /* endread:*/
8800: printf("Exiting calandcheckages: ");
8801: return (1);
8802: }
8803:
8804: #if defined(_MSC_VER)
8805: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
8806: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
8807: //#include "stdafx.h"
8808: //#include <stdio.h>
8809: //#include <tchar.h>
8810: //#include <windows.h>
8811: //#include <iostream>
8812: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
8813:
8814: LPFN_ISWOW64PROCESS fnIsWow64Process;
8815:
8816: BOOL IsWow64()
8817: {
8818: BOOL bIsWow64 = FALSE;
8819:
8820: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
8821: // (HANDLE, PBOOL);
8822:
8823: //LPFN_ISWOW64PROCESS fnIsWow64Process;
8824:
8825: HMODULE module = GetModuleHandle(_T("kernel32"));
8826: const char funcName[] = "IsWow64Process";
8827: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
8828: GetProcAddress(module, funcName);
8829:
8830: if (NULL != fnIsWow64Process)
8831: {
8832: if (!fnIsWow64Process(GetCurrentProcess(),
8833: &bIsWow64))
8834: //throw std::exception("Unknown error");
8835: printf("Unknown error\n");
8836: }
8837: return bIsWow64 != FALSE;
8838: }
8839: #endif
8840:
8841: void syscompilerinfo(int logged)
8842: {
8843: /* #include "syscompilerinfo.h"*/
8844: /* command line Intel compiler 32bit windows, XP compatible:*/
8845: /* /GS /W3 /Gy
8846: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
8847: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
8848: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
8849: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
8850: */
8851: /* 64 bits */
8852: /*
8853: /GS /W3 /Gy
8854: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
8855: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
8856: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
8857: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
8858: /* Optimization are useless and O3 is slower than O2 */
8859: /*
8860: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
8861: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
8862: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
8863: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
8864: */
8865: /* Link is */ /* /OUT:"visual studio
8866: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
8867: /PDB:"visual studio
8868: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
8869: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
8870: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
8871: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
8872: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
8873: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
8874: uiAccess='false'"
8875: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
8876: /NOLOGO /TLBID:1
8877: */
8878: #if defined __INTEL_COMPILER
8879: #if defined(__GNUC__)
8880: struct utsname sysInfo; /* For Intel on Linux and OS/X */
8881: #endif
8882: #elif defined(__GNUC__)
8883: #ifndef __APPLE__
8884: #include <gnu/libc-version.h> /* Only on gnu */
8885: #endif
8886: struct utsname sysInfo;
8887: int cross = CROSS;
8888: if (cross){
8889: printf("Cross-");
8890: if(logged) fprintf(ficlog, "Cross-");
8891: }
8892: #endif
8893:
8894: #include <stdint.h>
8895:
8896: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
8897: #if defined(__clang__)
8898: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
8899: #endif
8900: #if defined(__ICC) || defined(__INTEL_COMPILER)
8901: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
8902: #endif
8903: #if defined(__GNUC__) || defined(__GNUG__)
8904: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
8905: #endif
8906: #if defined(__HP_cc) || defined(__HP_aCC)
8907: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
8908: #endif
8909: #if defined(__IBMC__) || defined(__IBMCPP__)
8910: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
8911: #endif
8912: #if defined(_MSC_VER)
8913: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
8914: #endif
8915: #if defined(__PGI)
8916: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
8917: #endif
8918: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
8919: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
8920: #endif
8921: printf(" for "); if (logged) fprintf(ficlog, " for ");
8922:
8923: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
8924: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
8925: // Windows (x64 and x86)
8926: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
8927: #elif __unix__ // all unices, not all compilers
8928: // Unix
8929: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
8930: #elif __linux__
8931: // linux
8932: printf("linux ");if(logged) fprintf(ficlog,"linux ");
8933: #elif __APPLE__
8934: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
8935: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
8936: #endif
8937:
8938: /* __MINGW32__ */
8939: /* __CYGWIN__ */
8940: /* __MINGW64__ */
8941: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
8942: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
8943: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
8944: /* _WIN64 // Defined for applications for Win64. */
8945: /* _M_X64 // Defined for compilations that target x64 processors. */
8946: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
8947:
8948: #if UINTPTR_MAX == 0xffffffff
8949: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
8950: #elif UINTPTR_MAX == 0xffffffffffffffff
8951: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
8952: #else
8953: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
8954: #endif
8955:
8956: #if defined(__GNUC__)
8957: # if defined(__GNUC_PATCHLEVEL__)
8958: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
8959: + __GNUC_MINOR__ * 100 \
8960: + __GNUC_PATCHLEVEL__)
8961: # else
8962: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
8963: + __GNUC_MINOR__ * 100)
8964: # endif
8965: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
8966: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
8967:
8968: if (uname(&sysInfo) != -1) {
8969: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
8970: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
8971: }
8972: else
8973: perror("uname() error");
8974: //#ifndef __INTEL_COMPILER
8975: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
8976: printf("GNU libc version: %s\n", gnu_get_libc_version());
8977: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
8978: #endif
8979: #endif
8980:
8981: // void main()
8982: // {
8983: #if defined(_MSC_VER)
8984: if (IsWow64()){
8985: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
8986: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
8987: }
8988: else{
8989: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
8990: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
8991: }
8992: // printf("\nPress Enter to continue...");
8993: // getchar();
8994: // }
8995:
8996: #endif
8997:
8998:
8999: }
9000:
9001: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
9002: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
9003: int i, j, k, i1, k4=0, nres=0 ;
9004: /* double ftolpl = 1.e-10; */
9005: double age, agebase, agelim;
9006: double tot;
9007:
9008: strcpy(filerespl,"PL_");
9009: strcat(filerespl,fileresu);
9010: if((ficrespl=fopen(filerespl,"w"))==NULL) {
9011: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
9012: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
9013: }
9014: printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
9015: fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
9016: pstamp(ficrespl);
9017: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
9018: fprintf(ficrespl,"#Age ");
9019: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
9020: fprintf(ficrespl,"\n");
9021:
9022: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
9023:
9024: agebase=ageminpar;
9025: agelim=agemaxpar;
9026:
9027: /* i1=pow(2,ncoveff); */
9028: i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
9029: if (cptcovn < 1){i1=1;}
9030:
9031: for(nres=1; nres <= nresult; nres++) /* For each resultline */
9032: for(k=1; k<=i1;k++){
9033: if(TKresult[nres]!= k)
9034: continue;
9035:
9036: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
9037: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
9038: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
9039: /* k=k+1; */
9040: /* to clean */
9041: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
9042: fprintf(ficrespl,"#******");
9043: printf("#******");
9044: fprintf(ficlog,"#******");
9045: for(j=1;j<=cptcoveff ;j++) {/* all covariates */
9046: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
9047: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9048: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9049: }
9050: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
9051: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
9052: fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
9053: }
9054: fprintf(ficrespl,"******\n");
9055: printf("******\n");
9056: fprintf(ficlog,"******\n");
9057: if(invalidvarcomb[k]){
9058: printf("\nCombination (%d) ignored because no case \n",k);
9059: fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k);
9060: fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k);
9061: continue;
9062: }
9063:
9064: fprintf(ficrespl,"#Age ");
9065: for(j=1;j<=cptcoveff;j++) {
9066: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9067: }
9068: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
9069: fprintf(ficrespl,"Total Years_to_converge\n");
9070:
9071: for (age=agebase; age<=agelim; age++){
9072: /* for (age=agebase; age<=agebase; age++){ */
9073: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
9074: fprintf(ficrespl,"%.0f ",age );
9075: for(j=1;j<=cptcoveff;j++)
9076: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9077: tot=0.;
9078: for(i=1; i<=nlstate;i++){
9079: tot += prlim[i][i];
9080: fprintf(ficrespl," %.5f", prlim[i][i]);
9081: }
9082: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
9083: } /* Age */
9084: /* was end of cptcod */
9085: } /* cptcov */
9086: return 0;
9087: }
9088:
9089: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
9090: /*--------------- Back Prevalence limit (period or stable prevalence) --------------*/
9091:
9092: /* Computes the back prevalence limit for any combination of covariate values
9093: * at any age between ageminpar and agemaxpar
9094: */
9095: int i, j, k, i1, nres=0 ;
9096: /* double ftolpl = 1.e-10; */
9097: double age, agebase, agelim;
9098: double tot;
9099: /* double ***mobaverage; */
9100: /* double **dnewm, **doldm, **dsavm; /\* for use *\/ */
9101:
9102: strcpy(fileresplb,"PLB_");
9103: strcat(fileresplb,fileresu);
9104: if((ficresplb=fopen(fileresplb,"w"))==NULL) {
9105: printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
9106: fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
9107: }
9108: printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
9109: fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
9110: pstamp(ficresplb);
9111: fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
9112: fprintf(ficresplb,"#Age ");
9113: for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
9114: fprintf(ficresplb,"\n");
9115:
9116:
9117: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
9118:
9119: agebase=ageminpar;
9120: agelim=agemaxpar;
9121:
9122:
9123: i1=pow(2,cptcoveff);
9124: if (cptcovn < 1){i1=1;}
9125:
9126: for(nres=1; nres <= nresult; nres++) /* For each resultline */
9127: for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
9128: if(TKresult[nres]!= k)
9129: continue;
9130: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
9131: fprintf(ficresplb,"#******");
9132: printf("#******");
9133: fprintf(ficlog,"#******");
9134: for(j=1;j<=cptcoveff ;j++) {/* all covariates */
9135: fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9136: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9137: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9138: }
9139: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
9140: printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
9141: fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
9142: fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
9143: }
9144: fprintf(ficresplb,"******\n");
9145: printf("******\n");
9146: fprintf(ficlog,"******\n");
9147: if(invalidvarcomb[k]){
9148: printf("\nCombination (%d) ignored because no cases \n",k);
9149: fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k);
9150: fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k);
9151: continue;
9152: }
9153:
9154: fprintf(ficresplb,"#Age ");
9155: for(j=1;j<=cptcoveff;j++) {
9156: fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9157: }
9158: for(i=1; i<=nlstate;i++) fprintf(ficresplb," %d-%d ",i,i);
9159: fprintf(ficresplb,"Total Years_to_converge\n");
9160:
9161:
9162: for (age=agebase; age<=agelim; age++){
9163: /* for (age=agebase; age<=agebase; age++){ */
9164: if(mobilavproj > 0){
9165: /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
9166: /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
9167: bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
9168: }else if (mobilavproj == 0){
9169: printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
9170: fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
9171: exit(1);
9172: }else{
9173: /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
9174: bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
9175: }
9176: fprintf(ficresplb,"%.0f ",age );
9177: for(j=1;j<=cptcoveff;j++)
9178: fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9179: tot=0.;
9180: for(i=1; i<=nlstate;i++){
9181: tot += bprlim[i][i];
9182: fprintf(ficresplb," %.5f", bprlim[i][i]);
9183: }
9184: fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
9185: } /* Age */
9186: /* was end of cptcod */
9187: } /* cptcov */
9188:
9189: /* hBijx(p, bage, fage); */
9190: /* fclose(ficrespijb); */
9191:
9192: return 0;
9193: }
9194:
9195: int hPijx(double *p, int bage, int fage){
9196: /*------------- h Pij x at various ages ------------*/
9197:
9198: int stepsize;
9199: int agelim;
9200: int hstepm;
9201: int nhstepm;
9202: int h, i, i1, j, k, k4, nres=0;
9203:
9204: double agedeb;
9205: double ***p3mat;
9206:
9207: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
9208: if((ficrespij=fopen(filerespij,"w"))==NULL) {
9209: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
9210: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
9211: }
9212: printf("Computing pij: result on file '%s' \n", filerespij);
9213: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
9214:
9215: stepsize=(int) (stepm+YEARM-1)/YEARM;
9216: /*if (stepm<=24) stepsize=2;*/
9217:
9218: agelim=AGESUP;
9219: hstepm=stepsize*YEARM; /* Every year of age */
9220: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
9221:
9222: /* hstepm=1; aff par mois*/
9223: pstamp(ficrespij);
9224: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
9225: i1= pow(2,cptcoveff);
9226: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
9227: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
9228: /* k=k+1; */
9229: for(nres=1; nres <= nresult; nres++) /* For each resultline */
9230: for(k=1; k<=i1;k++){
9231: if(TKresult[nres]!= k)
9232: continue;
9233: fprintf(ficrespij,"\n#****** ");
9234: for(j=1;j<=cptcoveff;j++)
9235: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9236: for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
9237: printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
9238: fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
9239: }
9240: fprintf(ficrespij,"******\n");
9241:
9242: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
9243: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
9244: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
9245:
9246: /* nhstepm=nhstepm*YEARM; aff par mois*/
9247:
9248: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
9249: oldm=oldms;savm=savms;
9250: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
9251: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
9252: for(i=1; i<=nlstate;i++)
9253: for(j=1; j<=nlstate+ndeath;j++)
9254: fprintf(ficrespij," %1d-%1d",i,j);
9255: fprintf(ficrespij,"\n");
9256: for (h=0; h<=nhstepm; h++){
9257: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
9258: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
9259: for(i=1; i<=nlstate;i++)
9260: for(j=1; j<=nlstate+ndeath;j++)
9261: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
9262: fprintf(ficrespij,"\n");
9263: }
9264: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
9265: fprintf(ficrespij,"\n");
9266: }
9267: /*}*/
9268: }
9269: return 0;
9270: }
9271:
9272: int hBijx(double *p, int bage, int fage, double ***prevacurrent){
9273: /*------------- h Bij x at various ages ------------*/
9274:
9275: int stepsize;
9276: /* int agelim; */
9277: int ageminl;
9278: int hstepm;
9279: int nhstepm;
9280: int h, i, i1, j, k;
9281:
9282: double agedeb;
9283: double ***p3mat;
9284:
9285: strcpy(filerespijb,"PIJB_"); strcat(filerespijb,fileresu);
9286: if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
9287: printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
9288: fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
9289: }
9290: printf("Computing pij back: result on file '%s' \n", filerespijb);
9291: fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
9292:
9293: stepsize=(int) (stepm+YEARM-1)/YEARM;
9294: /*if (stepm<=24) stepsize=2;*/
9295:
9296: /* agelim=AGESUP; */
9297: ageminl=30;
9298: hstepm=stepsize*YEARM; /* Every year of age */
9299: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
9300:
9301: /* hstepm=1; aff par mois*/
9302: pstamp(ficrespijb);
9303: fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
9304: i1= pow(2,cptcoveff);
9305: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
9306: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
9307: /* k=k+1; */
9308: for (k=1; k <= (int) pow(2,cptcoveff); k++){
9309: fprintf(ficrespijb,"\n#****** ");
9310: for(j=1;j<=cptcoveff;j++)
9311: fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9312: fprintf(ficrespijb,"******\n");
9313: if(invalidvarcomb[k]){
9314: fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k);
9315: continue;
9316: }
9317:
9318: /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
9319: for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
9320: /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
9321: nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
9322: nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
9323:
9324: /* nhstepm=nhstepm*YEARM; aff par mois*/
9325:
9326: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
9327: /* oldm=oldms;savm=savms; */
9328: /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); */
9329: hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
9330: /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
9331: fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
9332: for(i=1; i<=nlstate;i++)
9333: for(j=1; j<=nlstate+ndeath;j++)
9334: fprintf(ficrespijb," %1d-%1d",i,j);
9335: fprintf(ficrespijb,"\n");
9336: for (h=0; h<=nhstepm; h++){
9337: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
9338: fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
9339: /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
9340: for(i=1; i<=nlstate;i++)
9341: for(j=1; j<=nlstate+ndeath;j++)
9342: fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
9343: fprintf(ficrespijb,"\n");
9344: }
9345: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
9346: fprintf(ficrespijb,"\n");
9347: }
9348: /*}*/
9349: }
9350: return 0;
9351: } /* hBijx */
9352:
9353:
9354: /***********************************************/
9355: /**************** Main Program *****************/
9356: /***********************************************/
9357:
9358: int main(int argc, char *argv[])
9359: {
9360: #ifdef GSL
9361: const gsl_multimin_fminimizer_type *T;
9362: size_t iteri = 0, it;
9363: int rval = GSL_CONTINUE;
9364: int status = GSL_SUCCESS;
9365: double ssval;
9366: #endif
9367: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
9368: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
9369: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
9370: int jj, ll, li, lj, lk;
9371: int numlinepar=0; /* Current linenumber of parameter file */
9372: int num_filled;
9373: int itimes;
9374: int NDIM=2;
9375: int vpopbased=0;
9376: int nres=0;
9377:
9378: char ca[32], cb[32];
9379: /* FILE *fichtm; *//* Html File */
9380: /* FILE *ficgp;*/ /*Gnuplot File */
9381: struct stat info;
9382: double agedeb=0.;
9383:
9384: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
9385: double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
9386:
9387: double fret;
9388: double dum=0.; /* Dummy variable */
9389: double ***p3mat;
9390: /* double ***mobaverage; */
9391:
9392: char line[MAXLINE];
9393: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
9394:
9395: char modeltemp[MAXLINE];
9396: char resultline[MAXLINE];
9397:
9398: char pathr[MAXLINE], pathimach[MAXLINE];
9399: char *tok, *val; /* pathtot */
9400: int firstobs=1, lastobs=10;
9401: int c, h , cpt, c2;
9402: int jl=0;
9403: int i1, j1, jk, stepsize=0;
9404: int count=0;
9405:
9406: int *tab;
9407: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
9408: int backcast=0;
9409: int mobilav=0,popforecast=0;
9410: int hstepm=0, nhstepm=0;
9411: int agemortsup;
9412: float sumlpop=0.;
9413: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
9414: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
9415:
9416: double bage=0, fage=110., age, agelim=0., agebase=0.;
9417: double ftolpl=FTOL;
9418: double **prlim;
9419: double **bprlim;
9420: double ***param; /* Matrix of parameters */
9421: double *p;
9422: double **matcov; /* Matrix of covariance */
9423: double **hess; /* Hessian matrix */
9424: double ***delti3; /* Scale */
9425: double *delti; /* Scale */
9426: double ***eij, ***vareij;
9427: double **varpl; /* Variances of prevalence limits by age */
9428: double *epj, vepp;
9429:
9430: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
9431: double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
9432:
9433: double **ximort;
9434: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
9435: int *dcwave;
9436:
9437: char z[1]="c";
9438:
9439: /*char *strt;*/
9440: char strtend[80];
9441:
9442:
9443: /* setlocale (LC_ALL, ""); */
9444: /* bindtextdomain (PACKAGE, LOCALEDIR); */
9445: /* textdomain (PACKAGE); */
9446: /* setlocale (LC_CTYPE, ""); */
9447: /* setlocale (LC_MESSAGES, ""); */
9448:
9449: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
9450: rstart_time = time(NULL);
9451: /* (void) gettimeofday(&start_time,&tzp);*/
9452: start_time = *localtime(&rstart_time);
9453: curr_time=start_time;
9454: /*tml = *localtime(&start_time.tm_sec);*/
9455: /* strcpy(strstart,asctime(&tml)); */
9456: strcpy(strstart,asctime(&start_time));
9457:
9458: /* printf("Localtime (at start)=%s",strstart); */
9459: /* tp.tm_sec = tp.tm_sec +86400; */
9460: /* tm = *localtime(&start_time.tm_sec); */
9461: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
9462: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
9463: /* tmg.tm_hour=tmg.tm_hour + 1; */
9464: /* tp.tm_sec = mktime(&tmg); */
9465: /* strt=asctime(&tmg); */
9466: /* printf("Time(after) =%s",strstart); */
9467: /* (void) time (&time_value);
9468: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
9469: * tm = *localtime(&time_value);
9470: * strstart=asctime(&tm);
9471: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
9472: */
9473:
9474: nberr=0; /* Number of errors and warnings */
9475: nbwarn=0;
9476: #ifdef WIN32
9477: _getcwd(pathcd, size);
9478: #else
9479: getcwd(pathcd, size);
9480: #endif
9481: syscompilerinfo(0);
9482: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
9483: if(argc <=1){
9484: printf("\nEnter the parameter file name: ");
9485: if(!fgets(pathr,FILENAMELENGTH,stdin)){
9486: printf("ERROR Empty parameter file name\n");
9487: goto end;
9488: }
9489: i=strlen(pathr);
9490: if(pathr[i-1]=='\n')
9491: pathr[i-1]='\0';
9492: i=strlen(pathr);
9493: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
9494: pathr[i-1]='\0';
9495: }
9496: i=strlen(pathr);
9497: if( i==0 ){
9498: printf("ERROR Empty parameter file name\n");
9499: goto end;
9500: }
9501: for (tok = pathr; tok != NULL; ){
9502: printf("Pathr |%s|\n",pathr);
9503: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
9504: printf("val= |%s| pathr=%s\n",val,pathr);
9505: strcpy (pathtot, val);
9506: if(pathr[0] == '\0') break; /* Dirty */
9507: }
9508: }
9509: else{
9510: strcpy(pathtot,argv[1]);
9511: }
9512: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
9513: /*cygwin_split_path(pathtot,path,optionfile);
9514: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
9515: /* cutv(path,optionfile,pathtot,'\\');*/
9516:
9517: /* Split argv[0], imach program to get pathimach */
9518: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
9519: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
9520: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
9521: /* strcpy(pathimach,argv[0]); */
9522: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
9523: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
9524: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
9525: #ifdef WIN32
9526: _chdir(path); /* Can be a relative path */
9527: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
9528: #else
9529: chdir(path); /* Can be a relative path */
9530: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
9531: #endif
9532: printf("Current directory %s!\n",pathcd);
9533: strcpy(command,"mkdir ");
9534: strcat(command,optionfilefiname);
9535: if((outcmd=system(command)) != 0){
9536: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
9537: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
9538: /* fclose(ficlog); */
9539: /* exit(1); */
9540: }
9541: /* if((imk=mkdir(optionfilefiname))<0){ */
9542: /* perror("mkdir"); */
9543: /* } */
9544:
9545: /*-------- arguments in the command line --------*/
9546:
9547: /* Main Log file */
9548: strcat(filelog, optionfilefiname);
9549: strcat(filelog,".log"); /* */
9550: if((ficlog=fopen(filelog,"w"))==NULL) {
9551: printf("Problem with logfile %s\n",filelog);
9552: goto end;
9553: }
9554: fprintf(ficlog,"Log filename:%s\n",filelog);
9555: fprintf(ficlog,"Version %s %s",version,fullversion);
9556: fprintf(ficlog,"\nEnter the parameter file name: \n");
9557: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
9558: path=%s \n\
9559: optionfile=%s\n\
9560: optionfilext=%s\n\
9561: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
9562:
9563: syscompilerinfo(1);
9564:
9565: printf("Local time (at start):%s",strstart);
9566: fprintf(ficlog,"Local time (at start): %s",strstart);
9567: fflush(ficlog);
9568: /* (void) gettimeofday(&curr_time,&tzp); */
9569: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
9570:
9571: /* */
9572: strcpy(fileres,"r");
9573: strcat(fileres, optionfilefiname);
9574: strcat(fileresu, optionfilefiname); /* Without r in front */
9575: strcat(fileres,".txt"); /* Other files have txt extension */
9576: strcat(fileresu,".txt"); /* Other files have txt extension */
9577:
9578: /* Main ---------arguments file --------*/
9579:
9580: if((ficpar=fopen(optionfile,"r"))==NULL) {
9581: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
9582: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
9583: fflush(ficlog);
9584: /* goto end; */
9585: exit(70);
9586: }
9587:
9588:
9589:
9590: strcpy(filereso,"o");
9591: strcat(filereso,fileresu);
9592: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
9593: printf("Problem with Output resultfile: %s\n", filereso);
9594: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
9595: fflush(ficlog);
9596: goto end;
9597: }
9598:
9599: /* Reads comments: lines beginning with '#' */
9600: numlinepar=0;
9601:
9602: /* First parameter line */
9603: while(fgets(line, MAXLINE, ficpar)) {
9604: /* If line starts with a # it is a comment */
9605: if (line[0] == '#') {
9606: numlinepar++;
9607: fputs(line,stdout);
9608: fputs(line,ficparo);
9609: fputs(line,ficlog);
9610: continue;
9611: }else
9612: break;
9613: }
9614: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
9615: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
9616: if (num_filled != 5) {
9617: printf("Should be 5 parameters\n");
9618: }
9619: numlinepar++;
9620: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
9621: }
9622: /* Second parameter line */
9623: while(fgets(line, MAXLINE, ficpar)) {
9624: /* If line starts with a # it is a comment */
9625: if (line[0] == '#') {
9626: numlinepar++;
9627: fputs(line,stdout);
9628: fputs(line,ficparo);
9629: fputs(line,ficlog);
9630: continue;
9631: }else
9632: break;
9633: }
9634: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
9635: &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
9636: if (num_filled != 11) {
9637: printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
9638: printf("but line=%s\n",line);
9639: }
9640: printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
9641: }
9642: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
9643: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
9644: /* Third parameter line */
9645: while(fgets(line, MAXLINE, ficpar)) {
9646: /* If line starts with a # it is a comment */
9647: if (line[0] == '#') {
9648: numlinepar++;
9649: fputs(line,stdout);
9650: fputs(line,ficparo);
9651: fputs(line,ficlog);
9652: continue;
9653: }else
9654: break;
9655: }
9656: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
9657: if (num_filled == 0)
9658: model[0]='\0';
9659: else if (num_filled != 1){
9660: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
9661: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
9662: model[0]='\0';
9663: goto end;
9664: }
9665: else{
9666: if (model[0]=='+'){
9667: for(i=1; i<=strlen(model);i++)
9668: modeltemp[i-1]=model[i];
9669: strcpy(model,modeltemp);
9670: }
9671: }
9672: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
9673: printf("model=1+age+%s\n",model);fflush(stdout);
9674: }
9675: /* 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); */
9676: /* numlinepar=numlinepar+3; /\* In general *\/ */
9677: /* 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); */
9678: fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
9679: fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
9680: fflush(ficlog);
9681: /* if(model[0]=='#'|| model[0]== '\0'){ */
9682: if(model[0]=='#'){
9683: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
9684: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
9685: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
9686: if(mle != -1){
9687: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
9688: exit(1);
9689: }
9690: }
9691: while((c=getc(ficpar))=='#' && c!= EOF){
9692: ungetc(c,ficpar);
9693: fgets(line, MAXLINE, ficpar);
9694: numlinepar++;
9695: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
9696: z[0]=line[1];
9697: }
9698: /* printf("****line [1] = %c \n",line[1]); */
9699: fputs(line, stdout);
9700: //puts(line);
9701: fputs(line,ficparo);
9702: fputs(line,ficlog);
9703: }
9704: ungetc(c,ficpar);
9705:
9706:
9707: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
9708: coqvar=matrix(1,nqv,1,n); /**< Fixed quantitative covariate */
9709: cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n); /**< Time varying covariate (dummy and quantitative)*/
9710: cotqvar=ma3x(1,maxwav,1,nqtv,1,n); /**< Time varying quantitative covariate */
9711: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
9712: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
9713: v1+v2*age+v2*v3 makes cptcovn = 3
9714: */
9715: if (strlen(model)>1)
9716: 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*/
9717: else
9718: ncovmodel=2; /* Constant and age */
9719: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
9720: npar= nforce*ncovmodel; /* Number of parameters like aij*/
9721: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
9722: 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);
9723: 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);
9724: fflush(stdout);
9725: fclose (ficlog);
9726: goto end;
9727: }
9728: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
9729: delti=delti3[1][1];
9730: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
9731: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
9732: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
9733: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
9734: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
9735: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
9736: fclose (ficparo);
9737: fclose (ficlog);
9738: goto end;
9739: exit(0);
9740: } else if(mle==-5) { /* Main Wizard */
9741: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
9742: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
9743: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
9744: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
9745: matcov=matrix(1,npar,1,npar);
9746: hess=matrix(1,npar,1,npar);
9747: } else{ /* Begin of mle != -1 or -5 */
9748: /* Read guessed parameters */
9749: /* Reads comments: lines beginning with '#' */
9750: while((c=getc(ficpar))=='#' && c!= EOF){
9751: ungetc(c,ficpar);
9752: fgets(line, MAXLINE, ficpar);
9753: numlinepar++;
9754: fputs(line,stdout);
9755: fputs(line,ficparo);
9756: fputs(line,ficlog);
9757: }
9758: ungetc(c,ficpar);
9759:
9760: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
9761: for(i=1; i <=nlstate; i++){
9762: j=0;
9763: for(jj=1; jj <=nlstate+ndeath; jj++){
9764: if(jj==i) continue;
9765: j++;
9766: fscanf(ficpar,"%1d%1d",&i1,&j1);
9767: if ((i1 != i) || (j1 != jj)){
9768: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
9769: It might be a problem of design; if ncovcol and the model are correct\n \
9770: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
9771: exit(1);
9772: }
9773: fprintf(ficparo,"%1d%1d",i1,j1);
9774: if(mle==1)
9775: printf("%1d%1d",i,jj);
9776: fprintf(ficlog,"%1d%1d",i,jj);
9777: for(k=1; k<=ncovmodel;k++){
9778: fscanf(ficpar," %lf",¶m[i][j][k]);
9779: if(mle==1){
9780: printf(" %lf",param[i][j][k]);
9781: fprintf(ficlog," %lf",param[i][j][k]);
9782: }
9783: else
9784: fprintf(ficlog," %lf",param[i][j][k]);
9785: fprintf(ficparo," %lf",param[i][j][k]);
9786: }
9787: fscanf(ficpar,"\n");
9788: numlinepar++;
9789: if(mle==1)
9790: printf("\n");
9791: fprintf(ficlog,"\n");
9792: fprintf(ficparo,"\n");
9793: }
9794: }
9795: fflush(ficlog);
9796:
9797: /* Reads scales values */
9798: p=param[1][1];
9799:
9800: /* Reads comments: lines beginning with '#' */
9801: while((c=getc(ficpar))=='#' && c!= EOF){
9802: ungetc(c,ficpar);
9803: fgets(line, MAXLINE, ficpar);
9804: numlinepar++;
9805: fputs(line,stdout);
9806: fputs(line,ficparo);
9807: fputs(line,ficlog);
9808: }
9809: ungetc(c,ficpar);
9810:
9811: for(i=1; i <=nlstate; i++){
9812: for(j=1; j <=nlstate+ndeath-1; j++){
9813: fscanf(ficpar,"%1d%1d",&i1,&j1);
9814: if ( (i1-i) * (j1-j) != 0){
9815: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
9816: exit(1);
9817: }
9818: printf("%1d%1d",i,j);
9819: fprintf(ficparo,"%1d%1d",i1,j1);
9820: fprintf(ficlog,"%1d%1d",i1,j1);
9821: for(k=1; k<=ncovmodel;k++){
9822: fscanf(ficpar,"%le",&delti3[i][j][k]);
9823: printf(" %le",delti3[i][j][k]);
9824: fprintf(ficparo," %le",delti3[i][j][k]);
9825: fprintf(ficlog," %le",delti3[i][j][k]);
9826: }
9827: fscanf(ficpar,"\n");
9828: numlinepar++;
9829: printf("\n");
9830: fprintf(ficparo,"\n");
9831: fprintf(ficlog,"\n");
9832: }
9833: }
9834: fflush(ficlog);
9835:
9836: /* Reads covariance matrix */
9837: delti=delti3[1][1];
9838:
9839:
9840: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
9841:
9842: /* Reads comments: lines beginning with '#' */
9843: while((c=getc(ficpar))=='#' && c!= EOF){
9844: ungetc(c,ficpar);
9845: fgets(line, MAXLINE, ficpar);
9846: numlinepar++;
9847: fputs(line,stdout);
9848: fputs(line,ficparo);
9849: fputs(line,ficlog);
9850: }
9851: ungetc(c,ficpar);
9852:
9853: matcov=matrix(1,npar,1,npar);
9854: hess=matrix(1,npar,1,npar);
9855: for(i=1; i <=npar; i++)
9856: for(j=1; j <=npar; j++) matcov[i][j]=0.;
9857:
9858: /* Scans npar lines */
9859: for(i=1; i <=npar; i++){
9860: count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
9861: if(count != 3){
9862: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
9863: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
9864: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
9865: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
9866: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
9867: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
9868: exit(1);
9869: }else{
9870: if(mle==1)
9871: printf("%1d%1d%d",i1,j1,jk);
9872: }
9873: fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
9874: fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
9875: for(j=1; j <=i; j++){
9876: fscanf(ficpar," %le",&matcov[i][j]);
9877: if(mle==1){
9878: printf(" %.5le",matcov[i][j]);
9879: }
9880: fprintf(ficlog," %.5le",matcov[i][j]);
9881: fprintf(ficparo," %.5le",matcov[i][j]);
9882: }
9883: fscanf(ficpar,"\n");
9884: numlinepar++;
9885: if(mle==1)
9886: printf("\n");
9887: fprintf(ficlog,"\n");
9888: fprintf(ficparo,"\n");
9889: }
9890: /* End of read covariance matrix npar lines */
9891: for(i=1; i <=npar; i++)
9892: for(j=i+1;j<=npar;j++)
9893: matcov[i][j]=matcov[j][i];
9894:
9895: if(mle==1)
9896: printf("\n");
9897: fprintf(ficlog,"\n");
9898:
9899: fflush(ficlog);
9900:
9901: /*-------- Rewriting parameter file ----------*/
9902: strcpy(rfileres,"r"); /* "Rparameterfile */
9903: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
9904: strcat(rfileres,"."); /* */
9905: strcat(rfileres,optionfilext); /* Other files have txt extension */
9906: if((ficres =fopen(rfileres,"w"))==NULL) {
9907: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
9908: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
9909: }
9910: fprintf(ficres,"#%s\n",version);
9911: } /* End of mle != -3 */
9912:
9913: /* Main data
9914: */
9915: n= lastobs;
9916: num=lvector(1,n);
9917: moisnais=vector(1,n);
9918: annais=vector(1,n);
9919: moisdc=vector(1,n);
9920: andc=vector(1,n);
9921: weight=vector(1,n);
9922: agedc=vector(1,n);
9923: cod=ivector(1,n);
9924: for(i=1;i<=n;i++){
9925: num[i]=0;
9926: moisnais[i]=0;
9927: annais[i]=0;
9928: moisdc[i]=0;
9929: andc[i]=0;
9930: agedc[i]=0;
9931: cod[i]=0;
9932: weight[i]=1.0; /* Equal weights, 1 by default */
9933: }
9934: mint=matrix(1,maxwav,1,n);
9935: anint=matrix(1,maxwav,1,n);
9936: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
9937: tab=ivector(1,NCOVMAX);
9938: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
9939: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
9940:
9941: /* Reads data from file datafile */
9942: if (readdata(datafile, firstobs, lastobs, &imx)==1)
9943: goto end;
9944:
9945: /* Calculation of the number of parameters from char model */
9946: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
9947: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
9948: k=3 V4 Tvar[k=3]= 4 (from V4)
9949: k=2 V1 Tvar[k=2]= 1 (from V1)
9950: k=1 Tvar[1]=2 (from V2)
9951: */
9952:
9953: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
9954: TvarsDind=ivector(1,NCOVMAX); /* */
9955: TvarsD=ivector(1,NCOVMAX); /* */
9956: TvarsQind=ivector(1,NCOVMAX); /* */
9957: TvarsQ=ivector(1,NCOVMAX); /* */
9958: TvarF=ivector(1,NCOVMAX); /* */
9959: TvarFind=ivector(1,NCOVMAX); /* */
9960: TvarV=ivector(1,NCOVMAX); /* */
9961: TvarVind=ivector(1,NCOVMAX); /* */
9962: TvarA=ivector(1,NCOVMAX); /* */
9963: TvarAind=ivector(1,NCOVMAX); /* */
9964: TvarFD=ivector(1,NCOVMAX); /* */
9965: TvarFDind=ivector(1,NCOVMAX); /* */
9966: TvarFQ=ivector(1,NCOVMAX); /* */
9967: TvarFQind=ivector(1,NCOVMAX); /* */
9968: TvarVD=ivector(1,NCOVMAX); /* */
9969: TvarVDind=ivector(1,NCOVMAX); /* */
9970: TvarVQ=ivector(1,NCOVMAX); /* */
9971: TvarVQind=ivector(1,NCOVMAX); /* */
9972:
9973: Tvalsel=vector(1,NCOVMAX); /* */
9974: Tvarsel=ivector(1,NCOVMAX); /* */
9975: Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
9976: Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
9977: Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
9978: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
9979: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
9980: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
9981: */
9982: /* For model-covariate k tells which data-covariate to use but
9983: because this model-covariate is a construction we invent a new column
9984: ncovcol + k1
9985: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
9986: Tvar[3=V1*V4]=4+1 etc */
9987: Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
9988: Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
9989: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
9990: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
9991: Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2
9992: */
9993: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
9994: 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
9995: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
9996: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
9997: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
9998: 4 covariates (3 plus signs)
9999: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
10000: */
10001: Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
10002: * individual dummy, fixed or varying:
10003: * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
10004: * 3, 1, 0, 0, 0, 0, 0, 0},
10005: * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 ,
10006: * V1 df, V2 qf, V3 & V4 dv, V5 qv
10007: * Tmodelind[1]@9={9,0,3,2,}*/
10008: TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
10009: TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
10010: * individual quantitative, fixed or varying:
10011: * Tmodelqind[1]=1,Tvaraff[1]@9={4,
10012: * 3, 1, 0, 0, 0, 0, 0, 0},
10013: * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
10014: /* Main decodemodel */
10015:
10016:
10017: if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3 = {4, 3, 5}*/
10018: goto end;
10019:
10020: if((double)(lastobs-imx)/(double)imx > 1.10){
10021: nbwarn++;
10022: 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);
10023: 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);
10024: }
10025: /* if(mle==1){*/
10026: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
10027: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
10028: }
10029:
10030: /*-calculation of age at interview from date of interview and age at death -*/
10031: agev=matrix(1,maxwav,1,imx);
10032:
10033: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
10034: goto end;
10035:
10036:
10037: agegomp=(int)agemin;
10038: free_vector(moisnais,1,n);
10039: free_vector(annais,1,n);
10040: /* free_matrix(mint,1,maxwav,1,n);
10041: free_matrix(anint,1,maxwav,1,n);*/
10042: /* free_vector(moisdc,1,n); */
10043: /* free_vector(andc,1,n); */
10044: /* */
10045:
10046: wav=ivector(1,imx);
10047: /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
10048: /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
10049: /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
10050: 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.*/
10051: bh=imatrix(1,lastpass-firstpass+2,1,imx);
10052: mw=imatrix(1,lastpass-firstpass+2,1,imx);
10053:
10054: /* Concatenates waves */
10055: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
10056: Death is a valid wave (if date is known).
10057: mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
10058: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
10059: and mw[mi+1][i]. dh depends on stepm.
10060: */
10061:
10062: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
10063: /* */
10064:
10065: free_vector(moisdc,1,n);
10066: free_vector(andc,1,n);
10067:
10068: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
10069: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
10070: ncodemax[1]=1;
10071: Ndum =ivector(-1,NCOVMAX);
10072: cptcoveff=0;
10073: if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
10074: tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
10075: }
10076:
10077: ncovcombmax=pow(2,cptcoveff);
10078: invalidvarcomb=ivector(1, ncovcombmax);
10079: for(i=1;i<ncovcombmax;i++)
10080: invalidvarcomb[i]=0;
10081:
10082: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
10083: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
10084: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
10085:
10086: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
10087: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
10088: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
10089: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
10090: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
10091: * (currently 0 or 1) in the data.
10092: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
10093: * corresponding modality (h,j).
10094: */
10095:
10096: h=0;
10097: /*if (cptcovn > 0) */
10098: m=pow(2,cptcoveff);
10099:
10100: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
10101: * For k=4 covariates, h goes from 1 to m=2**k
10102: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
10103: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
10104: * h\k 1 2 3 4
10105: *______________________________
10106: * 1 i=1 1 i=1 1 i=1 1 i=1 1
10107: * 2 2 1 1 1
10108: * 3 i=2 1 2 1 1
10109: * 4 2 2 1 1
10110: * 5 i=3 1 i=2 1 2 1
10111: * 6 2 1 2 1
10112: * 7 i=4 1 2 2 1
10113: * 8 2 2 2 1
10114: * 9 i=5 1 i=3 1 i=2 1 2
10115: * 10 2 1 1 2
10116: * 11 i=6 1 2 1 2
10117: * 12 2 2 1 2
10118: * 13 i=7 1 i=4 1 2 2
10119: * 14 2 1 2 2
10120: * 15 i=8 1 2 2 2
10121: * 16 2 2 2 2
10122: */
10123: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
10124: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
10125: * and the value of each covariate?
10126: * V1=1, V2=1, V3=2, V4=1 ?
10127: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
10128: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
10129: * In order to get the real value in the data, we use nbcode
10130: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
10131: * We are keeping this crazy system in order to be able (in the future?)
10132: * to have more than 2 values (0 or 1) for a covariate.
10133: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
10134: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
10135: * bbbbbbbb
10136: * 76543210
10137: * h-1 00000101 (6-1=5)
10138: *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
10139: * &
10140: * 1 00000001 (1)
10141: * 00000000 = 1 & ((h-1) >> (k-1))
10142: * +1= 00000001 =1
10143: *
10144: * h=14, k=3 => h'=h-1=13, k'=k-1=2
10145: * h' 1101 =2^3+2^2+0x2^1+2^0
10146: * >>k' 11
10147: * & 00000001
10148: * = 00000001
10149: * +1 = 00000010=2 = codtabm(14,3)
10150: * Reverse h=6 and m=16?
10151: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
10152: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
10153: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
10154: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
10155: * V3=decodtabm(14,3,2**4)=2
10156: * h'=13 1101 =2^3+2^2+0x2^1+2^0
10157: *(h-1) >> (j-1) 0011 =13 >> 2
10158: * &1 000000001
10159: * = 000000001
10160: * +1= 000000010 =2
10161: * 2211
10162: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
10163: * V3=2
10164: * codtabm and decodtabm are identical
10165: */
10166:
10167:
10168: free_ivector(Ndum,-1,NCOVMAX);
10169:
10170:
10171:
10172: /* Initialisation of ----------- gnuplot -------------*/
10173: strcpy(optionfilegnuplot,optionfilefiname);
10174: if(mle==-3)
10175: strcat(optionfilegnuplot,"-MORT_");
10176: strcat(optionfilegnuplot,".gp");
10177:
10178: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
10179: printf("Problem with file %s",optionfilegnuplot);
10180: }
10181: else{
10182: fprintf(ficgp,"\n# IMaCh-%s\n", version);
10183: fprintf(ficgp,"# %s\n", optionfilegnuplot);
10184: //fprintf(ficgp,"set missing 'NaNq'\n");
10185: fprintf(ficgp,"set datafile missing 'NaNq'\n");
10186: }
10187: /* fclose(ficgp);*/
10188:
10189:
10190: /* Initialisation of --------- index.htm --------*/
10191:
10192: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
10193: if(mle==-3)
10194: strcat(optionfilehtm,"-MORT_");
10195: strcat(optionfilehtm,".htm");
10196: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
10197: printf("Problem with %s \n",optionfilehtm);
10198: exit(0);
10199: }
10200:
10201: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
10202: strcat(optionfilehtmcov,"-cov.htm");
10203: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
10204: printf("Problem with %s \n",optionfilehtmcov), exit(0);
10205: }
10206: else{
10207: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
10208: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10209: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
10210: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
10211: }
10212:
10213: 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> \
10214: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10215: <font size=\"2\">IMaCh-%s <br> %s</font> \
10216: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10217: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
10218: \n\
10219: <hr size=\"2\" color=\"#EC5E5E\">\
10220: <ul><li><h4>Parameter files</h4>\n\
10221: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
10222: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
10223: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
10224: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
10225: - Date and time at start: %s</ul>\n",\
10226: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
10227: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
10228: fileres,fileres,\
10229: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
10230: fflush(fichtm);
10231:
10232: strcpy(pathr,path);
10233: strcat(pathr,optionfilefiname);
10234: #ifdef WIN32
10235: _chdir(optionfilefiname); /* Move to directory named optionfile */
10236: #else
10237: chdir(optionfilefiname); /* Move to directory named optionfile */
10238: #endif
10239:
10240:
10241: /* Calculates basic frequencies. Computes observed prevalence at single age
10242: and for any valid combination of covariates
10243: and prints on file fileres'p'. */
10244: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
10245: firstpass, lastpass, stepm, weightopt, model);
10246:
10247: fprintf(fichtm,"\n");
10248: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
10249: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
10250: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
10251: imx,agemin,agemax,jmin,jmax,jmean);
10252: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10253: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10254: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10255: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10256: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
10257:
10258: /* For Powell, parameters are in a vector p[] starting at p[1]
10259: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
10260: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
10261:
10262: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
10263: /* For mortality only */
10264: if (mle==-3){
10265: ximort=matrix(1,NDIM,1,NDIM);
10266: for(i=1;i<=NDIM;i++)
10267: for(j=1;j<=NDIM;j++)
10268: ximort[i][j]=0.;
10269: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
10270: cens=ivector(1,n);
10271: ageexmed=vector(1,n);
10272: agecens=vector(1,n);
10273: dcwave=ivector(1,n);
10274:
10275: for (i=1; i<=imx; i++){
10276: dcwave[i]=-1;
10277: for (m=firstpass; m<=lastpass; m++)
10278: if (s[m][i]>nlstate) {
10279: dcwave[i]=m;
10280: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
10281: break;
10282: }
10283: }
10284:
10285: for (i=1; i<=imx; i++) {
10286: if (wav[i]>0){
10287: ageexmed[i]=agev[mw[1][i]][i];
10288: j=wav[i];
10289: agecens[i]=1.;
10290:
10291: if (ageexmed[i]> 1 && wav[i] > 0){
10292: agecens[i]=agev[mw[j][i]][i];
10293: cens[i]= 1;
10294: }else if (ageexmed[i]< 1)
10295: cens[i]= -1;
10296: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
10297: cens[i]=0 ;
10298: }
10299: else cens[i]=-1;
10300: }
10301:
10302: for (i=1;i<=NDIM;i++) {
10303: for (j=1;j<=NDIM;j++)
10304: ximort[i][j]=(i == j ? 1.0 : 0.0);
10305: }
10306:
10307: /*p[1]=0.0268; p[NDIM]=0.083;*/
10308: /*printf("%lf %lf", p[1], p[2]);*/
10309:
10310:
10311: #ifdef GSL
10312: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
10313: #else
10314: printf("Powell\n"); fprintf(ficlog,"Powell\n");
10315: #endif
10316: strcpy(filerespow,"POW-MORT_");
10317: strcat(filerespow,fileresu);
10318: if((ficrespow=fopen(filerespow,"w"))==NULL) {
10319: printf("Problem with resultfile: %s\n", filerespow);
10320: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
10321: }
10322: #ifdef GSL
10323: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
10324: #else
10325: fprintf(ficrespow,"# Powell\n# iter -2*LL");
10326: #endif
10327: /* for (i=1;i<=nlstate;i++)
10328: for(j=1;j<=nlstate+ndeath;j++)
10329: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
10330: */
10331: fprintf(ficrespow,"\n");
10332: #ifdef GSL
10333: /* gsl starts here */
10334: T = gsl_multimin_fminimizer_nmsimplex;
10335: gsl_multimin_fminimizer *sfm = NULL;
10336: gsl_vector *ss, *x;
10337: gsl_multimin_function minex_func;
10338:
10339: /* Initial vertex size vector */
10340: ss = gsl_vector_alloc (NDIM);
10341:
10342: if (ss == NULL){
10343: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
10344: }
10345: /* Set all step sizes to 1 */
10346: gsl_vector_set_all (ss, 0.001);
10347:
10348: /* Starting point */
10349:
10350: x = gsl_vector_alloc (NDIM);
10351:
10352: if (x == NULL){
10353: gsl_vector_free(ss);
10354: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
10355: }
10356:
10357: /* Initialize method and iterate */
10358: /* p[1]=0.0268; p[NDIM]=0.083; */
10359: /* gsl_vector_set(x, 0, 0.0268); */
10360: /* gsl_vector_set(x, 1, 0.083); */
10361: gsl_vector_set(x, 0, p[1]);
10362: gsl_vector_set(x, 1, p[2]);
10363:
10364: minex_func.f = &gompertz_f;
10365: minex_func.n = NDIM;
10366: minex_func.params = (void *)&p; /* ??? */
10367:
10368: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
10369: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
10370:
10371: printf("Iterations beginning .....\n\n");
10372: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
10373:
10374: iteri=0;
10375: while (rval == GSL_CONTINUE){
10376: iteri++;
10377: status = gsl_multimin_fminimizer_iterate(sfm);
10378:
10379: if (status) printf("error: %s\n", gsl_strerror (status));
10380: fflush(0);
10381:
10382: if (status)
10383: break;
10384:
10385: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
10386: ssval = gsl_multimin_fminimizer_size (sfm);
10387:
10388: if (rval == GSL_SUCCESS)
10389: printf ("converged to a local maximum at\n");
10390:
10391: printf("%5d ", iteri);
10392: for (it = 0; it < NDIM; it++){
10393: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
10394: }
10395: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
10396: }
10397:
10398: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
10399:
10400: gsl_vector_free(x); /* initial values */
10401: gsl_vector_free(ss); /* inital step size */
10402: for (it=0; it<NDIM; it++){
10403: p[it+1]=gsl_vector_get(sfm->x,it);
10404: fprintf(ficrespow," %.12lf", p[it]);
10405: }
10406: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
10407: #endif
10408: #ifdef POWELL
10409: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
10410: #endif
10411: fclose(ficrespow);
10412:
10413: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
10414:
10415: for(i=1; i <=NDIM; i++)
10416: for(j=i+1;j<=NDIM;j++)
10417: matcov[i][j]=matcov[j][i];
10418:
10419: printf("\nCovariance matrix\n ");
10420: fprintf(ficlog,"\nCovariance matrix\n ");
10421: for(i=1; i <=NDIM; i++) {
10422: for(j=1;j<=NDIM;j++){
10423: printf("%f ",matcov[i][j]);
10424: fprintf(ficlog,"%f ",matcov[i][j]);
10425: }
10426: printf("\n "); fprintf(ficlog,"\n ");
10427: }
10428:
10429: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
10430: for (i=1;i<=NDIM;i++) {
10431: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10432: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10433: }
10434: lsurv=vector(1,AGESUP);
10435: lpop=vector(1,AGESUP);
10436: tpop=vector(1,AGESUP);
10437: lsurv[agegomp]=100000;
10438:
10439: for (k=agegomp;k<=AGESUP;k++) {
10440: agemortsup=k;
10441: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
10442: }
10443:
10444: for (k=agegomp;k<agemortsup;k++)
10445: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
10446:
10447: for (k=agegomp;k<agemortsup;k++){
10448: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
10449: sumlpop=sumlpop+lpop[k];
10450: }
10451:
10452: tpop[agegomp]=sumlpop;
10453: for (k=agegomp;k<(agemortsup-3);k++){
10454: /* tpop[k+1]=2;*/
10455: tpop[k+1]=tpop[k]-lpop[k];
10456: }
10457:
10458:
10459: printf("\nAge lx qx dx Lx Tx e(x)\n");
10460: for (k=agegomp;k<(agemortsup-2);k++)
10461: 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]);
10462:
10463:
10464: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10465: ageminpar=50;
10466: agemaxpar=100;
10467: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
10468: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10469: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
10470: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10471: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10472: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
10473: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10474: }else{
10475: printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10476: fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10477: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
10478: }
10479: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
10480: stepm, weightopt,\
10481: model,imx,p,matcov,agemortsup);
10482:
10483: free_vector(lsurv,1,AGESUP);
10484: free_vector(lpop,1,AGESUP);
10485: free_vector(tpop,1,AGESUP);
10486: free_matrix(ximort,1,NDIM,1,NDIM);
10487: free_ivector(cens,1,n);
10488: free_vector(agecens,1,n);
10489: free_ivector(dcwave,1,n);
10490: #ifdef GSL
10491: #endif
10492: } /* Endof if mle==-3 mortality only */
10493: /* Standard */
10494: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
10495: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10496: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10497: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10498: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10499: for (k=1; k<=npar;k++)
10500: printf(" %d %8.5f",k,p[k]);
10501: printf("\n");
10502: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
10503: /* mlikeli uses func not funcone */
10504: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
10505: }
10506: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
10507: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10508: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10509: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10510: }
10511: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
10512: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10513: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10514: for (k=1; k<=npar;k++)
10515: printf(" %d %8.5f",k,p[k]);
10516: printf("\n");
10517:
10518: /*--------- results files --------------*/
10519: fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, weightopt,model);
10520:
10521:
10522: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10523: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10524: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10525: for(i=1,jk=1; i <=nlstate; i++){
10526: for(k=1; k <=(nlstate+ndeath); k++){
10527: if (k != i) {
10528: printf("%d%d ",i,k);
10529: fprintf(ficlog,"%d%d ",i,k);
10530: fprintf(ficres,"%1d%1d ",i,k);
10531: for(j=1; j <=ncovmodel; j++){
10532: printf("%12.7f ",p[jk]);
10533: fprintf(ficlog,"%12.7f ",p[jk]);
10534: fprintf(ficres,"%12.7f ",p[jk]);
10535: jk++;
10536: }
10537: printf("\n");
10538: fprintf(ficlog,"\n");
10539: fprintf(ficres,"\n");
10540: }
10541: }
10542: }
10543: if(mle != 0){
10544: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
10545: ftolhess=ftol; /* Usually correct */
10546: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
10547: 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");
10548: 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");
10549: for(i=1,jk=1; i <=nlstate; i++){
10550: for(k=1; k <=(nlstate+ndeath); k++){
10551: if (k != i) {
10552: printf("%d%d ",i,k);
10553: fprintf(ficlog,"%d%d ",i,k);
10554: for(j=1; j <=ncovmodel; j++){
10555: 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]));
10556: 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]));
10557: jk++;
10558: }
10559: printf("\n");
10560: fprintf(ficlog,"\n");
10561: }
10562: }
10563: }
10564: } /* end of hesscov and Wald tests */
10565:
10566: /* */
10567: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
10568: printf("# Scales (for hessian or gradient estimation)\n");
10569: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
10570: for(i=1,jk=1; i <=nlstate; i++){
10571: for(j=1; j <=nlstate+ndeath; j++){
10572: if (j!=i) {
10573: fprintf(ficres,"%1d%1d",i,j);
10574: printf("%1d%1d",i,j);
10575: fprintf(ficlog,"%1d%1d",i,j);
10576: for(k=1; k<=ncovmodel;k++){
10577: printf(" %.5e",delti[jk]);
10578: fprintf(ficlog," %.5e",delti[jk]);
10579: fprintf(ficres," %.5e",delti[jk]);
10580: jk++;
10581: }
10582: printf("\n");
10583: fprintf(ficlog,"\n");
10584: fprintf(ficres,"\n");
10585: }
10586: }
10587: }
10588:
10589: 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");
10590: if(mle >= 1) /* To big for the screen */
10591: 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");
10592: 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");
10593: /* # 121 Var(a12)\n\ */
10594: /* # 122 Cov(b12,a12) Var(b12)\n\ */
10595: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10596: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10597: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10598: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10599: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10600: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10601:
10602:
10603: /* Just to have a covariance matrix which will be more understandable
10604: even is we still don't want to manage dictionary of variables
10605: */
10606: for(itimes=1;itimes<=2;itimes++){
10607: jj=0;
10608: for(i=1; i <=nlstate; i++){
10609: for(j=1; j <=nlstate+ndeath; j++){
10610: if(j==i) continue;
10611: for(k=1; k<=ncovmodel;k++){
10612: jj++;
10613: ca[0]= k+'a'-1;ca[1]='\0';
10614: if(itimes==1){
10615: if(mle>=1)
10616: printf("#%1d%1d%d",i,j,k);
10617: fprintf(ficlog,"#%1d%1d%d",i,j,k);
10618: fprintf(ficres,"#%1d%1d%d",i,j,k);
10619: }else{
10620: if(mle>=1)
10621: printf("%1d%1d%d",i,j,k);
10622: fprintf(ficlog,"%1d%1d%d",i,j,k);
10623: fprintf(ficres,"%1d%1d%d",i,j,k);
10624: }
10625: ll=0;
10626: for(li=1;li <=nlstate; li++){
10627: for(lj=1;lj <=nlstate+ndeath; lj++){
10628: if(lj==li) continue;
10629: for(lk=1;lk<=ncovmodel;lk++){
10630: ll++;
10631: if(ll<=jj){
10632: cb[0]= lk +'a'-1;cb[1]='\0';
10633: if(ll<jj){
10634: if(itimes==1){
10635: if(mle>=1)
10636: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10637: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10638: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10639: }else{
10640: if(mle>=1)
10641: printf(" %.5e",matcov[jj][ll]);
10642: fprintf(ficlog," %.5e",matcov[jj][ll]);
10643: fprintf(ficres," %.5e",matcov[jj][ll]);
10644: }
10645: }else{
10646: if(itimes==1){
10647: if(mle>=1)
10648: printf(" Var(%s%1d%1d)",ca,i,j);
10649: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
10650: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
10651: }else{
10652: if(mle>=1)
10653: printf(" %.7e",matcov[jj][ll]);
10654: fprintf(ficlog," %.7e",matcov[jj][ll]);
10655: fprintf(ficres," %.7e",matcov[jj][ll]);
10656: }
10657: }
10658: }
10659: } /* end lk */
10660: } /* end lj */
10661: } /* end li */
10662: if(mle>=1)
10663: printf("\n");
10664: fprintf(ficlog,"\n");
10665: fprintf(ficres,"\n");
10666: numlinepar++;
10667: } /* end k*/
10668: } /*end j */
10669: } /* end i */
10670: } /* end itimes */
10671:
10672: fflush(ficlog);
10673: fflush(ficres);
10674: while(fgets(line, MAXLINE, ficpar)) {
10675: /* If line starts with a # it is a comment */
10676: if (line[0] == '#') {
10677: numlinepar++;
10678: fputs(line,stdout);
10679: fputs(line,ficparo);
10680: fputs(line,ficlog);
10681: continue;
10682: }else
10683: break;
10684: }
10685:
10686: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
10687: /* ungetc(c,ficpar); */
10688: /* fgets(line, MAXLINE, ficpar); */
10689: /* fputs(line,stdout); */
10690: /* fputs(line,ficparo); */
10691: /* } */
10692: /* ungetc(c,ficpar); */
10693:
10694: estepm=0;
10695: 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){
10696:
10697: if (num_filled != 6) {
10698: printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
10699: fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
10700: goto end;
10701: }
10702: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
10703: }
10704: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
10705: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
10706:
10707: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
10708: if (estepm==0 || estepm < stepm) estepm=stepm;
10709: if (fage <= 2) {
10710: bage = ageminpar;
10711: fage = agemaxpar;
10712: }
10713:
10714: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
10715: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10716: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10717:
10718: /* Other stuffs, more or less useful */
10719: while((c=getc(ficpar))=='#' && c!= EOF){
10720: ungetc(c,ficpar);
10721: fgets(line, MAXLINE, ficpar);
10722: fputs(line,stdout);
10723: fputs(line,ficparo);
10724: }
10725: ungetc(c,ficpar);
10726:
10727: 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);
10728: 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);
10729: 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);
10730: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
10731: 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);
10732:
10733: while((c=getc(ficpar))=='#' && c!= EOF){
10734: ungetc(c,ficpar);
10735: fgets(line, MAXLINE, ficpar);
10736: fputs(line,stdout);
10737: fputs(line,ficparo);
10738: }
10739: ungetc(c,ficpar);
10740:
10741:
10742: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
10743: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
10744:
10745: fscanf(ficpar,"pop_based=%d\n",&popbased);
10746: fprintf(ficlog,"pop_based=%d\n",popbased);
10747: fprintf(ficparo,"pop_based=%d\n",popbased);
10748: fprintf(ficres,"pop_based=%d\n",popbased);
10749:
10750: while((c=getc(ficpar))=='#' && c!= EOF){
10751: ungetc(c,ficpar);
10752: fgets(line, MAXLINE, ficpar);
10753: fputs(line,stdout);
10754: fputs(line,ficparo);
10755: }
10756: ungetc(c,ficpar);
10757:
10758: 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);
10759: 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);
10760: 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);
10761: 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);
10762: 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);
10763: /* day and month of proj2 are not used but only year anproj2.*/
10764:
10765: while((c=getc(ficpar))=='#' && c!= EOF){
10766: ungetc(c,ficpar);
10767: fgets(line, MAXLINE, ficpar);
10768: fputs(line,stdout);
10769: fputs(line,ficparo);
10770: }
10771: ungetc(c,ficpar);
10772:
10773: fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
10774: fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
10775: fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
10776: fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
10777: /* day and month of proj2 are not used but only year anproj2.*/
10778:
10779: /* Results */
10780: nresult=0;
10781: while(fgets(line, MAXLINE, ficpar)) {
10782: /* If line starts with a # it is a comment */
10783: if (line[0] == '#') {
10784: numlinepar++;
10785: fputs(line,stdout);
10786: fputs(line,ficparo);
10787: fputs(line,ficlog);
10788: continue;
10789: }else
10790: break;
10791: }
10792: while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
10793: if (num_filled == 0)
10794: resultline[0]='\0';
10795: else if (num_filled != 1){
10796: printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
10797: }
10798: nresult++; /* Sum of resultlines */
10799: printf("Result %d: result=%s\n",nresult, resultline);
10800: if(nresult > MAXRESULTLINES){
10801: printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10802: fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10803: goto end;
10804: }
10805: decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
10806: while(fgets(line, MAXLINE, ficpar)) {
10807: /* If line starts with a # it is a comment */
10808: if (line[0] == '#') {
10809: numlinepar++;
10810: fputs(line,stdout);
10811: fputs(line,ficparo);
10812: fputs(line,ficlog);
10813: continue;
10814: }else
10815: break;
10816: }
10817: if (feof(ficpar))
10818: break;
10819: else{ /* Processess output results for this combination of covariate values */
10820: }
10821: }
10822:
10823:
10824:
10825: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
10826: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
10827:
10828: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10829: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
10830: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10831: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
10832: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10833: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10834: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
10835: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10836: }else{
10837: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
10838: }
10839: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
10840: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
10841: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
10842:
10843: /*------------ free_vector -------------*/
10844: /* chdir(path); */
10845:
10846: /* free_ivector(wav,1,imx); */ /* Moved after last prevalence call */
10847: /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
10848: /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
10849: /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx); */
10850: free_lvector(num,1,n);
10851: free_vector(agedc,1,n);
10852: /*free_matrix(covar,0,NCOVMAX,1,n);*/
10853: /*free_matrix(covar,1,NCOVMAX,1,n);*/
10854: fclose(ficparo);
10855: fclose(ficres);
10856:
10857:
10858: /* Other results (useful)*/
10859:
10860:
10861: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
10862: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
10863: prlim=matrix(1,nlstate,1,nlstate);
10864: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
10865: fclose(ficrespl);
10866:
10867: /*------------- h Pij x at various ages ------------*/
10868: /*#include "hpijx.h"*/
10869: hPijx(p, bage, fage);
10870: fclose(ficrespij);
10871:
10872: /* ncovcombmax= pow(2,cptcoveff); */
10873: /*-------------- Variance of one-step probabilities---*/
10874: k=1;
10875: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
10876:
10877: /* Prevalence for each covariates in probs[age][status][cov] */
10878: probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10879: for(i=1;i<=AGESUP;i++)
10880: for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
10881: for(k=1;k<=ncovcombmax;k++)
10882: probs[i][j][k]=0.;
10883: prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
10884: if (mobilav!=0 ||mobilavproj !=0 ) {
10885: mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10886: for(i=1;i<=AGESUP;i++)
10887: for(j=1;j<=nlstate;j++)
10888: for(k=1;k<=ncovcombmax;k++)
10889: mobaverages[i][j][k]=0.;
10890: mobaverage=mobaverages;
10891: if (mobilav!=0) {
10892: printf("Movingaveraging observed prevalence\n");
10893: if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
10894: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
10895: printf(" Error in movingaverage mobilav=%d\n",mobilav);
10896: }
10897: }
10898: /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
10899: /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10900: else if (mobilavproj !=0) {
10901: printf("Movingaveraging projected observed prevalence\n");
10902: if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
10903: fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
10904: printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
10905: }
10906: }
10907: }/* end if moving average */
10908:
10909: /*---------- Forecasting ------------------*/
10910: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
10911: if(prevfcast==1){
10912: /* if(stepm ==1){*/
10913: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
10914: }
10915: if(backcast==1){
10916: ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
10917: ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
10918: ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
10919:
10920: /*--------------- Back Prevalence limit (period or stable prevalence) --------------*/
10921:
10922: bprlim=matrix(1,nlstate,1,nlstate);
10923: back_prevalence_limit(p, bprlim, ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
10924: fclose(ficresplb);
10925:
10926: hBijx(p, bage, fage, mobaverage);
10927: fclose(ficrespijb);
10928: free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
10929:
10930: /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
10931: bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
10932: free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10933: free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10934: free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10935: }
10936:
10937:
10938: /* ------ Other prevalence ratios------------ */
10939:
10940: free_ivector(wav,1,imx);
10941: free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
10942: free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
10943: free_imatrix(mw,1,lastpass-firstpass+2,1,imx);
10944:
10945:
10946: /*---------- Health expectancies, no variances ------------*/
10947:
10948: strcpy(filerese,"E_");
10949: strcat(filerese,fileresu);
10950: if((ficreseij=fopen(filerese,"w"))==NULL) {
10951: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
10952: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
10953: }
10954: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
10955: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
10956:
10957: i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
10958: if (cptcovn < 1){i1=1;}
10959:
10960: for(nres=1; nres <= nresult; nres++) /* For each resultline */
10961: for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
10962: if(TKresult[nres]!= k)
10963: continue;
10964: fprintf(ficreseij,"\n#****** ");
10965: printf("\n#****** ");
10966: for(j=1;j<=cptcoveff;j++) {
10967: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10968: printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10969: }
10970: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
10971: printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
10972: fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
10973: }
10974: fprintf(ficreseij,"******\n");
10975: printf("******\n");
10976:
10977: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10978: oldm=oldms;savm=savms;
10979: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);
10980:
10981: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10982: }
10983: fclose(ficreseij);
10984: printf("done evsij\n");fflush(stdout);
10985: fprintf(ficlog,"done evsij\n");fflush(ficlog);
10986:
10987: /*---------- State-specific expectancies and variances ------------*/
10988:
10989:
10990: strcpy(filerest,"T_");
10991: strcat(filerest,fileresu);
10992: if((ficrest=fopen(filerest,"w"))==NULL) {
10993: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
10994: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
10995: }
10996: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
10997: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
10998:
10999:
11000: strcpy(fileresstde,"STDE_");
11001: strcat(fileresstde,fileresu);
11002: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
11003: printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11004: fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11005: }
11006: printf(" Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11007: fprintf(ficlog," Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11008:
11009: strcpy(filerescve,"CVE_");
11010: strcat(filerescve,fileresu);
11011: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
11012: printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11013: fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11014: }
11015: printf(" Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11016: fprintf(ficlog," Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11017:
11018: strcpy(fileresv,"V_");
11019: strcat(fileresv,fileresu);
11020: if((ficresvij=fopen(fileresv,"w"))==NULL) {
11021: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
11022: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
11023: }
11024: printf(" Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
11025: fprintf(ficlog," Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
11026:
11027: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11028: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11029:
11030: i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
11031: if (cptcovn < 1){i1=1;}
11032:
11033: for(nres=1; nres <= nresult; nres++) /* For each resultline */
11034: for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
11035: if(TKresult[nres]!= k)
11036: continue;
11037: printf("\n#****** Selected:");
11038: fprintf(ficrest,"\n#****** Selected:");
11039: fprintf(ficlog,"\n#****** Selected:");
11040: for(j=1;j<=cptcoveff;j++){
11041: printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11042: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11043: fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11044: }
11045: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11046: printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11047: fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11048: fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11049: }
11050: fprintf(ficrest,"******\n");
11051: fprintf(ficlog,"******\n");
11052: printf("******\n");
11053:
11054: fprintf(ficresstdeij,"\n#****** ");
11055: fprintf(ficrescveij,"\n#****** ");
11056: for(j=1;j<=cptcoveff;j++) {
11057: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11058: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11059: }
11060: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11061: fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11062: fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11063: }
11064: fprintf(ficresstdeij,"******\n");
11065: fprintf(ficrescveij,"******\n");
11066:
11067: fprintf(ficresvij,"\n#****** ");
11068: for(j=1;j<=cptcoveff;j++)
11069: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11070: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11071: fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11072: }
11073: fprintf(ficresvij,"******\n");
11074:
11075: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11076: oldm=oldms;savm=savms;
11077: printf(" cvevsij ");
11078: fprintf(ficlog, " cvevsij ");
11079: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
11080: printf(" end cvevsij \n ");
11081: fprintf(ficlog, " end cvevsij \n ");
11082:
11083: /*
11084: */
11085: /* goto endfree; */
11086:
11087: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11088: pstamp(ficrest);
11089:
11090:
11091: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
11092: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
11093: cptcod= 0; /* To be deleted */
11094: printf("varevsij vpopbased=%d \n",vpopbased);
11095: fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
11096: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
11097: 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 ");
11098: if(vpopbased==1)
11099: 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);
11100: else
11101: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
11102: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
11103: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
11104: fprintf(ficrest,"\n");
11105: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
11106: epj=vector(1,nlstate+1);
11107: printf("Computing age specific period (stable) prevalences in each health state \n");
11108: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
11109: for(age=bage; age <=fage ;age++){
11110: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
11111: if (vpopbased==1) {
11112: if(mobilav ==0){
11113: for(i=1; i<=nlstate;i++)
11114: prlim[i][i]=probs[(int)age][i][k];
11115: }else{ /* mobilav */
11116: for(i=1; i<=nlstate;i++)
11117: prlim[i][i]=mobaverage[(int)age][i][k];
11118: }
11119: }
11120:
11121: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
11122: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
11123: /* printf(" age %4.0f ",age); */
11124: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
11125: for(i=1, epj[j]=0.;i <=nlstate;i++) {
11126: epj[j] += prlim[i][i]*eij[i][j][(int)age];
11127: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
11128: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
11129: }
11130: epj[nlstate+1] +=epj[j];
11131: }
11132: /* printf(" age %4.0f \n",age); */
11133:
11134: for(i=1, vepp=0.;i <=nlstate;i++)
11135: for(j=1;j <=nlstate;j++)
11136: vepp += vareij[i][j][(int)age];
11137: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
11138: for(j=1;j <=nlstate;j++){
11139: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
11140: }
11141: fprintf(ficrest,"\n");
11142: }
11143: } /* End vpopbased */
11144: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11145: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11146: free_vector(epj,1,nlstate+1);
11147: printf("done selection\n");fflush(stdout);
11148: fprintf(ficlog,"done selection\n");fflush(ficlog);
11149:
11150: /*}*/
11151: } /* End k selection */
11152:
11153: printf("done State-specific expectancies\n");fflush(stdout);
11154: fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
11155:
11156: /*------- Variance of period (stable) prevalence------*/
11157:
11158: strcpy(fileresvpl,"VPL_");
11159: strcat(fileresvpl,fileresu);
11160: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
11161: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
11162: exit(0);
11163: }
11164: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
11165: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
11166:
11167: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11168: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11169:
11170: i1=pow(2,cptcoveff);
11171: if (cptcovn < 1){i1=1;}
11172:
11173: for(nres=1; nres <= nresult; nres++) /* For each resultline */
11174: for(k=1; k<=i1;k++){
11175: if(TKresult[nres]!= k)
11176: continue;
11177: fprintf(ficresvpl,"\n#****** ");
11178: printf("\n#****** ");
11179: fprintf(ficlog,"\n#****** ");
11180: for(j=1;j<=cptcoveff;j++) {
11181: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11182: fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11183: printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11184: }
11185: for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11186: printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11187: fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11188: fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11189: }
11190: fprintf(ficresvpl,"******\n");
11191: printf("******\n");
11192: fprintf(ficlog,"******\n");
11193:
11194: varpl=matrix(1,nlstate,(int) bage, (int) fage);
11195: oldm=oldms;savm=savms;
11196: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
11197: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
11198: /*}*/
11199: }
11200:
11201: fclose(ficresvpl);
11202: printf("done variance-covariance of period prevalence\n");fflush(stdout);
11203: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
11204:
11205: free_vector(weight,1,n);
11206: free_imatrix(Tvard,1,NCOVMAX,1,2);
11207: free_imatrix(s,1,maxwav+1,1,n);
11208: free_matrix(anint,1,maxwav,1,n);
11209: free_matrix(mint,1,maxwav,1,n);
11210: free_ivector(cod,1,n);
11211: free_ivector(tab,1,NCOVMAX);
11212: fclose(ficresstdeij);
11213: fclose(ficrescveij);
11214: fclose(ficresvij);
11215: fclose(ficrest);
11216: fclose(ficpar);
11217:
11218:
11219: /*---------- End : free ----------------*/
11220: if (mobilav!=0 ||mobilavproj !=0)
11221: free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
11222: free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
11223: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
11224: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
11225: } /* mle==-3 arrives here for freeing */
11226: /* endfree:*/
11227: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
11228: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
11229: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
11230: free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
11231: free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
11232: free_matrix(coqvar,1,maxwav,1,n);
11233: free_matrix(covar,0,NCOVMAX,1,n);
11234: free_matrix(matcov,1,npar,1,npar);
11235: free_matrix(hess,1,npar,1,npar);
11236: /*free_vector(delti,1,npar);*/
11237: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
11238: free_matrix(agev,1,maxwav,1,imx);
11239: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
11240:
11241: free_ivector(ncodemax,1,NCOVMAX);
11242: free_ivector(ncodemaxwundef,1,NCOVMAX);
11243: free_ivector(Dummy,-1,NCOVMAX);
11244: free_ivector(Fixed,-1,NCOVMAX);
11245: free_ivector(Typevar,-1,NCOVMAX);
11246: free_ivector(Tvar,1,NCOVMAX);
11247: free_ivector(TvarsQ,1,NCOVMAX);
11248: free_ivector(TvarsQind,1,NCOVMAX);
11249: free_ivector(TvarsD,1,NCOVMAX);
11250: free_ivector(TvarsDind,1,NCOVMAX);
11251: free_ivector(TvarFD,1,NCOVMAX);
11252: free_ivector(TvarFDind,1,NCOVMAX);
11253: free_ivector(TvarF,1,NCOVMAX);
11254: free_ivector(TvarFind,1,NCOVMAX);
11255: free_ivector(TvarV,1,NCOVMAX);
11256: free_ivector(TvarVind,1,NCOVMAX);
11257: free_ivector(TvarA,1,NCOVMAX);
11258: free_ivector(TvarAind,1,NCOVMAX);
11259: free_ivector(TvarFQ,1,NCOVMAX);
11260: free_ivector(TvarFQind,1,NCOVMAX);
11261: free_ivector(TvarVD,1,NCOVMAX);
11262: free_ivector(TvarVDind,1,NCOVMAX);
11263: free_ivector(TvarVQ,1,NCOVMAX);
11264: free_ivector(TvarVQind,1,NCOVMAX);
11265: free_ivector(Tvarsel,1,NCOVMAX);
11266: free_vector(Tvalsel,1,NCOVMAX);
11267: free_ivector(Tposprod,1,NCOVMAX);
11268: free_ivector(Tprod,1,NCOVMAX);
11269: free_ivector(Tvaraff,1,NCOVMAX);
11270: free_ivector(invalidvarcomb,1,ncovcombmax);
11271: free_ivector(Tage,1,NCOVMAX);
11272: free_ivector(Tmodelind,1,NCOVMAX);
11273: free_ivector(TmodelInvind,1,NCOVMAX);
11274: free_ivector(TmodelInvQind,1,NCOVMAX);
11275:
11276: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
11277: /* free_imatrix(codtab,1,100,1,10); */
11278: fflush(fichtm);
11279: fflush(ficgp);
11280:
11281:
11282: if((nberr >0) || (nbwarn>0)){
11283: printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
11284: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
11285: }else{
11286: printf("End of Imach\n");
11287: fprintf(ficlog,"End of Imach\n");
11288: }
11289: printf("See log file on %s\n",filelog);
11290: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
11291: /*(void) gettimeofday(&end_time,&tzp);*/
11292: rend_time = time(NULL);
11293: end_time = *localtime(&rend_time);
11294: /* tml = *localtime(&end_time.tm_sec); */
11295: strcpy(strtend,asctime(&end_time));
11296: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
11297: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
11298: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11299:
11300: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11301: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11302: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11303: /* printf("Total time was %d uSec.\n", total_usecs);*/
11304: /* if(fileappend(fichtm,optionfilehtm)){ */
11305: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
11306: fclose(fichtm);
11307: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
11308: fclose(fichtmcov);
11309: fclose(ficgp);
11310: fclose(ficlog);
11311: /*------ End -----------*/
11312:
11313:
11314: printf("Before Current directory %s!\n",pathcd);
11315: #ifdef WIN32
11316: if (_chdir(pathcd) != 0)
11317: printf("Can't move to directory %s!\n",path);
11318: if(_getcwd(pathcd,MAXLINE) > 0)
11319: #else
11320: if(chdir(pathcd) != 0)
11321: printf("Can't move to directory %s!\n", path);
11322: if (getcwd(pathcd, MAXLINE) > 0)
11323: #endif
11324: printf("Current directory %s!\n",pathcd);
11325: /*strcat(plotcmd,CHARSEPARATOR);*/
11326: sprintf(plotcmd,"gnuplot");
11327: #ifdef _WIN32
11328: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
11329: #endif
11330: if(!stat(plotcmd,&info)){
11331: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11332: if(!stat(getenv("GNUPLOTBIN"),&info)){
11333: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
11334: }else
11335: strcpy(pplotcmd,plotcmd);
11336: #ifdef __unix
11337: strcpy(plotcmd,GNUPLOTPROGRAM);
11338: if(!stat(plotcmd,&info)){
11339: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11340: }else
11341: strcpy(pplotcmd,plotcmd);
11342: #endif
11343: }else
11344: strcpy(pplotcmd,plotcmd);
11345:
11346: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
11347: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
11348:
11349: if((outcmd=system(plotcmd)) != 0){
11350: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
11351: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
11352: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
11353: if((outcmd=system(plotcmd)) != 0)
11354: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
11355: }
11356: printf(" Successful, please wait...");
11357: while (z[0] != 'q') {
11358: /* chdir(path); */
11359: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
11360: scanf("%s",z);
11361: /* if (z[0] == 'c') system("./imach"); */
11362: if (z[0] == 'e') {
11363: #ifdef __APPLE__
11364: sprintf(pplotcmd, "open %s", optionfilehtm);
11365: #elif __linux
11366: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
11367: #else
11368: sprintf(pplotcmd, "%s", optionfilehtm);
11369: #endif
11370: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
11371: system(pplotcmd);
11372: }
11373: else if (z[0] == 'g') system(plotcmd);
11374: else if (z[0] == 'q') exit(0);
11375: }
11376: end:
11377: while (z[0] != 'q') {
11378: printf("\nType q for exiting: "); fflush(stdout);
11379: scanf("%s",z);
11380: }
11381: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>