1: /* $Id: imach.c,v 1.219 2016/02/15 00:48:12 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.219 2016/02/15 00:48:12 brouard
5: *** empty log message ***
6:
7: Revision 1.218 2016/02/12 11:29:23 brouard
8: Summary: 0.99 Back projections
9:
10: Revision 1.217 2015/12/23 17:18:31 brouard
11: Summary: Experimental backcast
12:
13: Revision 1.216 2015/12/18 17:32:11 brouard
14: Summary: 0.98r4 Warning and status=-2
15:
16: Version 0.98r4 is now:
17: - displaying an error when status is -1, date of interview unknown and date of death known;
18: - permitting a status -2 when the vital status is unknown at a known date of right truncation.
19: Older changes concerning s=-2, dating from 2005 have been supersed.
20:
21: Revision 1.215 2015/12/16 08:52:24 brouard
22: Summary: 0.98r4 working
23:
24: Revision 1.214 2015/12/16 06:57:54 brouard
25: Summary: temporary not working
26:
27: Revision 1.213 2015/12/11 18:22:17 brouard
28: Summary: 0.98r4
29:
30: Revision 1.212 2015/11/21 12:47:24 brouard
31: Summary: minor typo
32:
33: Revision 1.211 2015/11/21 12:41:11 brouard
34: Summary: 0.98r3 with some graph of projected cross-sectional
35:
36: Author: Nicolas Brouard
37:
38: Revision 1.210 2015/11/18 17:41:20 brouard
39: Summary: Start working on projected prevalences
40:
41: Revision 1.209 2015/11/17 22:12:03 brouard
42: Summary: Adding ftolpl parameter
43: Author: N Brouard
44:
45: We had difficulties to get smoothed confidence intervals. It was due
46: to the period prevalence which wasn't computed accurately. The inner
47: parameter ftolpl is now an outer parameter of the .imach parameter
48: file after estepm. If ftolpl is small 1.e-4 and estepm too,
49: computation are long.
50:
51: Revision 1.208 2015/11/17 14:31:57 brouard
52: Summary: temporary
53:
54: Revision 1.207 2015/10/27 17:36:57 brouard
55: *** empty log message ***
56:
57: Revision 1.206 2015/10/24 07:14:11 brouard
58: *** empty log message ***
59:
60: Revision 1.205 2015/10/23 15:50:53 brouard
61: Summary: 0.98r3 some clarification for graphs on likelihood contributions
62:
63: Revision 1.204 2015/10/01 16:20:26 brouard
64: Summary: Some new graphs of contribution to likelihood
65:
66: Revision 1.203 2015/09/30 17:45:14 brouard
67: Summary: looking at better estimation of the hessian
68:
69: Also a better criteria for convergence to the period prevalence And
70: therefore adding the number of years needed to converge. (The
71: prevalence in any alive state shold sum to one
72:
73: Revision 1.202 2015/09/22 19:45:16 brouard
74: Summary: Adding some overall graph on contribution to likelihood. Might change
75:
76: Revision 1.201 2015/09/15 17:34:58 brouard
77: Summary: 0.98r0
78:
79: - Some new graphs like suvival functions
80: - Some bugs fixed like model=1+age+V2.
81:
82: Revision 1.200 2015/09/09 16:53:55 brouard
83: Summary: Big bug thanks to Flavia
84:
85: Even model=1+age+V2. did not work anymore
86:
87: Revision 1.199 2015/09/07 14:09:23 brouard
88: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
89:
90: Revision 1.198 2015/09/03 07:14:39 brouard
91: Summary: 0.98q5 Flavia
92:
93: Revision 1.197 2015/09/01 18:24:39 brouard
94: *** empty log message ***
95:
96: Revision 1.196 2015/08/18 23:17:52 brouard
97: Summary: 0.98q5
98:
99: Revision 1.195 2015/08/18 16:28:39 brouard
100: Summary: Adding a hack for testing purpose
101:
102: After reading the title, ftol and model lines, if the comment line has
103: a q, starting with #q, the answer at the end of the run is quit. It
104: permits to run test files in batch with ctest. The former workaround was
105: $ echo q | imach foo.imach
106:
107: Revision 1.194 2015/08/18 13:32:00 brouard
108: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
109:
110: Revision 1.193 2015/08/04 07:17:42 brouard
111: Summary: 0.98q4
112:
113: Revision 1.192 2015/07/16 16:49:02 brouard
114: Summary: Fixing some outputs
115:
116: Revision 1.191 2015/07/14 10:00:33 brouard
117: Summary: Some fixes
118:
119: Revision 1.190 2015/05/05 08:51:13 brouard
120: Summary: Adding digits in output parameters (7 digits instead of 6)
121:
122: Fix 1+age+.
123:
124: Revision 1.189 2015/04/30 14:45:16 brouard
125: Summary: 0.98q2
126:
127: Revision 1.188 2015/04/30 08:27:53 brouard
128: *** empty log message ***
129:
130: Revision 1.187 2015/04/29 09:11:15 brouard
131: *** empty log message ***
132:
133: Revision 1.186 2015/04/23 12:01:52 brouard
134: Summary: V1*age is working now, version 0.98q1
135:
136: Some codes had been disabled in order to simplify and Vn*age was
137: working in the optimization phase, ie, giving correct MLE parameters,
138: but, as usual, outputs were not correct and program core dumped.
139:
140: Revision 1.185 2015/03/11 13:26:42 brouard
141: Summary: Inclusion of compile and links command line for Intel Compiler
142:
143: Revision 1.184 2015/03/11 11:52:39 brouard
144: Summary: Back from Windows 8. Intel Compiler
145:
146: Revision 1.183 2015/03/10 20:34:32 brouard
147: Summary: 0.98q0, trying with directest, mnbrak fixed
148:
149: We use directest instead of original Powell test; probably no
150: incidence on the results, but better justifications;
151: We fixed Numerical Recipes mnbrak routine which was wrong and gave
152: wrong results.
153:
154: Revision 1.182 2015/02/12 08:19:57 brouard
155: Summary: Trying to keep directest which seems simpler and more general
156: Author: Nicolas Brouard
157:
158: Revision 1.181 2015/02/11 23:22:24 brouard
159: Summary: Comments on Powell added
160:
161: Author:
162:
163: Revision 1.180 2015/02/11 17:33:45 brouard
164: Summary: Finishing move from main to function (hpijx and prevalence_limit)
165:
166: Revision 1.179 2015/01/04 09:57:06 brouard
167: Summary: back to OS/X
168:
169: Revision 1.178 2015/01/04 09:35:48 brouard
170: *** empty log message ***
171:
172: Revision 1.177 2015/01/03 18:40:56 brouard
173: Summary: Still testing ilc32 on OSX
174:
175: Revision 1.176 2015/01/03 16:45:04 brouard
176: *** empty log message ***
177:
178: Revision 1.175 2015/01/03 16:33:42 brouard
179: *** empty log message ***
180:
181: Revision 1.174 2015/01/03 16:15:49 brouard
182: Summary: Still in cross-compilation
183:
184: Revision 1.173 2015/01/03 12:06:26 brouard
185: Summary: trying to detect cross-compilation
186:
187: Revision 1.172 2014/12/27 12:07:47 brouard
188: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
189:
190: Revision 1.171 2014/12/23 13:26:59 brouard
191: Summary: Back from Visual C
192:
193: Still problem with utsname.h on Windows
194:
195: Revision 1.170 2014/12/23 11:17:12 brouard
196: Summary: Cleaning some \%% back to %%
197:
198: The escape was mandatory for a specific compiler (which one?), but too many warnings.
199:
200: Revision 1.169 2014/12/22 23:08:31 brouard
201: Summary: 0.98p
202:
203: Outputs some informations on compiler used, OS etc. Testing on different platforms.
204:
205: Revision 1.168 2014/12/22 15:17:42 brouard
206: Summary: update
207:
208: Revision 1.167 2014/12/22 13:50:56 brouard
209: Summary: Testing uname and compiler version and if compiled 32 or 64
210:
211: Testing on Linux 64
212:
213: Revision 1.166 2014/12/22 11:40:47 brouard
214: *** empty log message ***
215:
216: Revision 1.165 2014/12/16 11:20:36 brouard
217: Summary: After compiling on Visual C
218:
219: * imach.c (Module): Merging 1.61 to 1.162
220:
221: Revision 1.164 2014/12/16 10:52:11 brouard
222: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
223:
224: * imach.c (Module): Merging 1.61 to 1.162
225:
226: Revision 1.163 2014/12/16 10:30:11 brouard
227: * imach.c (Module): Merging 1.61 to 1.162
228:
229: Revision 1.162 2014/09/25 11:43:39 brouard
230: Summary: temporary backup 0.99!
231:
232: Revision 1.1 2014/09/16 11:06:58 brouard
233: Summary: With some code (wrong) for nlopt
234:
235: Author:
236:
237: Revision 1.161 2014/09/15 20:41:41 brouard
238: Summary: Problem with macro SQR on Intel compiler
239:
240: Revision 1.160 2014/09/02 09:24:05 brouard
241: *** empty log message ***
242:
243: Revision 1.159 2014/09/01 10:34:10 brouard
244: Summary: WIN32
245: Author: Brouard
246:
247: Revision 1.158 2014/08/27 17:11:51 brouard
248: *** empty log message ***
249:
250: Revision 1.157 2014/08/27 16:26:55 brouard
251: Summary: Preparing windows Visual studio version
252: Author: Brouard
253:
254: In order to compile on Visual studio, time.h is now correct and time_t
255: and tm struct should be used. difftime should be used but sometimes I
256: just make the differences in raw time format (time(&now).
257: Trying to suppress #ifdef LINUX
258: Add xdg-open for __linux in order to open default browser.
259:
260: Revision 1.156 2014/08/25 20:10:10 brouard
261: *** empty log message ***
262:
263: Revision 1.155 2014/08/25 18:32:34 brouard
264: Summary: New compile, minor changes
265: Author: Brouard
266:
267: Revision 1.154 2014/06/20 17:32:08 brouard
268: Summary: Outputs now all graphs of convergence to period prevalence
269:
270: Revision 1.153 2014/06/20 16:45:46 brouard
271: Summary: If 3 live state, convergence to period prevalence on same graph
272: Author: Brouard
273:
274: Revision 1.152 2014/06/18 17:54:09 brouard
275: Summary: open browser, use gnuplot on same dir than imach if not found in the path
276:
277: Revision 1.151 2014/06/18 16:43:30 brouard
278: *** empty log message ***
279:
280: Revision 1.150 2014/06/18 16:42:35 brouard
281: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
282: Author: brouard
283:
284: Revision 1.149 2014/06/18 15:51:14 brouard
285: Summary: Some fixes in parameter files errors
286: Author: Nicolas Brouard
287:
288: Revision 1.148 2014/06/17 17:38:48 brouard
289: Summary: Nothing new
290: Author: Brouard
291:
292: Just a new packaging for OS/X version 0.98nS
293:
294: Revision 1.147 2014/06/16 10:33:11 brouard
295: *** empty log message ***
296:
297: Revision 1.146 2014/06/16 10:20:28 brouard
298: Summary: Merge
299: Author: Brouard
300:
301: Merge, before building revised version.
302:
303: Revision 1.145 2014/06/10 21:23:15 brouard
304: Summary: Debugging with valgrind
305: Author: Nicolas Brouard
306:
307: Lot of changes in order to output the results with some covariates
308: After the Edimburgh REVES conference 2014, it seems mandatory to
309: improve the code.
310: No more memory valgrind error but a lot has to be done in order to
311: continue the work of splitting the code into subroutines.
312: Also, decodemodel has been improved. Tricode is still not
313: optimal. nbcode should be improved. Documentation has been added in
314: the source code.
315:
316: Revision 1.143 2014/01/26 09:45:38 brouard
317: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
318:
319: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
320: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
321:
322: Revision 1.142 2014/01/26 03:57:36 brouard
323: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
324:
325: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
326:
327: Revision 1.141 2014/01/26 02:42:01 brouard
328: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
329:
330: Revision 1.140 2011/09/02 10:37:54 brouard
331: Summary: times.h is ok with mingw32 now.
332:
333: Revision 1.139 2010/06/14 07:50:17 brouard
334: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
335: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
336:
337: Revision 1.138 2010/04/30 18:19:40 brouard
338: *** empty log message ***
339:
340: Revision 1.137 2010/04/29 18:11:38 brouard
341: (Module): Checking covariates for more complex models
342: than V1+V2. A lot of change to be done. Unstable.
343:
344: Revision 1.136 2010/04/26 20:30:53 brouard
345: (Module): merging some libgsl code. Fixing computation
346: of likelione (using inter/intrapolation if mle = 0) in order to
347: get same likelihood as if mle=1.
348: Some cleaning of code and comments added.
349:
350: Revision 1.135 2009/10/29 15:33:14 brouard
351: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
352:
353: Revision 1.134 2009/10/29 13:18:53 brouard
354: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
355:
356: Revision 1.133 2009/07/06 10:21:25 brouard
357: just nforces
358:
359: Revision 1.132 2009/07/06 08:22:05 brouard
360: Many tings
361:
362: Revision 1.131 2009/06/20 16:22:47 brouard
363: Some dimensions resccaled
364:
365: Revision 1.130 2009/05/26 06:44:34 brouard
366: (Module): Max Covariate is now set to 20 instead of 8. A
367: lot of cleaning with variables initialized to 0. Trying to make
368: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
369:
370: Revision 1.129 2007/08/31 13:49:27 lievre
371: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
372:
373: Revision 1.128 2006/06/30 13:02:05 brouard
374: (Module): Clarifications on computing e.j
375:
376: Revision 1.127 2006/04/28 18:11:50 brouard
377: (Module): Yes the sum of survivors was wrong since
378: imach-114 because nhstepm was no more computed in the age
379: loop. Now we define nhstepma in the age loop.
380: (Module): In order to speed up (in case of numerous covariates) we
381: compute health expectancies (without variances) in a first step
382: and then all the health expectancies with variances or standard
383: deviation (needs data from the Hessian matrices) which slows the
384: computation.
385: In the future we should be able to stop the program is only health
386: expectancies and graph are needed without standard deviations.
387:
388: Revision 1.126 2006/04/28 17:23:28 brouard
389: (Module): Yes the sum of survivors was wrong since
390: imach-114 because nhstepm was no more computed in the age
391: loop. Now we define nhstepma in the age loop.
392: Version 0.98h
393:
394: Revision 1.125 2006/04/04 15:20:31 lievre
395: Errors in calculation of health expectancies. Age was not initialized.
396: Forecasting file added.
397:
398: Revision 1.124 2006/03/22 17:13:53 lievre
399: Parameters are printed with %lf instead of %f (more numbers after the comma).
400: The log-likelihood is printed in the log file
401:
402: Revision 1.123 2006/03/20 10:52:43 brouard
403: * imach.c (Module): <title> changed, corresponds to .htm file
404: name. <head> headers where missing.
405:
406: * imach.c (Module): Weights can have a decimal point as for
407: English (a comma might work with a correct LC_NUMERIC environment,
408: otherwise the weight is truncated).
409: Modification of warning when the covariates values are not 0 or
410: 1.
411: Version 0.98g
412:
413: Revision 1.122 2006/03/20 09:45:41 brouard
414: (Module): Weights can have a decimal point as for
415: English (a comma might work with a correct LC_NUMERIC environment,
416: otherwise the weight is truncated).
417: Modification of warning when the covariates values are not 0 or
418: 1.
419: Version 0.98g
420:
421: Revision 1.121 2006/03/16 17:45:01 lievre
422: * imach.c (Module): Comments concerning covariates added
423:
424: * imach.c (Module): refinements in the computation of lli if
425: status=-2 in order to have more reliable computation if stepm is
426: not 1 month. Version 0.98f
427:
428: Revision 1.120 2006/03/16 15:10:38 lievre
429: (Module): refinements in the computation of lli if
430: status=-2 in order to have more reliable computation if stepm is
431: not 1 month. Version 0.98f
432:
433: Revision 1.119 2006/03/15 17:42:26 brouard
434: (Module): Bug if status = -2, the loglikelihood was
435: computed as likelihood omitting the logarithm. Version O.98e
436:
437: Revision 1.118 2006/03/14 18:20:07 brouard
438: (Module): varevsij Comments added explaining the second
439: table of variances if popbased=1 .
440: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
441: (Module): Function pstamp added
442: (Module): Version 0.98d
443:
444: Revision 1.117 2006/03/14 17:16:22 brouard
445: (Module): varevsij Comments added explaining the second
446: table of variances if popbased=1 .
447: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
448: (Module): Function pstamp added
449: (Module): Version 0.98d
450:
451: Revision 1.116 2006/03/06 10:29:27 brouard
452: (Module): Variance-covariance wrong links and
453: varian-covariance of ej. is needed (Saito).
454:
455: Revision 1.115 2006/02/27 12:17:45 brouard
456: (Module): One freematrix added in mlikeli! 0.98c
457:
458: Revision 1.114 2006/02/26 12:57:58 brouard
459: (Module): Some improvements in processing parameter
460: filename with strsep.
461:
462: Revision 1.113 2006/02/24 14:20:24 brouard
463: (Module): Memory leaks checks with valgrind and:
464: datafile was not closed, some imatrix were not freed and on matrix
465: allocation too.
466:
467: Revision 1.112 2006/01/30 09:55:26 brouard
468: (Module): Back to gnuplot.exe instead of wgnuplot.exe
469:
470: Revision 1.111 2006/01/25 20:38:18 brouard
471: (Module): Lots of cleaning and bugs added (Gompertz)
472: (Module): Comments can be added in data file. Missing date values
473: can be a simple dot '.'.
474:
475: Revision 1.110 2006/01/25 00:51:50 brouard
476: (Module): Lots of cleaning and bugs added (Gompertz)
477:
478: Revision 1.109 2006/01/24 19:37:15 brouard
479: (Module): Comments (lines starting with a #) are allowed in data.
480:
481: Revision 1.108 2006/01/19 18:05:42 lievre
482: Gnuplot problem appeared...
483: To be fixed
484:
485: Revision 1.107 2006/01/19 16:20:37 brouard
486: Test existence of gnuplot in imach path
487:
488: Revision 1.106 2006/01/19 13:24:36 brouard
489: Some cleaning and links added in html output
490:
491: Revision 1.105 2006/01/05 20:23:19 lievre
492: *** empty log message ***
493:
494: Revision 1.104 2005/09/30 16:11:43 lievre
495: (Module): sump fixed, loop imx fixed, and simplifications.
496: (Module): If the status is missing at the last wave but we know
497: that the person is alive, then we can code his/her status as -2
498: (instead of missing=-1 in earlier versions) and his/her
499: contributions to the likelihood is 1 - Prob of dying from last
500: health status (= 1-p13= p11+p12 in the easiest case of somebody in
501: the healthy state at last known wave). Version is 0.98
502:
503: Revision 1.103 2005/09/30 15:54:49 lievre
504: (Module): sump fixed, loop imx fixed, and simplifications.
505:
506: Revision 1.102 2004/09/15 17:31:30 brouard
507: Add the possibility to read data file including tab characters.
508:
509: Revision 1.101 2004/09/15 10:38:38 brouard
510: Fix on curr_time
511:
512: Revision 1.100 2004/07/12 18:29:06 brouard
513: Add version for Mac OS X. Just define UNIX in Makefile
514:
515: Revision 1.99 2004/06/05 08:57:40 brouard
516: *** empty log message ***
517:
518: Revision 1.98 2004/05/16 15:05:56 brouard
519: New version 0.97 . First attempt to estimate force of mortality
520: directly from the data i.e. without the need of knowing the health
521: state at each age, but using a Gompertz model: log u =a + b*age .
522: This is the basic analysis of mortality and should be done before any
523: other analysis, in order to test if the mortality estimated from the
524: cross-longitudinal survey is different from the mortality estimated
525: from other sources like vital statistic data.
526:
527: The same imach parameter file can be used but the option for mle should be -3.
528:
529: Agnès, who wrote this part of the code, tried to keep most of the
530: former routines in order to include the new code within the former code.
531:
532: The output is very simple: only an estimate of the intercept and of
533: the slope with 95% confident intervals.
534:
535: Current limitations:
536: A) Even if you enter covariates, i.e. with the
537: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
538: B) There is no computation of Life Expectancy nor Life Table.
539:
540: Revision 1.97 2004/02/20 13:25:42 lievre
541: Version 0.96d. Population forecasting command line is (temporarily)
542: suppressed.
543:
544: Revision 1.96 2003/07/15 15:38:55 brouard
545: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
546: rewritten within the same printf. Workaround: many printfs.
547:
548: Revision 1.95 2003/07/08 07:54:34 brouard
549: * imach.c (Repository):
550: (Repository): Using imachwizard code to output a more meaningful covariance
551: matrix (cov(a12,c31) instead of numbers.
552:
553: Revision 1.94 2003/06/27 13:00:02 brouard
554: Just cleaning
555:
556: Revision 1.93 2003/06/25 16:33:55 brouard
557: (Module): On windows (cygwin) function asctime_r doesn't
558: exist so I changed back to asctime which exists.
559: (Module): Version 0.96b
560:
561: Revision 1.92 2003/06/25 16:30:45 brouard
562: (Module): On windows (cygwin) function asctime_r doesn't
563: exist so I changed back to asctime which exists.
564:
565: Revision 1.91 2003/06/25 15:30:29 brouard
566: * imach.c (Repository): Duplicated warning errors corrected.
567: (Repository): Elapsed time after each iteration is now output. It
568: helps to forecast when convergence will be reached. Elapsed time
569: is stamped in powell. We created a new html file for the graphs
570: concerning matrix of covariance. It has extension -cov.htm.
571:
572: Revision 1.90 2003/06/24 12:34:15 brouard
573: (Module): Some bugs corrected for windows. Also, when
574: mle=-1 a template is output in file "or"mypar.txt with the design
575: of the covariance matrix to be input.
576:
577: Revision 1.89 2003/06/24 12:30:52 brouard
578: (Module): Some bugs corrected for windows. Also, when
579: mle=-1 a template is output in file "or"mypar.txt with the design
580: of the covariance matrix to be input.
581:
582: Revision 1.88 2003/06/23 17:54:56 brouard
583: * 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.
584:
585: Revision 1.87 2003/06/18 12:26:01 brouard
586: Version 0.96
587:
588: Revision 1.86 2003/06/17 20:04:08 brouard
589: (Module): Change position of html and gnuplot routines and added
590: routine fileappend.
591:
592: Revision 1.85 2003/06/17 13:12:43 brouard
593: * imach.c (Repository): Check when date of death was earlier that
594: current date of interview. It may happen when the death was just
595: prior to the death. In this case, dh was negative and likelihood
596: was wrong (infinity). We still send an "Error" but patch by
597: assuming that the date of death was just one stepm after the
598: interview.
599: (Repository): Because some people have very long ID (first column)
600: we changed int to long in num[] and we added a new lvector for
601: memory allocation. But we also truncated to 8 characters (left
602: truncation)
603: (Repository): No more line truncation errors.
604:
605: Revision 1.84 2003/06/13 21:44:43 brouard
606: * imach.c (Repository): Replace "freqsummary" at a correct
607: place. It differs from routine "prevalence" which may be called
608: many times. Probs is memory consuming and must be used with
609: parcimony.
610: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
611:
612: Revision 1.83 2003/06/10 13:39:11 lievre
613: *** empty log message ***
614:
615: Revision 1.82 2003/06/05 15:57:20 brouard
616: Add log in imach.c and fullversion number is now printed.
617:
618: */
619: /*
620: Interpolated Markov Chain
621:
622: Short summary of the programme:
623:
624: This program computes Healthy Life Expectancies from
625: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
626: first survey ("cross") where individuals from different ages are
627: interviewed on their health status or degree of disability (in the
628: case of a health survey which is our main interest) -2- at least a
629: second wave of interviews ("longitudinal") which measure each change
630: (if any) in individual health status. Health expectancies are
631: computed from the time spent in each health state according to a
632: model. More health states you consider, more time is necessary to reach the
633: Maximum Likelihood of the parameters involved in the model. The
634: simplest model is the multinomial logistic model where pij is the
635: probability to be observed in state j at the second wave
636: conditional to be observed in state i at the first wave. Therefore
637: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
638: 'age' is age and 'sex' is a covariate. If you want to have a more
639: complex model than "constant and age", you should modify the program
640: where the markup *Covariates have to be included here again* invites
641: you to do it. More covariates you add, slower the
642: convergence.
643:
644: The advantage of this computer programme, compared to a simple
645: multinomial logistic model, is clear when the delay between waves is not
646: identical for each individual. Also, if a individual missed an
647: intermediate interview, the information is lost, but taken into
648: account using an interpolation or extrapolation.
649:
650: hPijx is the probability to be observed in state i at age x+h
651: conditional to the observed state i at age x. The delay 'h' can be
652: split into an exact number (nh*stepm) of unobserved intermediate
653: states. This elementary transition (by month, quarter,
654: semester or year) is modelled as a multinomial logistic. The hPx
655: matrix is simply the matrix product of nh*stepm elementary matrices
656: and the contribution of each individual to the likelihood is simply
657: hPijx.
658:
659: Also this programme outputs the covariance matrix of the parameters but also
660: of the life expectancies. It also computes the period (stable) prevalence.
661:
662: Back prevalence and projections:
663: - 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)
664: Computes the back prevalence limit for any combination of covariate values k
665: at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
666: - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
667: - hBijx Back Probability to be in state i at age x-h being in j at x
668: Computes for any combination of covariates k and any age between bage and fage
669: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
670: oldm=oldms;savm=savms;
671: - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
672: Computes the transition matrix starting at age 'age' over
673: 'nhstepm*hstepm*stepm' months (i.e. until
674: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
675: nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling
676: p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
677: 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
678:
679: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
680: Institut national d'études démographiques, Paris.
681: This software have been partly granted by Euro-REVES, a concerted action
682: from the European Union.
683: It is copyrighted identically to a GNU software product, ie programme and
684: software can be distributed freely for non commercial use. Latest version
685: can be accessed at http://euroreves.ined.fr/imach .
686:
687: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
688: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
689:
690: **********************************************************************/
691: /*
692: main
693: read parameterfile
694: read datafile
695: concatwav
696: freqsummary
697: if (mle >= 1)
698: mlikeli
699: print results files
700: if mle==1
701: computes hessian
702: read end of parameter file: agemin, agemax, bage, fage, estepm
703: begin-prev-date,...
704: open gnuplot file
705: open html file
706: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
707: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
708: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
709: freexexit2 possible for memory heap.
710:
711: h Pij x | pij_nom ficrestpij
712: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
713: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
714: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
715:
716: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
717: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
718: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
719: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
720: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
721:
722: forecasting if prevfcast==1 prevforecast call prevalence()
723: health expectancies
724: Variance-covariance of DFLE
725: prevalence()
726: movingaverage()
727: varevsij()
728: if popbased==1 varevsij(,popbased)
729: total life expectancies
730: Variance of period (stable) prevalence
731: end
732: */
733:
734: /* #define DEBUG */
735: /* #define DEBUGBRENT */
736: /* #define DEBUGLINMIN */
737: /* #define DEBUGHESS */
738: #define DEBUGHESSIJ
739: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
740: #define POWELL /* Instead of NLOPT */
741: #define POWELLF1F3 /* Skip test */
742: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
743: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
744:
745: #include <math.h>
746: #include <stdio.h>
747: #include <stdlib.h>
748: #include <string.h>
749:
750: #ifdef _WIN32
751: #include <io.h>
752: #include <windows.h>
753: #include <tchar.h>
754: #else
755: #include <unistd.h>
756: #endif
757:
758: #include <limits.h>
759: #include <sys/types.h>
760:
761: #if defined(__GNUC__)
762: #include <sys/utsname.h> /* Doesn't work on Windows */
763: #endif
764:
765: #include <sys/stat.h>
766: #include <errno.h>
767: /* extern int errno; */
768:
769: /* #ifdef LINUX */
770: /* #include <time.h> */
771: /* #include "timeval.h" */
772: /* #else */
773: /* #include <sys/time.h> */
774: /* #endif */
775:
776: #include <time.h>
777:
778: #ifdef GSL
779: #include <gsl/gsl_errno.h>
780: #include <gsl/gsl_multimin.h>
781: #endif
782:
783:
784: #ifdef NLOPT
785: #include <nlopt.h>
786: typedef struct {
787: double (* function)(double [] );
788: } myfunc_data ;
789: #endif
790:
791: /* #include <libintl.h> */
792: /* #define _(String) gettext (String) */
793:
794: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
795:
796: #define GNUPLOTPROGRAM "gnuplot"
797: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
798: #define FILENAMELENGTH 132
799:
800: #define GLOCK_ERROR_NOPATH -1 /* empty path */
801: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
802:
803: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
804: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
805:
806: #define NINTERVMAX 8
807: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
808: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
809: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
810: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
811: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
812: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
813: #define MAXN 20000
814: #define YEARM 12. /**< Number of months per year */
815: /* #define AGESUP 130 */
816: #define AGESUP 150
817: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
818: #define AGEBASE 40
819: #define AGEOVERFLOW 1.e20
820: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
821: #ifdef _WIN32
822: #define DIRSEPARATOR '\\'
823: #define CHARSEPARATOR "\\"
824: #define ODIRSEPARATOR '/'
825: #else
826: #define DIRSEPARATOR '/'
827: #define CHARSEPARATOR "/"
828: #define ODIRSEPARATOR '\\'
829: #endif
830:
831: /* $Id: imach.c,v 1.219 2016/02/15 00:48:12 brouard Exp $ */
832: /* $State: Exp $ */
833: #include "version.h"
834: char version[]=__IMACH_VERSION__;
835: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
836: char fullversion[]="$Revision: 1.219 $ $Date: 2016/02/15 00:48:12 $";
837: char strstart[80];
838: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
839: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
840: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
841: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
842: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
843: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
844: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
845: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
846: int cptcovprodnoage=0; /**< Number of covariate products without age */
847: int cptcoveff=0; /* Total number of covariates to vary for printing results */
848: int cptcov=0; /* Working variable */
849: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
850: int npar=NPARMAX;
851: int nlstate=2; /* Number of live states */
852: int ndeath=1; /* Number of dead states */
853: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
854: int popbased=0;
855:
856: int *wav; /* Number of waves for this individuual 0 is possible */
857: int maxwav=0; /* Maxim number of waves */
858: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
859: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
860: int gipmx=0, gsw=0; /* Global variables on the number of contributions
861: to the likelihood and the sum of weights (done by funcone)*/
862: int mle=1, weightopt=0;
863: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
864: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
865: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
866: * wave mi and wave mi+1 is not an exact multiple of stepm. */
867: int countcallfunc=0; /* Count the number of calls to func */
868: double jmean=1; /* Mean space between 2 waves */
869: double **matprod2(); /* test */
870: double **oldm, **newm, **savm; /* Working pointers to matrices */
871: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
872: double **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
873:
874: /*FILE *fic ; */ /* Used in readdata only */
875: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
876: FILE *ficlog, *ficrespow;
877: int globpr=0; /* Global variable for printing or not */
878: double fretone; /* Only one call to likelihood */
879: long ipmx=0; /* Number of contributions */
880: double sw; /* Sum of weights */
881: char filerespow[FILENAMELENGTH];
882: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
883: FILE *ficresilk;
884: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
885: FILE *ficresprobmorprev;
886: FILE *fichtm, *fichtmcov; /* Html File */
887: FILE *ficreseij;
888: char filerese[FILENAMELENGTH];
889: FILE *ficresstdeij;
890: char fileresstde[FILENAMELENGTH];
891: FILE *ficrescveij;
892: char filerescve[FILENAMELENGTH];
893: FILE *ficresvij;
894: char fileresv[FILENAMELENGTH];
895: FILE *ficresvpl;
896: char fileresvpl[FILENAMELENGTH];
897: char title[MAXLINE];
898: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH], fileresplb[FILENAMELENGTH];
899: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
900: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
901: char command[FILENAMELENGTH];
902: int outcmd=0;
903:
904: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
905: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
906: char filelog[FILENAMELENGTH]; /* Log file */
907: char filerest[FILENAMELENGTH];
908: char fileregp[FILENAMELENGTH];
909: char popfile[FILENAMELENGTH];
910:
911: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
912:
913: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
914: /* struct timezone tzp; */
915: /* extern int gettimeofday(); */
916: struct tm tml, *gmtime(), *localtime();
917:
918: extern time_t time();
919:
920: struct tm start_time, end_time, curr_time, last_time, forecast_time;
921: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
922: struct tm tm;
923:
924: char strcurr[80], strfor[80];
925:
926: char *endptr;
927: long lval;
928: double dval;
929:
930: #define NR_END 1
931: #define FREE_ARG char*
932: #define FTOL 1.0e-10
933:
934: #define NRANSI
935: #define ITMAX 200
936:
937: #define TOL 2.0e-4
938:
939: #define CGOLD 0.3819660
940: #define ZEPS 1.0e-10
941: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
942:
943: #define GOLD 1.618034
944: #define GLIMIT 100.0
945: #define TINY 1.0e-20
946:
947: static double maxarg1,maxarg2;
948: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
949: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
950:
951: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
952: #define rint(a) floor(a+0.5)
953: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
954: #define mytinydouble 1.0e-16
955: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
956: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
957: /* static double dsqrarg; */
958: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
959: static double sqrarg;
960: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
961: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
962: int agegomp= AGEGOMP;
963:
964: int imx;
965: int stepm=1;
966: /* Stepm, step in month: minimum step interpolation*/
967:
968: int estepm;
969: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
970:
971: int m,nb;
972: long *num;
973: int firstpass=0, lastpass=4,*cod, *cens;
974: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
975: covariate for which somebody answered excluding
976: undefined. Usually 2: 0 and 1. */
977: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
978: covariate for which somebody answered including
979: undefined. Usually 3: -1, 0 and 1. */
980: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
981: double **pmmij, ***probs; /* Global pointer */
982: double ***mobaverage, ***mobaverages; /* New global variable */
983: double *ageexmed,*agecens;
984: double dateintmean=0;
985:
986: double *weight;
987: int **s; /* Status */
988: double *agedc;
989: double **covar; /**< covar[j,i], value of jth covariate for individual i,
990: * covar=matrix(0,NCOVMAX,1,n);
991: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
992: double idx;
993: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
994: int *Tage;
995: int *Ndum; /** Freq of modality (tricode */
996: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
997: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
998: double *lsurv, *lpop, *tpop;
999:
1000: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
1001: double ftolhess; /**< Tolerance for computing hessian */
1002:
1003: /**************** split *************************/
1004: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
1005: {
1006: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
1007: the name of the file (name), its extension only (ext) and its first part of the name (finame)
1008: */
1009: char *ss; /* pointer */
1010: int l1=0, l2=0; /* length counters */
1011:
1012: l1 = strlen(path ); /* length of path */
1013: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
1014: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
1015: if ( ss == NULL ) { /* no directory, so determine current directory */
1016: strcpy( name, path ); /* we got the fullname name because no directory */
1017: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
1018: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
1019: /* get current working directory */
1020: /* extern char* getcwd ( char *buf , int len);*/
1021: #ifdef WIN32
1022: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
1023: #else
1024: if (getcwd(dirc, FILENAME_MAX) == NULL) {
1025: #endif
1026: return( GLOCK_ERROR_GETCWD );
1027: }
1028: /* got dirc from getcwd*/
1029: printf(" DIRC = %s \n",dirc);
1030: } else { /* strip directory from path */
1031: ss++; /* after this, the filename */
1032: l2 = strlen( ss ); /* length of filename */
1033: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
1034: strcpy( name, ss ); /* save file name */
1035: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1036: dirc[l1-l2] = '\0'; /* add zero */
1037: printf(" DIRC2 = %s \n",dirc);
1038: }
1039: /* We add a separator at the end of dirc if not exists */
1040: l1 = strlen( dirc ); /* length of directory */
1041: if( dirc[l1-1] != DIRSEPARATOR ){
1042: dirc[l1] = DIRSEPARATOR;
1043: dirc[l1+1] = 0;
1044: printf(" DIRC3 = %s \n",dirc);
1045: }
1046: ss = strrchr( name, '.' ); /* find last / */
1047: if (ss >0){
1048: ss++;
1049: strcpy(ext,ss); /* save extension */
1050: l1= strlen( name);
1051: l2= strlen(ss)+1;
1052: strncpy( finame, name, l1-l2);
1053: finame[l1-l2]= 0;
1054: }
1055:
1056: return( 0 ); /* we're done */
1057: }
1058:
1059:
1060: /******************************************/
1061:
1062: void replace_back_to_slash(char *s, char*t)
1063: {
1064: int i;
1065: int lg=0;
1066: i=0;
1067: lg=strlen(t);
1068: for(i=0; i<= lg; i++) {
1069: (s[i] = t[i]);
1070: if (t[i]== '\\') s[i]='/';
1071: }
1072: }
1073:
1074: char *trimbb(char *out, char *in)
1075: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1076: char *s;
1077: s=out;
1078: while (*in != '\0'){
1079: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1080: in++;
1081: }
1082: *out++ = *in++;
1083: }
1084: *out='\0';
1085: return s;
1086: }
1087:
1088: /* char *substrchaine(char *out, char *in, char *chain) */
1089: /* { */
1090: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1091: /* char *s, *t; */
1092: /* t=in;s=out; */
1093: /* while ((*in != *chain) && (*in != '\0')){ */
1094: /* *out++ = *in++; */
1095: /* } */
1096:
1097: /* /\* *in matches *chain *\/ */
1098: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1099: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1100: /* } */
1101: /* in--; chain--; */
1102: /* while ( (*in != '\0')){ */
1103: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1104: /* *out++ = *in++; */
1105: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1106: /* } */
1107: /* *out='\0'; */
1108: /* out=s; */
1109: /* return out; */
1110: /* } */
1111: char *substrchaine(char *out, char *in, char *chain)
1112: {
1113: /* Substract chain 'chain' from 'in', return and output 'out' */
1114: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1115:
1116: char *strloc;
1117:
1118: strcpy (out, in);
1119: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1120: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1121: if(strloc != NULL){
1122: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1123: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1124: /* strcpy (strloc, strloc +strlen(chain));*/
1125: }
1126: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1127: return out;
1128: }
1129:
1130:
1131: char *cutl(char *blocc, char *alocc, char *in, char occ)
1132: {
1133: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1134: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1135: gives blocc="abcdef" and alocc="ghi2j".
1136: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1137: */
1138: char *s, *t;
1139: t=in;s=in;
1140: while ((*in != occ) && (*in != '\0')){
1141: *alocc++ = *in++;
1142: }
1143: if( *in == occ){
1144: *(alocc)='\0';
1145: s=++in;
1146: }
1147:
1148: if (s == t) {/* occ not found */
1149: *(alocc-(in-s))='\0';
1150: in=s;
1151: }
1152: while ( *in != '\0'){
1153: *blocc++ = *in++;
1154: }
1155:
1156: *blocc='\0';
1157: return t;
1158: }
1159: char *cutv(char *blocc, char *alocc, char *in, char occ)
1160: {
1161: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1162: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1163: gives blocc="abcdef2ghi" and alocc="j".
1164: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1165: */
1166: char *s, *t;
1167: t=in;s=in;
1168: while (*in != '\0'){
1169: while( *in == occ){
1170: *blocc++ = *in++;
1171: s=in;
1172: }
1173: *blocc++ = *in++;
1174: }
1175: if (s == t) /* occ not found */
1176: *(blocc-(in-s))='\0';
1177: else
1178: *(blocc-(in-s)-1)='\0';
1179: in=s;
1180: while ( *in != '\0'){
1181: *alocc++ = *in++;
1182: }
1183:
1184: *alocc='\0';
1185: return s;
1186: }
1187:
1188: int nbocc(char *s, char occ)
1189: {
1190: int i,j=0;
1191: int lg=20;
1192: i=0;
1193: lg=strlen(s);
1194: for(i=0; i<= lg; i++) {
1195: if (s[i] == occ ) j++;
1196: }
1197: return j;
1198: }
1199:
1200: /* void cutv(char *u,char *v, char*t, char occ) */
1201: /* { */
1202: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1203: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1204: /* gives u="abcdef2ghi" and v="j" *\/ */
1205: /* int i,lg,j,p=0; */
1206: /* i=0; */
1207: /* lg=strlen(t); */
1208: /* for(j=0; j<=lg-1; j++) { */
1209: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1210: /* } */
1211:
1212: /* for(j=0; j<p; j++) { */
1213: /* (u[j] = t[j]); */
1214: /* } */
1215: /* u[p]='\0'; */
1216:
1217: /* for(j=0; j<= lg; j++) { */
1218: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1219: /* } */
1220: /* } */
1221:
1222: #ifdef _WIN32
1223: char * strsep(char **pp, const char *delim)
1224: {
1225: char *p, *q;
1226:
1227: if ((p = *pp) == NULL)
1228: return 0;
1229: if ((q = strpbrk (p, delim)) != NULL)
1230: {
1231: *pp = q + 1;
1232: *q = '\0';
1233: }
1234: else
1235: *pp = 0;
1236: return p;
1237: }
1238: #endif
1239:
1240: /********************** nrerror ********************/
1241:
1242: void nrerror(char error_text[])
1243: {
1244: fprintf(stderr,"ERREUR ...\n");
1245: fprintf(stderr,"%s\n",error_text);
1246: exit(EXIT_FAILURE);
1247: }
1248: /*********************** vector *******************/
1249: double *vector(int nl, int nh)
1250: {
1251: double *v;
1252: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1253: if (!v) nrerror("allocation failure in vector");
1254: return v-nl+NR_END;
1255: }
1256:
1257: /************************ free vector ******************/
1258: void free_vector(double*v, int nl, int nh)
1259: {
1260: free((FREE_ARG)(v+nl-NR_END));
1261: }
1262:
1263: /************************ivector *******************************/
1264: int *ivector(long nl,long nh)
1265: {
1266: int *v;
1267: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1268: if (!v) nrerror("allocation failure in ivector");
1269: return v-nl+NR_END;
1270: }
1271:
1272: /******************free ivector **************************/
1273: void free_ivector(int *v, long nl, long nh)
1274: {
1275: free((FREE_ARG)(v+nl-NR_END));
1276: }
1277:
1278: /************************lvector *******************************/
1279: long *lvector(long nl,long nh)
1280: {
1281: long *v;
1282: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1283: if (!v) nrerror("allocation failure in ivector");
1284: return v-nl+NR_END;
1285: }
1286:
1287: /******************free lvector **************************/
1288: void free_lvector(long *v, long nl, long nh)
1289: {
1290: free((FREE_ARG)(v+nl-NR_END));
1291: }
1292:
1293: /******************* imatrix *******************************/
1294: int **imatrix(long nrl, long nrh, long ncl, long nch)
1295: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1296: {
1297: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1298: int **m;
1299:
1300: /* allocate pointers to rows */
1301: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1302: if (!m) nrerror("allocation failure 1 in matrix()");
1303: m += NR_END;
1304: m -= nrl;
1305:
1306:
1307: /* allocate rows and set pointers to them */
1308: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1309: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1310: m[nrl] += NR_END;
1311: m[nrl] -= ncl;
1312:
1313: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1314:
1315: /* return pointer to array of pointers to rows */
1316: return m;
1317: }
1318:
1319: /****************** free_imatrix *************************/
1320: void free_imatrix(m,nrl,nrh,ncl,nch)
1321: int **m;
1322: long nch,ncl,nrh,nrl;
1323: /* free an int matrix allocated by imatrix() */
1324: {
1325: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1326: free((FREE_ARG) (m+nrl-NR_END));
1327: }
1328:
1329: /******************* matrix *******************************/
1330: double **matrix(long nrl, long nrh, long ncl, long nch)
1331: {
1332: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1333: double **m;
1334:
1335: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1336: if (!m) nrerror("allocation failure 1 in matrix()");
1337: m += NR_END;
1338: m -= nrl;
1339:
1340: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1341: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1342: m[nrl] += NR_END;
1343: m[nrl] -= ncl;
1344:
1345: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1346: return m;
1347: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1348: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1349: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1350: */
1351: }
1352:
1353: /*************************free matrix ************************/
1354: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1355: {
1356: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1357: free((FREE_ARG)(m+nrl-NR_END));
1358: }
1359:
1360: /******************* ma3x *******************************/
1361: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1362: {
1363: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1364: double ***m;
1365:
1366: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1367: if (!m) nrerror("allocation failure 1 in matrix()");
1368: m += NR_END;
1369: m -= nrl;
1370:
1371: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1372: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1373: m[nrl] += NR_END;
1374: m[nrl] -= ncl;
1375:
1376: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1377:
1378: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1379: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1380: m[nrl][ncl] += NR_END;
1381: m[nrl][ncl] -= nll;
1382: for (j=ncl+1; j<=nch; j++)
1383: m[nrl][j]=m[nrl][j-1]+nlay;
1384:
1385: for (i=nrl+1; i<=nrh; i++) {
1386: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1387: for (j=ncl+1; j<=nch; j++)
1388: m[i][j]=m[i][j-1]+nlay;
1389: }
1390: return m;
1391: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1392: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1393: */
1394: }
1395:
1396: /*************************free ma3x ************************/
1397: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1398: {
1399: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1400: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1401: free((FREE_ARG)(m+nrl-NR_END));
1402: }
1403:
1404: /*************** function subdirf ***********/
1405: char *subdirf(char fileres[])
1406: {
1407: /* Caution optionfilefiname is hidden */
1408: strcpy(tmpout,optionfilefiname);
1409: strcat(tmpout,"/"); /* Add to the right */
1410: strcat(tmpout,fileres);
1411: return tmpout;
1412: }
1413:
1414: /*************** function subdirf2 ***********/
1415: char *subdirf2(char fileres[], char *preop)
1416: {
1417:
1418: /* Caution optionfilefiname is hidden */
1419: strcpy(tmpout,optionfilefiname);
1420: strcat(tmpout,"/");
1421: strcat(tmpout,preop);
1422: strcat(tmpout,fileres);
1423: return tmpout;
1424: }
1425:
1426: /*************** function subdirf3 ***********/
1427: char *subdirf3(char fileres[], char *preop, char *preop2)
1428: {
1429:
1430: /* Caution optionfilefiname is hidden */
1431: strcpy(tmpout,optionfilefiname);
1432: strcat(tmpout,"/");
1433: strcat(tmpout,preop);
1434: strcat(tmpout,preop2);
1435: strcat(tmpout,fileres);
1436: return tmpout;
1437: }
1438:
1439: /*************** function subdirfext ***********/
1440: char *subdirfext(char fileres[], char *preop, char *postop)
1441: {
1442:
1443: strcpy(tmpout,preop);
1444: strcat(tmpout,fileres);
1445: strcat(tmpout,postop);
1446: return tmpout;
1447: }
1448:
1449: /*************** function subdirfext3 ***********/
1450: char *subdirfext3(char fileres[], char *preop, char *postop)
1451: {
1452:
1453: /* Caution optionfilefiname is hidden */
1454: strcpy(tmpout,optionfilefiname);
1455: strcat(tmpout,"/");
1456: strcat(tmpout,preop);
1457: strcat(tmpout,fileres);
1458: strcat(tmpout,postop);
1459: return tmpout;
1460: }
1461:
1462: char *asc_diff_time(long time_sec, char ascdiff[])
1463: {
1464: long sec_left, days, hours, minutes;
1465: days = (time_sec) / (60*60*24);
1466: sec_left = (time_sec) % (60*60*24);
1467: hours = (sec_left) / (60*60) ;
1468: sec_left = (sec_left) %(60*60);
1469: minutes = (sec_left) /60;
1470: sec_left = (sec_left) % (60);
1471: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1472: return ascdiff;
1473: }
1474:
1475: /***************** f1dim *************************/
1476: extern int ncom;
1477: extern double *pcom,*xicom;
1478: extern double (*nrfunc)(double []);
1479:
1480: double f1dim(double x)
1481: {
1482: int j;
1483: double f;
1484: double *xt;
1485:
1486: xt=vector(1,ncom);
1487: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1488: f=(*nrfunc)(xt);
1489: free_vector(xt,1,ncom);
1490: return f;
1491: }
1492:
1493: /*****************brent *************************/
1494: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1495: {
1496: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1497: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1498: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1499: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1500: * returned function value.
1501: */
1502: int iter;
1503: double a,b,d,etemp;
1504: double fu=0,fv,fw,fx;
1505: double ftemp=0.;
1506: double p,q,r,tol1,tol2,u,v,w,x,xm;
1507: double e=0.0;
1508:
1509: a=(ax < cx ? ax : cx);
1510: b=(ax > cx ? ax : cx);
1511: x=w=v=bx;
1512: fw=fv=fx=(*f)(x);
1513: for (iter=1;iter<=ITMAX;iter++) {
1514: xm=0.5*(a+b);
1515: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1516: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1517: printf(".");fflush(stdout);
1518: fprintf(ficlog,".");fflush(ficlog);
1519: #ifdef DEBUGBRENT
1520: 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);
1521: 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);
1522: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1523: #endif
1524: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1525: *xmin=x;
1526: return fx;
1527: }
1528: ftemp=fu;
1529: if (fabs(e) > tol1) {
1530: r=(x-w)*(fx-fv);
1531: q=(x-v)*(fx-fw);
1532: p=(x-v)*q-(x-w)*r;
1533: q=2.0*(q-r);
1534: if (q > 0.0) p = -p;
1535: q=fabs(q);
1536: etemp=e;
1537: e=d;
1538: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1539: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1540: else {
1541: d=p/q;
1542: u=x+d;
1543: if (u-a < tol2 || b-u < tol2)
1544: d=SIGN(tol1,xm-x);
1545: }
1546: } else {
1547: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1548: }
1549: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1550: fu=(*f)(u);
1551: if (fu <= fx) {
1552: if (u >= x) a=x; else b=x;
1553: SHFT(v,w,x,u)
1554: SHFT(fv,fw,fx,fu)
1555: } else {
1556: if (u < x) a=u; else b=u;
1557: if (fu <= fw || w == x) {
1558: v=w;
1559: w=u;
1560: fv=fw;
1561: fw=fu;
1562: } else if (fu <= fv || v == x || v == w) {
1563: v=u;
1564: fv=fu;
1565: }
1566: }
1567: }
1568: nrerror("Too many iterations in brent");
1569: *xmin=x;
1570: return fx;
1571: }
1572:
1573: /****************** mnbrak ***********************/
1574:
1575: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1576: double (*func)(double))
1577: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1578: the downhill direction (defined by the function as evaluated at the initial points) and returns
1579: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1580: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1581: */
1582: double ulim,u,r,q, dum;
1583: double fu;
1584:
1585: double scale=10.;
1586: int iterscale=0;
1587:
1588: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1589: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1590:
1591:
1592: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1593: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1594: /* *bx = *ax - (*ax - *bx)/scale; */
1595: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1596: /* } */
1597:
1598: if (*fb > *fa) {
1599: SHFT(dum,*ax,*bx,dum)
1600: SHFT(dum,*fb,*fa,dum)
1601: }
1602: *cx=(*bx)+GOLD*(*bx-*ax);
1603: *fc=(*func)(*cx);
1604: #ifdef DEBUG
1605: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1606: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1607: #endif
1608: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1609: r=(*bx-*ax)*(*fb-*fc);
1610: q=(*bx-*cx)*(*fb-*fa);
1611: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1612: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1613: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1614: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1615: fu=(*func)(u);
1616: #ifdef DEBUG
1617: /* f(x)=A(x-u)**2+f(u) */
1618: double A, fparabu;
1619: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1620: fparabu= *fa - A*(*ax-u)*(*ax-u);
1621: printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1622: fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1623: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1624: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1625: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1626: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1627: #endif
1628: #ifdef MNBRAKORIGINAL
1629: #else
1630: /* if (fu > *fc) { */
1631: /* #ifdef DEBUG */
1632: /* printf("mnbrak4 fu > fc \n"); */
1633: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1634: /* #endif */
1635: /* /\* 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 *\\/ *\/ */
1636: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1637: /* dum=u; /\* Shifting c and u *\/ */
1638: /* u = *cx; */
1639: /* *cx = dum; */
1640: /* dum = fu; */
1641: /* fu = *fc; */
1642: /* *fc =dum; */
1643: /* } else { /\* end *\/ */
1644: /* #ifdef DEBUG */
1645: /* printf("mnbrak3 fu < fc \n"); */
1646: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1647: /* #endif */
1648: /* dum=u; /\* Shifting c and u *\/ */
1649: /* u = *cx; */
1650: /* *cx = dum; */
1651: /* dum = fu; */
1652: /* fu = *fc; */
1653: /* *fc =dum; */
1654: /* } */
1655: #ifdef DEBUG
1656: printf("mnbrak34 fu < or >= fc \n");
1657: fprintf(ficlog, "mnbrak34 fu < fc\n");
1658: #endif
1659: dum=u; /* Shifting c and u */
1660: u = *cx;
1661: *cx = dum;
1662: dum = fu;
1663: fu = *fc;
1664: *fc =dum;
1665: #endif
1666: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1667: #ifdef DEBUG
1668: printf("mnbrak2 u after c but before ulim\n");
1669: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1670: #endif
1671: fu=(*func)(u);
1672: if (fu < *fc) {
1673: #ifdef DEBUG
1674: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1675: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1676: #endif
1677: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1678: SHFT(*fb,*fc,fu,(*func)(u))
1679: }
1680: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1681: #ifdef DEBUG
1682: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1683: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1684: #endif
1685: u=ulim;
1686: fu=(*func)(u);
1687: } else { /* u could be left to b (if r > q parabola has a maximum) */
1688: #ifdef DEBUG
1689: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1690: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1691: #endif
1692: u=(*cx)+GOLD*(*cx-*bx);
1693: fu=(*func)(u);
1694: } /* end tests */
1695: SHFT(*ax,*bx,*cx,u)
1696: SHFT(*fa,*fb,*fc,fu)
1697: #ifdef DEBUG
1698: printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
1699: fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
1700: #endif
1701: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1702: }
1703:
1704: /*************** linmin ************************/
1705: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1706: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1707: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1708: the value of func at the returned location p . This is actually all accomplished by calling the
1709: routines mnbrak and brent .*/
1710: int ncom;
1711: double *pcom,*xicom;
1712: double (*nrfunc)(double []);
1713:
1714: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1715: {
1716: double brent(double ax, double bx, double cx,
1717: double (*f)(double), double tol, double *xmin);
1718: double f1dim(double x);
1719: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1720: double *fc, double (*func)(double));
1721: int j;
1722: double xx,xmin,bx,ax;
1723: double fx,fb,fa;
1724:
1725: #ifdef LINMINORIGINAL
1726: #else
1727: double scale=10., axs, xxs; /* Scale added for infinity */
1728: #endif
1729:
1730: ncom=n;
1731: pcom=vector(1,n);
1732: xicom=vector(1,n);
1733: nrfunc=func;
1734: for (j=1;j<=n;j++) {
1735: pcom[j]=p[j];
1736: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1737: }
1738:
1739: #ifdef LINMINORIGINAL
1740: xx=1.;
1741: #else
1742: axs=0.0;
1743: xxs=1.;
1744: do{
1745: xx= xxs;
1746: #endif
1747: ax=0.;
1748: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1749: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1750: /* 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)) */
1751: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1752: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1753: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1754: /* 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]]*/
1755: #ifdef LINMINORIGINAL
1756: #else
1757: if (fx != fx){
1758: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1759: printf("|");
1760: fprintf(ficlog,"|");
1761: #ifdef DEBUGLINMIN
1762: 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);
1763: #endif
1764: }
1765: }while(fx != fx);
1766: #endif
1767:
1768: #ifdef DEBUGLINMIN
1769: 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);
1770: 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);
1771: #endif
1772: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1773: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1774: /* fmin = f(p[j] + xmin * xi[j]) */
1775: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1776: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1777: #ifdef DEBUG
1778: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1779: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1780: #endif
1781: #ifdef DEBUGLINMIN
1782: printf("linmin end ");
1783: fprintf(ficlog,"linmin end ");
1784: #endif
1785: for (j=1;j<=n;j++) {
1786: #ifdef LINMINORIGINAL
1787: xi[j] *= xmin;
1788: #else
1789: #ifdef DEBUGLINMIN
1790: if(xxs <1.0)
1791: printf(" before xi[%d]=%12.8f", j,xi[j]);
1792: #endif
1793: 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) */
1794: #ifdef DEBUGLINMIN
1795: if(xxs <1.0)
1796: 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 );
1797: #endif
1798: #endif
1799: p[j] += xi[j]; /* Parameters values are updated accordingly */
1800: }
1801: #ifdef DEBUGLINMIN
1802: printf("\n");
1803: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1804: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1805: for (j=1;j<=n;j++) {
1806: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1807: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1808: if(j % ncovmodel == 0){
1809: printf("\n");
1810: fprintf(ficlog,"\n");
1811: }
1812: }
1813: #else
1814: #endif
1815: free_vector(xicom,1,n);
1816: free_vector(pcom,1,n);
1817: }
1818:
1819:
1820: /*************** powell ************************/
1821: /*
1822: Minimization of a function func of n variables. Input consists of an initial starting point
1823: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1824: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1825: such that failure to decrease by more than this amount on one iteration signals doneness. On
1826: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1827: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1828: */
1829: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1830: double (*func)(double []))
1831: {
1832: void linmin(double p[], double xi[], int n, double *fret,
1833: double (*func)(double []));
1834: int i,ibig,j;
1835: double del,t,*pt,*ptt,*xit;
1836: double directest;
1837: double fp,fptt;
1838: double *xits;
1839: int niterf, itmp;
1840:
1841: pt=vector(1,n);
1842: ptt=vector(1,n);
1843: xit=vector(1,n);
1844: xits=vector(1,n);
1845: *fret=(*func)(p);
1846: for (j=1;j<=n;j++) pt[j]=p[j];
1847: rcurr_time = time(NULL);
1848: for (*iter=1;;++(*iter)) {
1849: fp=(*fret); /* From former iteration or initial value */
1850: ibig=0;
1851: del=0.0;
1852: rlast_time=rcurr_time;
1853: /* (void) gettimeofday(&curr_time,&tzp); */
1854: rcurr_time = time(NULL);
1855: curr_time = *localtime(&rcurr_time);
1856: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1857: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1858: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1859: for (i=1;i<=n;i++) {
1860: printf(" %d %.12f",i, p[i]);
1861: fprintf(ficlog," %d %.12lf",i, p[i]);
1862: fprintf(ficrespow," %.12lf", p[i]);
1863: }
1864: printf("\n");
1865: fprintf(ficlog,"\n");
1866: fprintf(ficrespow,"\n");fflush(ficrespow);
1867: if(*iter <=3){
1868: tml = *localtime(&rcurr_time);
1869: strcpy(strcurr,asctime(&tml));
1870: rforecast_time=rcurr_time;
1871: itmp = strlen(strcurr);
1872: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1873: strcurr[itmp-1]='\0';
1874: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1875: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1876: for(niterf=10;niterf<=30;niterf+=10){
1877: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1878: forecast_time = *localtime(&rforecast_time);
1879: strcpy(strfor,asctime(&forecast_time));
1880: itmp = strlen(strfor);
1881: if(strfor[itmp-1]=='\n')
1882: strfor[itmp-1]='\0';
1883: 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);
1884: 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);
1885: }
1886: }
1887: for (i=1;i<=n;i++) { /* For each direction i */
1888: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1889: fptt=(*fret);
1890: #ifdef DEBUG
1891: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1892: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1893: #endif
1894: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1895: fprintf(ficlog,"%d",i);fflush(ficlog);
1896: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1897: /* Outputs are fret(new point p) p is updated and xit rescaled */
1898: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1899: /* because that direction will be replaced unless the gain del is small */
1900: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1901: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1902: /* with the new direction. */
1903: del=fabs(fptt-(*fret));
1904: ibig=i;
1905: }
1906: #ifdef DEBUG
1907: printf("%d %.12e",i,(*fret));
1908: fprintf(ficlog,"%d %.12e",i,(*fret));
1909: for (j=1;j<=n;j++) {
1910: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1911: printf(" x(%d)=%.12e",j,xit[j]);
1912: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1913: }
1914: for(j=1;j<=n;j++) {
1915: printf(" p(%d)=%.12e",j,p[j]);
1916: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1917: }
1918: printf("\n");
1919: fprintf(ficlog,"\n");
1920: #endif
1921: } /* end loop on each direction i */
1922: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1923: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1924: /* New value of last point Pn is not computed, P(n-1) */
1925: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1926: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1927: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1928: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1929: /* decreased of more than 3.84 */
1930: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1931: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1932: /* By adding 10 parameters more the gain should be 18.31 */
1933:
1934: /* Starting the program with initial values given by a former maximization will simply change */
1935: /* the scales of the directions and the directions, because the are reset to canonical directions */
1936: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1937: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1938: #ifdef DEBUG
1939: int k[2],l;
1940: k[0]=1;
1941: k[1]=-1;
1942: printf("Max: %.12e",(*func)(p));
1943: fprintf(ficlog,"Max: %.12e",(*func)(p));
1944: for (j=1;j<=n;j++) {
1945: printf(" %.12e",p[j]);
1946: fprintf(ficlog," %.12e",p[j]);
1947: }
1948: printf("\n");
1949: fprintf(ficlog,"\n");
1950: for(l=0;l<=1;l++) {
1951: for (j=1;j<=n;j++) {
1952: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1953: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1954: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1955: }
1956: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1957: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1958: }
1959: #endif
1960:
1961:
1962: free_vector(xit,1,n);
1963: free_vector(xits,1,n);
1964: free_vector(ptt,1,n);
1965: free_vector(pt,1,n);
1966: return;
1967: } /* enough precision */
1968: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1969: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1970: ptt[j]=2.0*p[j]-pt[j];
1971: xit[j]=p[j]-pt[j];
1972: pt[j]=p[j];
1973: }
1974: fptt=(*func)(ptt); /* f_3 */
1975: #ifdef POWELLF1F3
1976: #else
1977: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1978: #endif
1979: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1980: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1981: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1982: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1983: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1984: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1985: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1986: #ifdef NRCORIGINAL
1987: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1988: #else
1989: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1990: t= t- del*SQR(fp-fptt);
1991: #endif
1992: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1993: #ifdef DEBUG
1994: 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);
1995: 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);
1996: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1997: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1998: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1999: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
2000: 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);
2001: 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);
2002: #endif
2003: #ifdef POWELLORIGINAL
2004: if (t < 0.0) { /* Then we use it for new direction */
2005: #else
2006: if (directest*t < 0.0) { /* Contradiction between both tests */
2007: 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);
2008: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
2009: fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
2010: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
2011: }
2012: if (directest < 0.0) { /* Then we use it for new direction */
2013: #endif
2014: #ifdef DEBUGLINMIN
2015: printf("Before linmin in direction P%d-P0\n",n);
2016: for (j=1;j<=n;j++) {
2017: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2018: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2019: if(j % ncovmodel == 0){
2020: printf("\n");
2021: fprintf(ficlog,"\n");
2022: }
2023: }
2024: #endif
2025: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
2026: #ifdef DEBUGLINMIN
2027: for (j=1;j<=n;j++) {
2028: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2029: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
2030: if(j % ncovmodel == 0){
2031: printf("\n");
2032: fprintf(ficlog,"\n");
2033: }
2034: }
2035: #endif
2036: for (j=1;j<=n;j++) {
2037: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
2038: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
2039: }
2040: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2041: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2042:
2043: #ifdef DEBUG
2044: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2045: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2046: for(j=1;j<=n;j++){
2047: printf(" %.12e",xit[j]);
2048: fprintf(ficlog," %.12e",xit[j]);
2049: }
2050: printf("\n");
2051: fprintf(ficlog,"\n");
2052: #endif
2053: } /* end of t or directest negative */
2054: #ifdef POWELLF1F3
2055: #else
2056: } /* end if (fptt < fp) */
2057: #endif
2058: } /* loop iteration */
2059: }
2060:
2061: /**** Prevalence limit (stable or period prevalence) ****************/
2062:
2063: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
2064: {
2065: /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
2066: matrix by transitions matrix until convergence is reached with precision ftolpl */
2067: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2068: /* Wx is row vector: population in state 1, population in state 2, population dead */
2069: /* or prevalence in state 1, prevalence in state 2, 0 */
2070: /* newm is the matrix after multiplications, its rows are identical at a factor */
2071: /* Initial matrix pimij */
2072: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2073: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2074: /* 0, 0 , 1} */
2075: /*
2076: * and after some iteration: */
2077: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2078: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2079: /* 0, 0 , 1} */
2080: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2081: /* {0.51571254859325999, 0.4842874514067399, */
2082: /* 0.51326036147820708, 0.48673963852179264} */
2083: /* If we start from prlim again, prlim tends to a constant matrix */
2084:
2085: int i, ii,j,k;
2086: double *min, *max, *meandiff, maxmax,sumnew=0.;
2087: /* double **matprod2(); */ /* test */
2088: double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
2089: double **newm;
2090: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2091: int ncvloop=0;
2092:
2093: min=vector(1,nlstate);
2094: max=vector(1,nlstate);
2095: meandiff=vector(1,nlstate);
2096:
2097: /* Starting with matrix unity */
2098: for (ii=1;ii<=nlstate+ndeath;ii++)
2099: for (j=1;j<=nlstate+ndeath;j++){
2100: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2101: }
2102:
2103: cov[1]=1.;
2104:
2105: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2106: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2107: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2108: ncvloop++;
2109: newm=savm;
2110: /* Covariates have to be included here again */
2111: cov[2]=agefin;
2112: if(nagesqr==1)
2113: cov[3]= agefin*agefin;;
2114: for (k=1; k<=cptcovn;k++) {
2115: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2116: /* Here comes the value of the covariate 'ij' */
2117: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2118: /* 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])]); */
2119: }
2120: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2121: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2122: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2123: for (k=1; k<=cptcovprod;k++) /* Useless */
2124: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2125: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2126:
2127: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2128: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2129: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2130: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2131: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2132: /* age and covariate values of ij are in 'cov' */
2133: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2134:
2135: savm=oldm;
2136: oldm=newm;
2137:
2138: for(j=1; j<=nlstate; j++){
2139: max[j]=0.;
2140: min[j]=1.;
2141: }
2142: for(i=1;i<=nlstate;i++){
2143: sumnew=0;
2144: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2145: for(j=1; j<=nlstate; j++){
2146: prlim[i][j]= newm[i][j]/(1-sumnew);
2147: max[j]=FMAX(max[j],prlim[i][j]);
2148: min[j]=FMIN(min[j],prlim[i][j]);
2149: }
2150: }
2151:
2152: maxmax=0.;
2153: for(j=1; j<=nlstate; j++){
2154: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2155: maxmax=FMAX(maxmax,meandiff[j]);
2156: /* 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); */
2157: } /* j loop */
2158: *ncvyear= (int)age- (int)agefin;
2159: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2160: if(maxmax < ftolpl){
2161: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2162: free_vector(min,1,nlstate);
2163: free_vector(max,1,nlstate);
2164: free_vector(meandiff,1,nlstate);
2165: return prlim;
2166: }
2167: } /* age loop */
2168: /* After some age loop it doesn't converge */
2169: 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\
2170: 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);
2171: /* 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); */
2172: free_vector(min,1,nlstate);
2173: free_vector(max,1,nlstate);
2174: free_vector(meandiff,1,nlstate);
2175:
2176: return prlim; /* should not reach here */
2177: }
2178:
2179:
2180: /**** Back Prevalence limit (stable or period prevalence) ****************/
2181:
2182: /* 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) */
2183: /* 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) */
2184: double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
2185: {
2186: /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
2187: matrix by transitions matrix until convergence is reached with precision ftolpl */
2188: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2189: /* Wx is row vector: population in state 1, population in state 2, population dead */
2190: /* or prevalence in state 1, prevalence in state 2, 0 */
2191: /* newm is the matrix after multiplications, its rows are identical at a factor */
2192: /* Initial matrix pimij */
2193: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2194: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2195: /* 0, 0 , 1} */
2196: /*
2197: * and after some iteration: */
2198: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2199: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2200: /* 0, 0 , 1} */
2201: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2202: /* {0.51571254859325999, 0.4842874514067399, */
2203: /* 0.51326036147820708, 0.48673963852179264} */
2204: /* If we start from prlim again, prlim tends to a constant matrix */
2205:
2206: int i, ii,j,k;
2207: double *min, *max, *meandiff, maxmax,sumnew=0.;
2208: /* double **matprod2(); */ /* test */
2209: double **out, cov[NCOVMAX+1], **bmij();
2210: double **newm;
2211: double **dnewm, **doldm, **dsavm; /* for use */
2212: double **oldm, **savm; /* for use */
2213:
2214: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2215: int ncvloop=0;
2216:
2217: min=vector(1,nlstate);
2218: max=vector(1,nlstate);
2219: meandiff=vector(1,nlstate);
2220:
2221: dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
2222: oldm=oldms; savm=savms;
2223:
2224: /* Starting with matrix unity */
2225: for (ii=1;ii<=nlstate+ndeath;ii++)
2226: for (j=1;j<=nlstate+ndeath;j++){
2227: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2228: }
2229:
2230: cov[1]=1.;
2231:
2232: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2233: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2234: /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
2235: for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
2236: ncvloop++;
2237: newm=savm; /* oldm should be kept from previous iteration or unity at start */
2238: /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
2239: /* Covariates have to be included here again */
2240: cov[2]=agefin;
2241: if(nagesqr==1)
2242: cov[3]= agefin*agefin;;
2243: for (k=1; k<=cptcovn;k++) {
2244: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2245: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2246: /* 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])]); */
2247: }
2248: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2249: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2250: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2251: for (k=1; k<=cptcovprod;k++) /* Useless */
2252: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2253: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2254:
2255: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2256: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2257: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2258: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2259: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2260: /* ij should be linked to the correct index of cov */
2261: /* age and covariate values ij are in 'cov', but we need to pass
2262: * ij for the observed prevalence at age and status and covariate
2263: * number: prevacurrent[(int)agefin][ii][ij]
2264: */
2265: /* 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 *\/ */
2266: /* 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 *\/ */
2267: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
2268: savm=oldm;
2269: oldm=newm;
2270: for(j=1; j<=nlstate; j++){
2271: max[j]=0.;
2272: min[j]=1.;
2273: }
2274: for(j=1; j<=nlstate; j++){
2275: for(i=1;i<=nlstate;i++){
2276: /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
2277: bprlim[i][j]= newm[i][j];
2278: max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
2279: min[i]=FMIN(min[i],bprlim[i][j]);
2280: }
2281: }
2282:
2283: maxmax=0.;
2284: for(i=1; i<=nlstate; i++){
2285: meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
2286: maxmax=FMAX(maxmax,meandiff[i]);
2287: /* 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); */
2288: } /* j loop */
2289: *ncvyear= -( (int)age- (int)agefin);
2290: /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
2291: if(maxmax < ftolpl){
2292: printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);
2293: free_vector(min,1,nlstate);
2294: free_vector(max,1,nlstate);
2295: free_vector(meandiff,1,nlstate);
2296: return bprlim;
2297: }
2298: } /* age loop */
2299: /* After some age loop it doesn't converge */
2300: 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\
2301: 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);
2302: /* 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); */
2303: free_vector(min,1,nlstate);
2304: free_vector(max,1,nlstate);
2305: free_vector(meandiff,1,nlstate);
2306:
2307: return bprlim; /* should not reach here */
2308: }
2309:
2310: /*************** transition probabilities ***************/
2311:
2312: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2313: {
2314: /* According to parameters values stored in x and the covariate's values stored in cov,
2315: computes the probability to be observed in state j being in state i by appying the
2316: model to the ncovmodel covariates (including constant and age).
2317: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2318: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2319: ncth covariate in the global vector x is given by the formula:
2320: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2321: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2322: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2323: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2324: Outputs ps[i][j] the probability to be observed in j being in j according to
2325: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2326: */
2327: double s1, lnpijopii;
2328: /*double t34;*/
2329: int i,j, nc, ii, jj;
2330:
2331: for(i=1; i<= nlstate; i++){
2332: for(j=1; j<i;j++){
2333: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2334: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2335: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2336: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2337: }
2338: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2339: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2340: }
2341: for(j=i+1; j<=nlstate+ndeath;j++){
2342: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2343: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2344: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2345: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2346: }
2347: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2348: }
2349: }
2350:
2351: for(i=1; i<= nlstate; i++){
2352: s1=0;
2353: for(j=1; j<i; j++){
2354: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2355: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2356: }
2357: for(j=i+1; j<=nlstate+ndeath; j++){
2358: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2359: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2360: }
2361: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2362: ps[i][i]=1./(s1+1.);
2363: /* Computing other pijs */
2364: for(j=1; j<i; j++)
2365: ps[i][j]= exp(ps[i][j])*ps[i][i];
2366: for(j=i+1; j<=nlstate+ndeath; j++)
2367: ps[i][j]= exp(ps[i][j])*ps[i][i];
2368: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2369: } /* end i */
2370:
2371: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2372: for(jj=1; jj<= nlstate+ndeath; jj++){
2373: ps[ii][jj]=0;
2374: ps[ii][ii]=1;
2375: }
2376: }
2377:
2378:
2379: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2380: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2381: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2382: /* } */
2383: /* printf("\n "); */
2384: /* } */
2385: /* printf("\n ");printf("%lf ",cov[2]);*/
2386: /*
2387: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2388: goto end;*/
2389: return ps;
2390: }
2391:
2392: /*************** backward transition probabilities ***************/
2393:
2394: /* 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 ) */
2395: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate, double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
2396: double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate, double ***prevacurrent, int ij )
2397: {
2398: /* Computes the backward probability at age agefin and covariate ij
2399: * and returns in **ps as well as **bmij.
2400: */
2401: int i, ii, j,k;
2402:
2403: double **out, **pmij();
2404: double sumnew=0.;
2405: double agefin;
2406:
2407: double **dnewm, **dsavm, **doldm;
2408: double **bbmij;
2409:
2410: doldm=ddoldms; /* global pointers */
2411: dnewm=ddnewms;
2412: dsavm=ddsavms;
2413:
2414: agefin=cov[2];
2415: /* bmij *//* age is cov[2], ij is included in cov, but we need for
2416: the observed prevalence (with this covariate ij) */
2417: dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
2418: /* We do have the matrix Px in savm and we need pij */
2419: for (j=1;j<=nlstate+ndeath;j++){
2420: sumnew=0.; /* w1 p11 + w2 p21 only on live states */
2421: for (ii=1;ii<=nlstate;ii++){
2422: sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
2423: } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
2424: for (ii=1;ii<=nlstate+ndeath;ii++){
2425: if(sumnew >= 1.e-10){
2426: /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
2427: /* doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
2428: /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
2429: /* doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
2430: /* }else */
2431: doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
2432: }else{
2433: 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);
2434: }
2435: } /*End ii */
2436: } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
2437: /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
2438: bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
2439: /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
2440: /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
2441: /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
2442: /* left Product of this matrix by diag matrix of prevalences (savm) */
2443: for (j=1;j<=nlstate+ndeath;j++){
2444: for (ii=1;ii<=nlstate+ndeath;ii++){
2445: dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
2446: }
2447: } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
2448: ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
2449: /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
2450: /* end bmij */
2451: return ps;
2452: }
2453: /*************** transition probabilities ***************/
2454:
2455: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2456: {
2457: /* According to parameters values stored in x and the covariate's values stored in cov,
2458: computes the probability to be observed in state j being in state i by appying the
2459: model to the ncovmodel covariates (including constant and age).
2460: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2461: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2462: ncth covariate in the global vector x is given by the formula:
2463: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2464: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2465: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2466: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2467: Outputs ps[i][j] the probability to be observed in j being in j according to
2468: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2469: */
2470: double s1, lnpijopii;
2471: /*double t34;*/
2472: int i,j, nc, ii, jj;
2473:
2474: for(i=1; i<= nlstate; i++){
2475: for(j=1; j<i;j++){
2476: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2477: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2478: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2479: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2480: }
2481: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2482: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2483: }
2484: for(j=i+1; j<=nlstate+ndeath;j++){
2485: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2486: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2487: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2488: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2489: }
2490: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2491: }
2492: }
2493:
2494: for(i=1; i<= nlstate; i++){
2495: s1=0;
2496: for(j=1; j<i; j++){
2497: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2498: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2499: }
2500: for(j=i+1; j<=nlstate+ndeath; j++){
2501: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2502: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2503: }
2504: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2505: ps[i][i]=1./(s1+1.);
2506: /* Computing other pijs */
2507: for(j=1; j<i; j++)
2508: ps[i][j]= exp(ps[i][j])*ps[i][i];
2509: for(j=i+1; j<=nlstate+ndeath; j++)
2510: ps[i][j]= exp(ps[i][j])*ps[i][i];
2511: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2512: } /* end i */
2513:
2514: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2515: for(jj=1; jj<= nlstate+ndeath; jj++){
2516: ps[ii][jj]=0;
2517: ps[ii][ii]=1;
2518: }
2519: }
2520: /* Added for backcast */ /* Transposed matrix too */
2521: for(jj=1; jj<= nlstate+ndeath; jj++){
2522: s1=0.;
2523: for(ii=1; ii<= nlstate+ndeath; ii++){
2524: s1+=ps[ii][jj];
2525: }
2526: for(ii=1; ii<= nlstate; ii++){
2527: ps[ii][jj]=ps[ii][jj]/s1;
2528: }
2529: }
2530: /* Transposition */
2531: for(jj=1; jj<= nlstate+ndeath; jj++){
2532: for(ii=jj; ii<= nlstate+ndeath; ii++){
2533: s1=ps[ii][jj];
2534: ps[ii][jj]=ps[jj][ii];
2535: ps[jj][ii]=s1;
2536: }
2537: }
2538: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2539: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2540: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2541: /* } */
2542: /* printf("\n "); */
2543: /* } */
2544: /* printf("\n ");printf("%lf ",cov[2]);*/
2545: /*
2546: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2547: goto end;*/
2548: return ps;
2549: }
2550:
2551:
2552: /**************** Product of 2 matrices ******************/
2553:
2554: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2555: {
2556: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2557: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2558: /* in, b, out are matrice of pointers which should have been initialized
2559: before: only the contents of out is modified. The function returns
2560: a pointer to pointers identical to out */
2561: int i, j, k;
2562: for(i=nrl; i<= nrh; i++)
2563: for(k=ncolol; k<=ncoloh; k++){
2564: out[i][k]=0.;
2565: for(j=ncl; j<=nch; j++)
2566: out[i][k] +=in[i][j]*b[j][k];
2567: }
2568: return out;
2569: }
2570:
2571:
2572: /************* Higher Matrix Product ***************/
2573:
2574: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2575: {
2576: /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over
2577: 'nhstepm*hstepm*stepm' months (i.e. until
2578: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2579: nhstepm*hstepm matrices.
2580: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2581: (typically every 2 years instead of every month which is too big
2582: for the memory).
2583: Model is determined by parameters x and covariates have to be
2584: included manually here.
2585:
2586: */
2587:
2588: int i, j, d, h, k;
2589: double **out, cov[NCOVMAX+1];
2590: double **newm;
2591: double agexact;
2592: double agebegin, ageend;
2593:
2594: /* Hstepm could be zero and should return the unit matrix */
2595: for (i=1;i<=nlstate+ndeath;i++)
2596: for (j=1;j<=nlstate+ndeath;j++){
2597: oldm[i][j]=(i==j ? 1.0 : 0.0);
2598: po[i][j][0]=(i==j ? 1.0 : 0.0);
2599: }
2600: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2601: for(h=1; h <=nhstepm; h++){
2602: for(d=1; d <=hstepm; d++){
2603: newm=savm;
2604: /* Covariates have to be included here again */
2605: cov[1]=1.;
2606: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
2607: cov[2]=agexact;
2608: if(nagesqr==1)
2609: cov[3]= agexact*agexact;
2610: for (k=1; k<=cptcovn;k++)
2611: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2612: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2613: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2614: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2615: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2616: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2617: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2618: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2619: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2620:
2621:
2622: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2623: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2624: /* right multiplication of oldm by the current matrix */
2625: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2626: pmij(pmmij,cov,ncovmodel,x,nlstate));
2627: /* if((int)age == 70){ */
2628: /* printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
2629: /* for(i=1; i<=nlstate+ndeath; i++) { */
2630: /* printf("%d pmmij ",i); */
2631: /* for(j=1;j<=nlstate+ndeath;j++) { */
2632: /* printf("%f ",pmmij[i][j]); */
2633: /* } */
2634: /* printf(" oldm "); */
2635: /* for(j=1;j<=nlstate+ndeath;j++) { */
2636: /* printf("%f ",oldm[i][j]); */
2637: /* } */
2638: /* printf("\n"); */
2639: /* } */
2640: /* } */
2641: savm=oldm;
2642: oldm=newm;
2643: }
2644: for(i=1; i<=nlstate+ndeath; i++)
2645: for(j=1;j<=nlstate+ndeath;j++) {
2646: po[i][j][h]=newm[i][j];
2647: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2648: }
2649: /*printf("h=%d ",h);*/
2650: } /* end h */
2651: /* printf("\n H=%d \n",h); */
2652: return po;
2653: }
2654:
2655: /************* Higher Back Matrix Product ***************/
2656: /* 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 ) */
2657: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
2658: {
2659: /* Computes the transition matrix starting at age 'age' over
2660: 'nhstepm*hstepm*stepm' months (i.e. until
2661: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2662: nhstepm*hstepm matrices.
2663: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2664: (typically every 2 years instead of every month which is too big
2665: for the memory).
2666: Model is determined by parameters x and covariates have to be
2667: included manually here.
2668:
2669: */
2670:
2671: int i, j, d, h, k;
2672: double **out, cov[NCOVMAX+1];
2673: double **newm;
2674: double agexact;
2675: double agebegin, ageend;
2676: double **oldm, **savm;
2677:
2678: oldm=oldms;savm=savms;
2679: /* Hstepm could be zero and should return the unit matrix */
2680: for (i=1;i<=nlstate+ndeath;i++)
2681: for (j=1;j<=nlstate+ndeath;j++){
2682: oldm[i][j]=(i==j ? 1.0 : 0.0);
2683: po[i][j][0]=(i==j ? 1.0 : 0.0);
2684: }
2685: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2686: for(h=1; h <=nhstepm; h++){
2687: for(d=1; d <=hstepm; d++){
2688: newm=savm;
2689: /* Covariates have to be included here again */
2690: cov[1]=1.;
2691: agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
2692: /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
2693: cov[2]=agexact;
2694: if(nagesqr==1)
2695: cov[3]= agexact*agexact;
2696: for (k=1; k<=cptcovn;k++)
2697: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2698: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2699: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2700: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2701: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2702: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2703: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2704: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2705: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2706:
2707:
2708: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2709: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2710: /* Careful transposed matrix */
2711: /* age is in cov[2] */
2712: /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
2713: /* 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
2714: out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
2715: 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
2716: /* if((int)age == 70){ */
2717: /* printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
2718: /* for(i=1; i<=nlstate+ndeath; i++) { */
2719: /* printf("%d pmmij ",i); */
2720: /* for(j=1;j<=nlstate+ndeath;j++) { */
2721: /* printf("%f ",pmmij[i][j]); */
2722: /* } */
2723: /* printf(" oldm "); */
2724: /* for(j=1;j<=nlstate+ndeath;j++) { */
2725: /* printf("%f ",oldm[i][j]); */
2726: /* } */
2727: /* printf("\n"); */
2728: /* } */
2729: /* } */
2730: savm=oldm;
2731: oldm=newm;
2732: }
2733: for(i=1; i<=nlstate+ndeath; i++)
2734: for(j=1;j<=nlstate+ndeath;j++) {
2735: po[i][j][h]=newm[i][j];
2736: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2737: }
2738: /*printf("h=%d ",h);*/
2739: } /* end h */
2740: /* printf("\n H=%d \n",h); */
2741: return po;
2742: }
2743:
2744:
2745: #ifdef NLOPT
2746: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2747: double fret;
2748: double *xt;
2749: int j;
2750: myfunc_data *d2 = (myfunc_data *) pd;
2751: /* xt = (p1-1); */
2752: xt=vector(1,n);
2753: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2754:
2755: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2756: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2757: printf("Function = %.12lf ",fret);
2758: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2759: printf("\n");
2760: free_vector(xt,1,n);
2761: return fret;
2762: }
2763: #endif
2764:
2765: /*************** log-likelihood *************/
2766: double func( double *x)
2767: {
2768: int i, ii, j, k, mi, d, kk;
2769: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2770: double **out;
2771: double sw; /* Sum of weights */
2772: double lli; /* Individual log likelihood */
2773: int s1, s2;
2774: double bbh, survp;
2775: long ipmx;
2776: double agexact;
2777: /*extern weight */
2778: /* We are differentiating ll according to initial status */
2779: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2780: /*for(i=1;i<imx;i++)
2781: printf(" %d\n",s[4][i]);
2782: */
2783:
2784: ++countcallfunc;
2785:
2786: cov[1]=1.;
2787:
2788: for(k=1; k<=nlstate; k++) ll[k]=0.;
2789:
2790: if(mle==1){
2791: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2792: /* Computes the values of the ncovmodel covariates of the model
2793: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2794: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2795: to be observed in j being in i according to the model.
2796: */
2797: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2798: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2799: }
2800: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2801: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2802: has been calculated etc */
2803: for(mi=1; mi<= wav[i]-1; mi++){
2804: for (ii=1;ii<=nlstate+ndeath;ii++)
2805: for (j=1;j<=nlstate+ndeath;j++){
2806: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2807: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2808: }
2809: for(d=0; d<dh[mi][i]; d++){
2810: newm=savm;
2811: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2812: cov[2]=agexact;
2813: if(nagesqr==1)
2814: cov[3]= agexact*agexact;
2815: for (kk=1; kk<=cptcovage;kk++) {
2816: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2817: }
2818: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2819: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2820: savm=oldm;
2821: oldm=newm;
2822: } /* end mult */
2823:
2824: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2825: /* But now since version 0.9 we anticipate for bias at large stepm.
2826: * If stepm is larger than one month (smallest stepm) and if the exact delay
2827: * (in months) between two waves is not a multiple of stepm, we rounded to
2828: * the nearest (and in case of equal distance, to the lowest) interval but now
2829: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2830: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2831: * probability in order to take into account the bias as a fraction of the way
2832: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2833: * -stepm/2 to stepm/2 .
2834: * For stepm=1 the results are the same as for previous versions of Imach.
2835: * For stepm > 1 the results are less biased than in previous versions.
2836: */
2837: s1=s[mw[mi][i]][i];
2838: s2=s[mw[mi+1][i]][i];
2839: bbh=(double)bh[mi][i]/(double)stepm;
2840: /* bias bh is positive if real duration
2841: * is higher than the multiple of stepm and negative otherwise.
2842: */
2843: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2844: if( s2 > nlstate){
2845: /* i.e. if s2 is a death state and if the date of death is known
2846: then the contribution to the likelihood is the probability to
2847: die between last step unit time and current step unit time,
2848: which is also equal to probability to die before dh
2849: minus probability to die before dh-stepm .
2850: In version up to 0.92 likelihood was computed
2851: as if date of death was unknown. Death was treated as any other
2852: health state: the date of the interview describes the actual state
2853: and not the date of a change in health state. The former idea was
2854: to consider that at each interview the state was recorded
2855: (healthy, disable or death) and IMaCh was corrected; but when we
2856: introduced the exact date of death then we should have modified
2857: the contribution of an exact death to the likelihood. This new
2858: contribution is smaller and very dependent of the step unit
2859: stepm. It is no more the probability to die between last interview
2860: and month of death but the probability to survive from last
2861: interview up to one month before death multiplied by the
2862: probability to die within a month. Thanks to Chris
2863: Jackson for correcting this bug. Former versions increased
2864: mortality artificially. The bad side is that we add another loop
2865: which slows down the processing. The difference can be up to 10%
2866: lower mortality.
2867: */
2868: /* If, at the beginning of the maximization mostly, the
2869: cumulative probability or probability to be dead is
2870: constant (ie = 1) over time d, the difference is equal to
2871: 0. out[s1][3] = savm[s1][3]: probability, being at state
2872: s1 at precedent wave, to be dead a month before current
2873: wave is equal to probability, being at state s1 at
2874: precedent wave, to be dead at mont of the current
2875: wave. Then the observed probability (that this person died)
2876: is null according to current estimated parameter. In fact,
2877: it should be very low but not zero otherwise the log go to
2878: infinity.
2879: */
2880: /* #ifdef INFINITYORIGINAL */
2881: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2882: /* #else */
2883: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2884: /* lli=log(mytinydouble); */
2885: /* else */
2886: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2887: /* #endif */
2888: lli=log(out[s1][s2] - savm[s1][s2]);
2889:
2890: } else if ( s2==-1 ) { /* alive */
2891: for (j=1,survp=0. ; j<=nlstate; j++)
2892: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2893: /*survp += out[s1][j]; */
2894: lli= log(survp);
2895: }
2896: else if (s2==-4) {
2897: for (j=3,survp=0. ; j<=nlstate; j++)
2898: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2899: lli= log(survp);
2900: }
2901: else if (s2==-5) {
2902: for (j=1,survp=0. ; j<=2; j++)
2903: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2904: lli= log(survp);
2905: }
2906: else{
2907: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2908: /* 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 */
2909: }
2910: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2911: /*if(lli ==000.0)*/
2912: /*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); */
2913: ipmx +=1;
2914: sw += weight[i];
2915: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2916: /* if (lli < log(mytinydouble)){ */
2917: /* 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); */
2918: /* 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]); */
2919: /* } */
2920: } /* end of wave */
2921: } /* end of individual */
2922: } else if(mle==2){
2923: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2924: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2925: for(mi=1; mi<= wav[i]-1; mi++){
2926: for (ii=1;ii<=nlstate+ndeath;ii++)
2927: for (j=1;j<=nlstate+ndeath;j++){
2928: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2929: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2930: }
2931: for(d=0; d<=dh[mi][i]; d++){
2932: newm=savm;
2933: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2934: cov[2]=agexact;
2935: if(nagesqr==1)
2936: cov[3]= agexact*agexact;
2937: for (kk=1; kk<=cptcovage;kk++) {
2938: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2939: }
2940: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2941: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2942: savm=oldm;
2943: oldm=newm;
2944: } /* end mult */
2945:
2946: s1=s[mw[mi][i]][i];
2947: s2=s[mw[mi+1][i]][i];
2948: bbh=(double)bh[mi][i]/(double)stepm;
2949: 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 */
2950: ipmx +=1;
2951: sw += weight[i];
2952: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2953: } /* end of wave */
2954: } /* end of individual */
2955: } else if(mle==3){ /* exponential inter-extrapolation */
2956: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2957: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2958: for(mi=1; mi<= wav[i]-1; mi++){
2959: for (ii=1;ii<=nlstate+ndeath;ii++)
2960: for (j=1;j<=nlstate+ndeath;j++){
2961: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2962: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2963: }
2964: for(d=0; d<dh[mi][i]; d++){
2965: newm=savm;
2966: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2967: cov[2]=agexact;
2968: if(nagesqr==1)
2969: cov[3]= agexact*agexact;
2970: for (kk=1; kk<=cptcovage;kk++) {
2971: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2972: }
2973: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2974: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2975: savm=oldm;
2976: oldm=newm;
2977: } /* end mult */
2978:
2979: s1=s[mw[mi][i]][i];
2980: s2=s[mw[mi+1][i]][i];
2981: bbh=(double)bh[mi][i]/(double)stepm;
2982: 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 */
2983: ipmx +=1;
2984: sw += weight[i];
2985: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2986: } /* end of wave */
2987: } /* end of individual */
2988: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2989: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2990: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2991: for(mi=1; mi<= wav[i]-1; mi++){
2992: for (ii=1;ii<=nlstate+ndeath;ii++)
2993: for (j=1;j<=nlstate+ndeath;j++){
2994: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2995: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2996: }
2997: for(d=0; d<dh[mi][i]; d++){
2998: newm=savm;
2999: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3000: cov[2]=agexact;
3001: if(nagesqr==1)
3002: cov[3]= agexact*agexact;
3003: for (kk=1; kk<=cptcovage;kk++) {
3004: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3005: }
3006:
3007: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3008: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3009: savm=oldm;
3010: oldm=newm;
3011: } /* end mult */
3012:
3013: s1=s[mw[mi][i]][i];
3014: s2=s[mw[mi+1][i]][i];
3015: if( s2 > nlstate){
3016: lli=log(out[s1][s2] - savm[s1][s2]);
3017: } else if ( s2==-1 ) { /* alive */
3018: for (j=1,survp=0. ; j<=nlstate; j++)
3019: survp += out[s1][j];
3020: lli= log(survp);
3021: }else{
3022: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
3023: }
3024: ipmx +=1;
3025: sw += weight[i];
3026: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3027: /* 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]); */
3028: } /* end of wave */
3029: } /* end of individual */
3030: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
3031: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3032: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3033: for(mi=1; mi<= wav[i]-1; mi++){
3034: for (ii=1;ii<=nlstate+ndeath;ii++)
3035: for (j=1;j<=nlstate+ndeath;j++){
3036: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3037: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3038: }
3039: for(d=0; d<dh[mi][i]; d++){
3040: newm=savm;
3041: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3042: cov[2]=agexact;
3043: if(nagesqr==1)
3044: cov[3]= agexact*agexact;
3045: for (kk=1; kk<=cptcovage;kk++) {
3046: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3047: }
3048:
3049: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3050: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3051: savm=oldm;
3052: oldm=newm;
3053: } /* end mult */
3054:
3055: s1=s[mw[mi][i]][i];
3056: s2=s[mw[mi+1][i]][i];
3057: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
3058: ipmx +=1;
3059: sw += weight[i];
3060: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3061: /*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]);*/
3062: } /* end of wave */
3063: } /* end of individual */
3064: } /* End of if */
3065: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
3066: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
3067: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
3068: return -l;
3069: }
3070:
3071: /*************** log-likelihood *************/
3072: double funcone( double *x)
3073: {
3074: /* Same as likeli but slower because of a lot of printf and if */
3075: int i, ii, j, k, mi, d, kk;
3076: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
3077: double **out;
3078: double lli; /* Individual log likelihood */
3079: double llt;
3080: int s1, s2;
3081: double bbh, survp;
3082: double agexact;
3083: double agebegin, ageend;
3084: /*extern weight */
3085: /* We are differentiating ll according to initial status */
3086: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
3087: /*for(i=1;i<imx;i++)
3088: printf(" %d\n",s[4][i]);
3089: */
3090: cov[1]=1.;
3091:
3092: for(k=1; k<=nlstate; k++) ll[k]=0.;
3093:
3094: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
3095: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
3096: for(mi=1; mi<= wav[i]-1; mi++){
3097: for (ii=1;ii<=nlstate+ndeath;ii++)
3098: for (j=1;j<=nlstate+ndeath;j++){
3099: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
3100: savm[ii][j]=(ii==j ? 1.0 : 0.0);
3101: }
3102:
3103: agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
3104: ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
3105: for(d=0; d<dh[mi][i]; d++){ /* Delay between two effective waves */
3106: /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3107: and mw[mi+1][i]. dh depends on stepm.*/
3108: newm=savm;
3109: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
3110: cov[2]=agexact;
3111: if(nagesqr==1)
3112: cov[3]= agexact*agexact;
3113: for (kk=1; kk<=cptcovage;kk++) {
3114: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
3115: }
3116:
3117: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
3118: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
3119: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
3120: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
3121: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
3122: savm=oldm;
3123: oldm=newm;
3124: } /* end mult */
3125:
3126: s1=s[mw[mi][i]][i];
3127: s2=s[mw[mi+1][i]][i];
3128: /* if(s2==-1){ */
3129: /* printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
3130: /* /\* exit(1); *\/ */
3131: /* } */
3132: bbh=(double)bh[mi][i]/(double)stepm;
3133: /* bias is positive if real duration
3134: * is higher than the multiple of stepm and negative otherwise.
3135: */
3136: if( s2 > nlstate && (mle <5) ){ /* Jackson */
3137: lli=log(out[s1][s2] - savm[s1][s2]);
3138: } else if ( s2==-1 ) { /* alive */
3139: for (j=1,survp=0. ; j<=nlstate; j++)
3140: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
3141: lli= log(survp);
3142: }else if (mle==1){
3143: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
3144: } else if(mle==2){
3145: 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 */
3146: } else if(mle==3){ /* exponential inter-extrapolation */
3147: 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 */
3148: } else if (mle==4){ /* mle=4 no inter-extrapolation */
3149: lli=log(out[s1][s2]); /* Original formula */
3150: } else{ /* mle=0 back to 1 */
3151: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
3152: /*lli=log(out[s1][s2]); */ /* Original formula */
3153: } /* End of if */
3154: ipmx +=1;
3155: sw += weight[i];
3156: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
3157: /*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]); */
3158: if(globpr){
3159: fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
3160: %11.6f %11.6f %11.6f ", \
3161: num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
3162: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
3163: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
3164: llt +=ll[k]*gipmx/gsw;
3165: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
3166: }
3167: fprintf(ficresilk," %10.6f\n", -llt);
3168: }
3169: } /* end of wave */
3170: } /* end of individual */
3171: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
3172: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
3173: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
3174: if(globpr==0){ /* First time we count the contributions and weights */
3175: gipmx=ipmx;
3176: gsw=sw;
3177: }
3178: return -l;
3179: }
3180:
3181:
3182: /*************** function likelione ***********/
3183: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
3184: {
3185: /* This routine should help understanding what is done with
3186: the selection of individuals/waves and
3187: to check the exact contribution to the likelihood.
3188: Plotting could be done.
3189: */
3190: int k;
3191:
3192: if(*globpri !=0){ /* Just counts and sums, no printings */
3193: strcpy(fileresilk,"ILK_");
3194: strcat(fileresilk,fileresu);
3195: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
3196: printf("Problem with resultfile: %s\n", fileresilk);
3197: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
3198: }
3199: 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");
3200: fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
3201: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
3202: for(k=1; k<=nlstate; k++)
3203: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
3204: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
3205: }
3206:
3207: *fretone=(*funcone)(p);
3208: if(*globpri !=0){
3209: fclose(ficresilk);
3210: if (mle ==0)
3211: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
3212: else if(mle >=1)
3213: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
3214: 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));
3215:
3216:
3217: for (k=1; k<= nlstate ; k++) {
3218: 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> \
3219: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
3220: }
3221: 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> \
3222: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
3223: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
3224: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
3225: fflush(fichtm);
3226: }
3227: return;
3228: }
3229:
3230:
3231: /*********** Maximum Likelihood Estimation ***************/
3232:
3233: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
3234: {
3235: int i,j, iter=0;
3236: double **xi;
3237: double fret;
3238: double fretone; /* Only one call to likelihood */
3239: /* char filerespow[FILENAMELENGTH];*/
3240:
3241: #ifdef NLOPT
3242: int creturn;
3243: nlopt_opt opt;
3244: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
3245: double *lb;
3246: double minf; /* the minimum objective value, upon return */
3247: double * p1; /* Shifted parameters from 0 instead of 1 */
3248: myfunc_data dinst, *d = &dinst;
3249: #endif
3250:
3251:
3252: xi=matrix(1,npar,1,npar);
3253: for (i=1;i<=npar;i++)
3254: for (j=1;j<=npar;j++)
3255: xi[i][j]=(i==j ? 1.0 : 0.0);
3256: printf("Powell\n"); fprintf(ficlog,"Powell\n");
3257: strcpy(filerespow,"POW_");
3258: strcat(filerespow,fileres);
3259: if((ficrespow=fopen(filerespow,"w"))==NULL) {
3260: printf("Problem with resultfile: %s\n", filerespow);
3261: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
3262: }
3263: fprintf(ficrespow,"# Powell\n# iter -2*LL");
3264: for (i=1;i<=nlstate;i++)
3265: for(j=1;j<=nlstate+ndeath;j++)
3266: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
3267: fprintf(ficrespow,"\n");
3268: #ifdef POWELL
3269: powell(p,xi,npar,ftol,&iter,&fret,func);
3270: #endif
3271:
3272: #ifdef NLOPT
3273: #ifdef NEWUOA
3274: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
3275: #else
3276: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
3277: #endif
3278: lb=vector(0,npar-1);
3279: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
3280: nlopt_set_lower_bounds(opt, lb);
3281: nlopt_set_initial_step1(opt, 0.1);
3282:
3283: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
3284: d->function = func;
3285: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
3286: nlopt_set_min_objective(opt, myfunc, d);
3287: nlopt_set_xtol_rel(opt, ftol);
3288: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
3289: printf("nlopt failed! %d\n",creturn);
3290: }
3291: else {
3292: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
3293: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
3294: iter=1; /* not equal */
3295: }
3296: nlopt_destroy(opt);
3297: #endif
3298: free_matrix(xi,1,npar,1,npar);
3299: fclose(ficrespow);
3300: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3301: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3302: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
3303:
3304: }
3305:
3306: /**** Computes Hessian and covariance matrix ***/
3307: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
3308: {
3309: double **a,**y,*x,pd;
3310: /* double **hess; */
3311: int i, j;
3312: int *indx;
3313:
3314: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
3315: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
3316: void lubksb(double **a, int npar, int *indx, double b[]) ;
3317: void ludcmp(double **a, int npar, int *indx, double *d) ;
3318: double gompertz(double p[]);
3319: /* hess=matrix(1,npar,1,npar); */
3320:
3321: printf("\nCalculation of the hessian matrix. Wait...\n");
3322: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
3323: for (i=1;i<=npar;i++){
3324: printf("%d-",i);fflush(stdout);
3325: fprintf(ficlog,"%d-",i);fflush(ficlog);
3326:
3327: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
3328:
3329: /* printf(" %f ",p[i]);
3330: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
3331: }
3332:
3333: for (i=1;i<=npar;i++) {
3334: for (j=1;j<=npar;j++) {
3335: if (j>i) {
3336: printf(".%d-%d",i,j);fflush(stdout);
3337: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
3338: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
3339:
3340: hess[j][i]=hess[i][j];
3341: /*printf(" %lf ",hess[i][j]);*/
3342: }
3343: }
3344: }
3345: printf("\n");
3346: fprintf(ficlog,"\n");
3347:
3348: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
3349: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
3350:
3351: a=matrix(1,npar,1,npar);
3352: y=matrix(1,npar,1,npar);
3353: x=vector(1,npar);
3354: indx=ivector(1,npar);
3355: for (i=1;i<=npar;i++)
3356: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
3357: ludcmp(a,npar,indx,&pd);
3358:
3359: for (j=1;j<=npar;j++) {
3360: for (i=1;i<=npar;i++) x[i]=0;
3361: x[j]=1;
3362: lubksb(a,npar,indx,x);
3363: for (i=1;i<=npar;i++){
3364: matcov[i][j]=x[i];
3365: }
3366: }
3367:
3368: printf("\n#Hessian matrix#\n");
3369: fprintf(ficlog,"\n#Hessian matrix#\n");
3370: for (i=1;i<=npar;i++) {
3371: for (j=1;j<=npar;j++) {
3372: printf("%.6e ",hess[i][j]);
3373: fprintf(ficlog,"%.6e ",hess[i][j]);
3374: }
3375: printf("\n");
3376: fprintf(ficlog,"\n");
3377: }
3378:
3379: /* printf("\n#Covariance matrix#\n"); */
3380: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
3381: /* for (i=1;i<=npar;i++) { */
3382: /* for (j=1;j<=npar;j++) { */
3383: /* printf("%.6e ",matcov[i][j]); */
3384: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
3385: /* } */
3386: /* printf("\n"); */
3387: /* fprintf(ficlog,"\n"); */
3388: /* } */
3389:
3390: /* Recompute Inverse */
3391: /* for (i=1;i<=npar;i++) */
3392: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
3393: /* ludcmp(a,npar,indx,&pd); */
3394:
3395: /* printf("\n#Hessian matrix recomputed#\n"); */
3396:
3397: /* for (j=1;j<=npar;j++) { */
3398: /* for (i=1;i<=npar;i++) x[i]=0; */
3399: /* x[j]=1; */
3400: /* lubksb(a,npar,indx,x); */
3401: /* for (i=1;i<=npar;i++){ */
3402: /* y[i][j]=x[i]; */
3403: /* printf("%.3e ",y[i][j]); */
3404: /* fprintf(ficlog,"%.3e ",y[i][j]); */
3405: /* } */
3406: /* printf("\n"); */
3407: /* fprintf(ficlog,"\n"); */
3408: /* } */
3409:
3410: /* Verifying the inverse matrix */
3411: #ifdef DEBUGHESS
3412: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
3413:
3414: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
3415: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
3416:
3417: for (j=1;j<=npar;j++) {
3418: for (i=1;i<=npar;i++){
3419: printf("%.2f ",y[i][j]);
3420: fprintf(ficlog,"%.2f ",y[i][j]);
3421: }
3422: printf("\n");
3423: fprintf(ficlog,"\n");
3424: }
3425: #endif
3426:
3427: free_matrix(a,1,npar,1,npar);
3428: free_matrix(y,1,npar,1,npar);
3429: free_vector(x,1,npar);
3430: free_ivector(indx,1,npar);
3431: /* free_matrix(hess,1,npar,1,npar); */
3432:
3433:
3434: }
3435:
3436: /*************** hessian matrix ****************/
3437: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
3438: { /* Around values of x, computes the function func and returns the scales delti and hessian */
3439: int i;
3440: int l=1, lmax=20;
3441: double k1,k2, res, fx;
3442: double p2[MAXPARM+1]; /* identical to x */
3443: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
3444: int k=0,kmax=10;
3445: double l1;
3446:
3447: fx=func(x);
3448: for (i=1;i<=npar;i++) p2[i]=x[i];
3449: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
3450: l1=pow(10,l);
3451: delts=delt;
3452: for(k=1 ; k <kmax; k=k+1){
3453: delt = delta*(l1*k);
3454: p2[theta]=x[theta] +delt;
3455: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
3456: p2[theta]=x[theta]-delt;
3457: k2=func(p2)-fx;
3458: /*res= (k1-2.0*fx+k2)/delt/delt; */
3459: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
3460:
3461: #ifdef DEBUGHESSII
3462: 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);
3463: 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);
3464: #endif
3465: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3466: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3467: k=kmax;
3468: }
3469: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
3470: k=kmax; l=lmax*10;
3471: }
3472: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3473: delts=delt;
3474: }
3475: } /* End loop k */
3476: }
3477: delti[theta]=delts;
3478: return res;
3479:
3480: }
3481:
3482: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
3483: {
3484: int i;
3485: int l=1, lmax=20;
3486: double k1,k2,k3,k4,res,fx;
3487: double p2[MAXPARM+1];
3488: int k, kmax=1;
3489: double v1, v2, cv12, lc1, lc2;
3490:
3491: int firstime=0;
3492:
3493: fx=func(x);
3494: for (k=1; k<=kmax; k=k+10) {
3495: for (i=1;i<=npar;i++) p2[i]=x[i];
3496: p2[thetai]=x[thetai]+delti[thetai]*k;
3497: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3498: k1=func(p2)-fx;
3499:
3500: p2[thetai]=x[thetai]+delti[thetai]*k;
3501: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3502: k2=func(p2)-fx;
3503:
3504: p2[thetai]=x[thetai]-delti[thetai]*k;
3505: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3506: k3=func(p2)-fx;
3507:
3508: p2[thetai]=x[thetai]-delti[thetai]*k;
3509: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3510: k4=func(p2)-fx;
3511: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3512: if(k1*k2*k3*k4 <0.){
3513: firstime=1;
3514: kmax=kmax+10;
3515: }
3516: if(kmax >=10 || firstime ==1){
3517: 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);
3518: 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);
3519: 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);
3520: 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);
3521: }
3522: #ifdef DEBUGHESSIJ
3523: v1=hess[thetai][thetai];
3524: v2=hess[thetaj][thetaj];
3525: cv12=res;
3526: /* Computing eigen value of Hessian matrix */
3527: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3528: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3529: if ((lc2 <0) || (lc1 <0) ){
3530: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3531: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3532: 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);
3533: 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);
3534: }
3535: #endif
3536: }
3537: return res;
3538: }
3539:
3540: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3541: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3542: /* { */
3543: /* int i; */
3544: /* int l=1, lmax=20; */
3545: /* double k1,k2,k3,k4,res,fx; */
3546: /* double p2[MAXPARM+1]; */
3547: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3548: /* int k=0,kmax=10; */
3549: /* double l1; */
3550:
3551: /* fx=func(x); */
3552: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3553: /* l1=pow(10,l); */
3554: /* delts=delt; */
3555: /* for(k=1 ; k <kmax; k=k+1){ */
3556: /* delt = delti*(l1*k); */
3557: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3558: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3559: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3560: /* k1=func(p2)-fx; */
3561:
3562: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3563: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3564: /* k2=func(p2)-fx; */
3565:
3566: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3567: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3568: /* k3=func(p2)-fx; */
3569:
3570: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3571: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3572: /* k4=func(p2)-fx; */
3573: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3574: /* #ifdef DEBUGHESSIJ */
3575: /* 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); */
3576: /* 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); */
3577: /* #endif */
3578: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3579: /* k=kmax; */
3580: /* } */
3581: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3582: /* k=kmax; l=lmax*10; */
3583: /* } */
3584: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3585: /* delts=delt; */
3586: /* } */
3587: /* } /\* End loop k *\/ */
3588: /* } */
3589: /* delti[theta]=delts; */
3590: /* return res; */
3591: /* } */
3592:
3593:
3594: /************** Inverse of matrix **************/
3595: void ludcmp(double **a, int n, int *indx, double *d)
3596: {
3597: int i,imax,j,k;
3598: double big,dum,sum,temp;
3599: double *vv;
3600:
3601: vv=vector(1,n);
3602: *d=1.0;
3603: for (i=1;i<=n;i++) {
3604: big=0.0;
3605: for (j=1;j<=n;j++)
3606: if ((temp=fabs(a[i][j])) > big) big=temp;
3607: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3608: vv[i]=1.0/big;
3609: }
3610: for (j=1;j<=n;j++) {
3611: for (i=1;i<j;i++) {
3612: sum=a[i][j];
3613: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3614: a[i][j]=sum;
3615: }
3616: big=0.0;
3617: for (i=j;i<=n;i++) {
3618: sum=a[i][j];
3619: for (k=1;k<j;k++)
3620: sum -= a[i][k]*a[k][j];
3621: a[i][j]=sum;
3622: if ( (dum=vv[i]*fabs(sum)) >= big) {
3623: big=dum;
3624: imax=i;
3625: }
3626: }
3627: if (j != imax) {
3628: for (k=1;k<=n;k++) {
3629: dum=a[imax][k];
3630: a[imax][k]=a[j][k];
3631: a[j][k]=dum;
3632: }
3633: *d = -(*d);
3634: vv[imax]=vv[j];
3635: }
3636: indx[j]=imax;
3637: if (a[j][j] == 0.0) a[j][j]=TINY;
3638: if (j != n) {
3639: dum=1.0/(a[j][j]);
3640: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3641: }
3642: }
3643: free_vector(vv,1,n); /* Doesn't work */
3644: ;
3645: }
3646:
3647: void lubksb(double **a, int n, int *indx, double b[])
3648: {
3649: int i,ii=0,ip,j;
3650: double sum;
3651:
3652: for (i=1;i<=n;i++) {
3653: ip=indx[i];
3654: sum=b[ip];
3655: b[ip]=b[i];
3656: if (ii)
3657: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3658: else if (sum) ii=i;
3659: b[i]=sum;
3660: }
3661: for (i=n;i>=1;i--) {
3662: sum=b[i];
3663: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3664: b[i]=sum/a[i][i];
3665: }
3666: }
3667:
3668: void pstamp(FILE *fichier)
3669: {
3670: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3671: }
3672:
3673: /************ Frequencies ********************/
3674: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
3675: int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
3676: int firstpass, int lastpass, int stepm, int weightopt, char model[])
3677: { /* Some frequencies */
3678:
3679: int i, m, jk, j1, bool, z1,j;
3680: int mi; /* Effective wave */
3681: int first;
3682: double ***freq; /* Frequencies */
3683: double *pp, **prop;
3684: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3685: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
3686: double agebegin, ageend;
3687:
3688: pp=vector(1,nlstate);
3689: prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
3690: /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
3691: strcpy(fileresp,"P_");
3692: strcat(fileresp,fileresu);
3693: /*strcat(fileresphtm,fileresu);*/
3694: if((ficresp=fopen(fileresp,"w"))==NULL) {
3695: printf("Problem with prevalence resultfile: %s\n", fileresp);
3696: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3697: exit(0);
3698: }
3699:
3700: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
3701: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
3702: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3703: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3704: fflush(ficlog);
3705: exit(70);
3706: }
3707: else{
3708: fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3709: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3710: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3711: fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3712: }
3713: fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
3714:
3715: strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
3716: if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
3717: printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3718: fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3719: fflush(ficlog);
3720: exit(70);
3721: }
3722: else{
3723: fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3724: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3725: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3726: fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3727: }
3728: 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);
3729:
3730: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
3731: j1=0;
3732:
3733: j=cptcoveff;
3734: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3735:
3736: first=1;
3737:
3738: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
3739: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3740: scanf("%d", i);*/
3741: for (i=-5; i<=nlstate+ndeath; i++)
3742: for (jk=-5; jk<=nlstate+ndeath; jk++)
3743: for(m=iagemin; m <= iagemax+3; m++)
3744: freq[i][jk][m]=0;
3745:
3746: for (i=1; i<=nlstate; i++)
3747: for(m=iagemin; m <= iagemax+3; m++)
3748: prop[i][m]=0;
3749:
3750: dateintsum=0;
3751: k2cpt=0;
3752: for (i=1; i<=imx; i++) { /* For each individual i */
3753: bool=1;
3754: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3755: for (z1=1; z1<=cptcoveff; z1++)
3756: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3757: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3758: bool=0;
3759: /* 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",
3760: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3761: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3762: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3763: }
3764: } /* cptcovn > 0 */
3765:
3766: if (bool==1){
3767: /* for(m=firstpass; m<=lastpass; m++){ */
3768: for(mi=1; mi<wav[i];mi++){
3769: m=mw[mi][i];
3770: /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
3771: and mw[mi+1][i]. dh depends on stepm. */
3772: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3773: ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
3774: if(m >=firstpass && m <=lastpass){
3775: k2=anint[m][i]+(mint[m][i]/12.);
3776: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3777: if(agev[m][i]==0) agev[m][i]=iagemax+1; /* All ages equal to 0 are in iagemax+1 */
3778: if(agev[m][i]==1) agev[m][i]=iagemax+2; /* All ages equal to 1 are in iagemax+2 */
3779: if (s[m][i]>0 && s[m][i]<=nlstate) /* If status at wave m is known and a live state */
3780: prop[s[m][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3781: if (m<lastpass) {
3782: /* if(s[m][i]==4 && s[m+1][i]==4) */
3783: /* printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
3784: if(s[m][i]==-1)
3785: printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
3786: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3787: /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
3788: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
3789: }
3790: }
3791: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
3792: dateintsum=dateintsum+k2;
3793: k2cpt++;
3794: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
3795: }
3796: /*}*/
3797: } /* end m */
3798: } /* end bool */
3799: } /* end i = 1 to imx */
3800:
3801: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3802: pstamp(ficresp);
3803: if (cptcovn>0) {
3804: fprintf(ficresp, "\n#********** Variable ");
3805: fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable ");
3806: fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable ");
3807: for (z1=1; z1<=cptcoveff; z1++){
3808: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3809: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3810: fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3811: }
3812: fprintf(ficresp, "**********\n#");
3813: fprintf(ficresphtm, "**********</h3>\n");
3814: fprintf(ficresphtmfr, "**********</h3>\n");
3815: fprintf(ficlog, "\n#********** Variable ");
3816: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3817: fprintf(ficlog, "**********\n");
3818: }
3819: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
3820: for(i=1; i<=nlstate;i++) {
3821: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3822: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
3823: }
3824: fprintf(ficresp, "\n");
3825: fprintf(ficresphtm, "\n");
3826:
3827: /* Header of frequency table by age */
3828: fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
3829: fprintf(ficresphtmfr,"<th>Age</th> ");
3830: for(jk=-1; jk <=nlstate+ndeath; jk++){
3831: for(m=-1; m <=nlstate+ndeath; m++){
3832: if(jk!=0 && m!=0)
3833: fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
3834: }
3835: }
3836: fprintf(ficresphtmfr, "\n");
3837:
3838: /* For each age */
3839: for(i=iagemin; i <= iagemax+3; i++){
3840: fprintf(ficresphtm,"<tr>");
3841: if(i==iagemax+1){
3842: fprintf(ficlog,"1");
3843: fprintf(ficresphtmfr,"<tr><th>0</th> ");
3844: }else if(i==iagemax+2){
3845: fprintf(ficlog,"0");
3846: fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
3847: }else if(i==iagemax+3){
3848: fprintf(ficlog,"Total");
3849: fprintf(ficresphtmfr,"<tr><th>Total</th> ");
3850: }else{
3851: if(first==1){
3852: first=0;
3853: printf("See log file for details...\n");
3854: }
3855: fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
3856: fprintf(ficlog,"Age %d", i);
3857: }
3858: for(jk=1; jk <=nlstate ; jk++){
3859: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3860: pp[jk] += freq[jk][m][i];
3861: }
3862: for(jk=1; jk <=nlstate ; jk++){
3863: for(m=-1, pos=0; m <=0 ; m++)
3864: pos += freq[jk][m][i];
3865: if(pp[jk]>=1.e-10){
3866: if(first==1){
3867: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3868: }
3869: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3870: }else{
3871: if(first==1)
3872: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3873: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3874: }
3875: }
3876:
3877: for(jk=1; jk <=nlstate ; jk++){
3878: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3879: pp[jk] += freq[jk][m][i];
3880: }
3881: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3882: pos += pp[jk];
3883: posprop += prop[jk][i];
3884: }
3885: for(jk=1; jk <=nlstate ; jk++){
3886: if(pos>=1.e-5){
3887: if(first==1)
3888: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3889: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3890: }else{
3891: if(first==1)
3892: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3893: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3894: }
3895: if( i <= iagemax){
3896: if(pos>=1.e-5){
3897: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3898: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3899: /*probs[i][jk][j1]= pp[jk]/pos;*/
3900: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3901: }
3902: else{
3903: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3904: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
3905: }
3906: }
3907: }
3908:
3909: for(jk=-1; jk <=nlstate+ndeath; jk++){
3910: for(m=-1; m <=nlstate+ndeath; m++){
3911: if(freq[jk][m][i] !=0 ) { /* minimizing output */
3912: if(first==1){
3913: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3914: }
3915: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3916: }
3917: if(jk!=0 && m!=0)
3918: fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
3919: }
3920: }
3921: fprintf(ficresphtmfr,"</tr>\n ");
3922: if(i <= iagemax){
3923: fprintf(ficresp,"\n");
3924: fprintf(ficresphtm,"</tr>\n");
3925: }
3926: if(first==1)
3927: printf("Others in log...\n");
3928: fprintf(ficlog,"\n");
3929: } /* end loop i */
3930: fprintf(ficresphtm,"</table>\n");
3931: fprintf(ficresphtmfr,"</table>\n");
3932: /*}*/
3933: } /* end j1 */
3934: dateintmean=dateintsum/k2cpt;
3935:
3936: fclose(ficresp);
3937: fclose(ficresphtm);
3938: fclose(ficresphtmfr);
3939: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
3940: free_vector(pp,1,nlstate);
3941: free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
3942: /* End of Freq */
3943: }
3944:
3945: /************ Prevalence ********************/
3946: 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)
3947: {
3948: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3949: in each health status at the date of interview (if between dateprev1 and dateprev2).
3950: We still use firstpass and lastpass as another selection.
3951: */
3952:
3953: int i, m, jk, j1, bool, z1,j;
3954: int mi; /* Effective wave */
3955: int iage;
3956: double agebegin, ageend;
3957:
3958: double **prop;
3959: double posprop;
3960: double y2; /* in fractional years */
3961: int iagemin, iagemax;
3962: int first; /** to stop verbosity which is redirected to log file */
3963:
3964: iagemin= (int) agemin;
3965: iagemax= (int) agemax;
3966: /*pp=vector(1,nlstate);*/
3967: prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
3968: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3969: j1=0;
3970:
3971: /*j=cptcoveff;*/
3972: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3973:
3974: first=1;
3975: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
3976: for (i=1; i<=nlstate; i++)
3977: for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
3978: prop[i][iage]=0.0;
3979:
3980: for (i=1; i<=imx; i++) { /* Each individual */
3981: bool=1;
3982: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3983: for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
3984: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3985: bool=0;
3986: }
3987: if (bool==1) { /* For this combination of covariates values, this individual fits */
3988: /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
3989: for(mi=1; mi<wav[i];mi++){
3990: m=mw[mi][i];
3991: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3992: /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
3993: if(m >=firstpass && m <=lastpass){
3994: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3995: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3996: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3997: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3998: if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
3999: 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);
4000: exit(1);
4001: }
4002: if (s[m][i]>0 && s[m][i]<=nlstate) {
4003: /*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]]);*/
4004: prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
4005: prop[s[m][i]][iagemax+3] += weight[i];
4006: } /* end valid statuses */
4007: } /* end selection of dates */
4008: } /* end selection of waves */
4009: } /* end effective waves */
4010: } /* end bool */
4011: }
4012: for(i=iagemin; i <= iagemax+3; i++){
4013: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
4014: posprop += prop[jk][i];
4015: }
4016:
4017: for(jk=1; jk <=nlstate ; jk++){
4018: if( i <= iagemax){
4019: if(posprop>=1.e-5){
4020: probs[i][jk][j1]= prop[jk][i]/posprop;
4021: } else{
4022: if(first==1){
4023: first=0;
4024: printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
4025: }
4026: }
4027: }
4028: }/* end jk */
4029: }/* end i */
4030: /*} *//* end i1 */
4031: } /* end j1 */
4032:
4033: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
4034: /*free_vector(pp,1,nlstate);*/
4035: free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
4036: } /* End of prevalence */
4037:
4038: /************* Waves Concatenation ***************/
4039:
4040: 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)
4041: {
4042: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
4043: Death is a valid wave (if date is known).
4044: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
4045: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
4046: and mw[mi+1][i]. dh depends on stepm.
4047: */
4048:
4049: int i, mi, m;
4050: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
4051: double sum=0., jmean=0.;*/
4052: int first, firstwo, firsthree, firstfour;
4053: int j, k=0,jk, ju, jl;
4054: double sum=0.;
4055: first=0;
4056: firstwo=0;
4057: firsthree=0;
4058: firstfour=0;
4059: jmin=100000;
4060: jmax=-1;
4061: jmean=0.;
4062: for(i=1; i<=imx; i++){ /* For simple cases and if state is death */
4063: mi=0;
4064: m=firstpass;
4065: while(s[m][i] <= nlstate){ /* a live state */
4066: 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 */
4067: mw[++mi][i]=m;
4068: }
4069: if(m >=lastpass){
4070: if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
4071: if(firsthree == 0){
4072: printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
4073: firsthree=1;
4074: }
4075: 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.\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);
4076: mw[++mi][i]=m;
4077: }
4078: if(s[m][i]==-2){ /* Vital status is really unknown */
4079: nbwarn++;
4080: if((int)anint[m][i] == 9999){ /* Has the vital status really been verified? */
4081: 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);
4082: fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
4083: }
4084: break;
4085: }
4086: break;
4087: }
4088: else
4089: m++;
4090: }/* end while */
4091:
4092: /* After last pass */
4093: if (s[m][i] > nlstate){ /* In a death state */
4094: mi++; /* Death is another wave */
4095: /* if(mi==0) never been interviewed correctly before death */
4096: /* Only death is a correct wave */
4097: mw[mi][i]=m;
4098: }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
4099: /* m++; */
4100: /* mi++; */
4101: /* s[m][i]=nlstate+1; /\* We are setting the status to the last of non live state *\/ */
4102: /* mw[mi][i]=m; */
4103: nberr++;
4104: if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
4105: if(firstwo==0){
4106: printf("Error! Death for individual %ld line=%d occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4107: firstwo=1;
4108: }
4109: fprintf(ficlog,"Error! Death for individual %ld line=%d occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
4110: }else{ /* end date of interview is known */
4111: /* death is known but not confirmed by death status at any wave */
4112: if(firstfour==0){
4113: 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 );
4114: firstfour=1;
4115: }
4116: 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 );
4117: }
4118: }
4119: wav[i]=mi;
4120: if(mi==0){
4121: nbwarn++;
4122: if(first==0){
4123: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
4124: first=1;
4125: }
4126: if(first==1){
4127: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
4128: }
4129: } /* end mi==0 */
4130: } /* End individuals */
4131: /* wav and mw are no more changed */
4132:
4133:
4134: for(i=1; i<=imx; i++){
4135: for(mi=1; mi<wav[i];mi++){
4136: if (stepm <=0)
4137: dh[mi][i]=1;
4138: else{
4139: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
4140: if (agedc[i] < 2*AGESUP) {
4141: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
4142: if(j==0) j=1; /* Survives at least one month after exam */
4143: else if(j<0){
4144: nberr++;
4145: 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]);
4146: j=1; /* Temporary Dangerous patch */
4147: 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);
4148: 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]);
4149: 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);
4150: }
4151: k=k+1;
4152: if (j >= jmax){
4153: jmax=j;
4154: ijmax=i;
4155: }
4156: if (j <= jmin){
4157: jmin=j;
4158: ijmin=i;
4159: }
4160: sum=sum+j;
4161: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
4162: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
4163: }
4164: }
4165: else{
4166: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
4167: /* 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]); */
4168:
4169: k=k+1;
4170: if (j >= jmax) {
4171: jmax=j;
4172: ijmax=i;
4173: }
4174: else if (j <= jmin){
4175: jmin=j;
4176: ijmin=i;
4177: }
4178: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
4179: /*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]);*/
4180: if(j<0){
4181: nberr++;
4182: 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]);
4183: 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]);
4184: }
4185: sum=sum+j;
4186: }
4187: jk= j/stepm;
4188: jl= j -jk*stepm;
4189: ju= j -(jk+1)*stepm;
4190: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
4191: if(jl==0){
4192: dh[mi][i]=jk;
4193: bh[mi][i]=0;
4194: }else{ /* We want a negative bias in order to only have interpolation ie
4195: * to avoid the price of an extra matrix product in likelihood */
4196: dh[mi][i]=jk+1;
4197: bh[mi][i]=ju;
4198: }
4199: }else{
4200: if(jl <= -ju){
4201: dh[mi][i]=jk;
4202: bh[mi][i]=jl; /* bias is positive if real duration
4203: * is higher than the multiple of stepm and negative otherwise.
4204: */
4205: }
4206: else{
4207: dh[mi][i]=jk+1;
4208: bh[mi][i]=ju;
4209: }
4210: if(dh[mi][i]==0){
4211: dh[mi][i]=1; /* At least one step */
4212: bh[mi][i]=ju; /* At least one step */
4213: /* 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);*/
4214: }
4215: } /* end if mle */
4216: }
4217: } /* end wave */
4218: }
4219: jmean=sum/k;
4220: 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);
4221: 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);
4222: }
4223:
4224: /*********** Tricode ****************************/
4225: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
4226: {
4227: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
4228: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
4229: * Boring subroutine which should only output nbcode[Tvar[j]][k]
4230: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
4231: * nbcode[Tvar[j]][1]=
4232: */
4233:
4234: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
4235: int modmaxcovj=0; /* Modality max of covariates j */
4236: int cptcode=0; /* Modality max of covariates j */
4237: int modmincovj=0; /* Modality min of covariates j */
4238:
4239:
4240: cptcoveff=0;
4241:
4242: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
4243:
4244: /* Loop on covariates without age and products */
4245: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
4246: for (k=-1; k < maxncov; k++) Ndum[k]=0;
4247: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
4248: modality of this covariate Vj*/
4249: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
4250: * If product of Vn*Vm, still boolean *:
4251: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
4252: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
4253: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
4254: modality of the nth covariate of individual i. */
4255: if (ij > modmaxcovj)
4256: modmaxcovj=ij;
4257: else if (ij < modmincovj)
4258: modmincovj=ij;
4259: if ((ij < -1) && (ij > NCOVMAX)){
4260: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
4261: exit(1);
4262: }else
4263: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
4264: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
4265: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
4266: /* getting the maximum value of the modality of the covariate
4267: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
4268: female is 1, then modmaxcovj=1.*/
4269: } /* end for loop on individuals i */
4270: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
4271: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
4272: cptcode=modmaxcovj;
4273: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
4274: /*for (i=0; i<=cptcode; i++) {*/
4275: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
4276: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
4277: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
4278: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
4279: if( k != -1){
4280: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
4281: covariate for which somebody answered excluding
4282: undefined. Usually 2: 0 and 1. */
4283: }
4284: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
4285: covariate for which somebody answered including
4286: undefined. Usually 3: -1, 0 and 1. */
4287: }
4288: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
4289: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
4290: } /* Ndum[-1] number of undefined modalities */
4291:
4292: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
4293: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
4294: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
4295: modmincovj=3; modmaxcovj = 7;
4296: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
4297: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
4298: defining two dummy variables: variables V1_1 and V1_2.
4299: nbcode[Tvar[j]][ij]=k;
4300: nbcode[Tvar[j]][1]=0;
4301: nbcode[Tvar[j]][2]=1;
4302: nbcode[Tvar[j]][3]=2;
4303: To be continued (not working yet).
4304: */
4305: ij=0; /* ij is similar to i but can jump over null modalities */
4306: 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*/
4307: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
4308: break;
4309: }
4310: ij++;
4311: nbcode[Tvar[j]][ij]=i; /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
4312: cptcode = ij; /* New max modality for covar j */
4313: } /* end of loop on modality i=-1 to 1 or more */
4314:
4315: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
4316: /* /\*recode from 0 *\/ */
4317: /* k is a modality. If we have model=V1+V1*sex */
4318: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
4319: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
4320: /* } */
4321: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
4322: /* if (ij > ncodemax[j]) { */
4323: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
4324: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
4325: /* break; */
4326: /* } */
4327: /* } /\* end of loop on modality k *\/ */
4328: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
4329:
4330: for (k=-1; k< maxncov; k++) Ndum[k]=0;
4331:
4332: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
4333: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
4334: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
4335: Ndum[ij]++; /* Might be supersed V1 + V1*age */
4336: }
4337:
4338: ij=0;
4339: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
4340: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
4341: if((Ndum[i]!=0) && (i<=ncovcol)){
4342: ij++;
4343: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
4344: Tvaraff[ij]=i; /*For printing (unclear) */
4345: }else{
4346: /* Tvaraff[ij]=0; */
4347: }
4348: }
4349: /* ij--; */
4350: cptcoveff=ij; /*Number of total covariates*/
4351:
4352: }
4353:
4354:
4355: /*********** Health Expectancies ****************/
4356:
4357: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
4358:
4359: {
4360: /* Health expectancies, no variances */
4361: int i, j, nhstepm, hstepm, h, nstepm;
4362: int nhstepma, nstepma; /* Decreasing with age */
4363: double age, agelim, hf;
4364: double ***p3mat;
4365: double eip;
4366:
4367: pstamp(ficreseij);
4368: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
4369: fprintf(ficreseij,"# Age");
4370: for(i=1; i<=nlstate;i++){
4371: for(j=1; j<=nlstate;j++){
4372: fprintf(ficreseij," e%1d%1d ",i,j);
4373: }
4374: fprintf(ficreseij," e%1d. ",i);
4375: }
4376: fprintf(ficreseij,"\n");
4377:
4378:
4379: if(estepm < stepm){
4380: printf ("Problem %d lower than %d\n",estepm, stepm);
4381: }
4382: else hstepm=estepm;
4383: /* We compute the life expectancy from trapezoids spaced every estepm months
4384: * This is mainly to measure the difference between two models: for example
4385: * if stepm=24 months pijx are given only every 2 years and by summing them
4386: * we are calculating an estimate of the Life Expectancy assuming a linear
4387: * progression in between and thus overestimating or underestimating according
4388: * to the curvature of the survival function. If, for the same date, we
4389: * estimate the model with stepm=1 month, we can keep estepm to 24 months
4390: * to compare the new estimate of Life expectancy with the same linear
4391: * hypothesis. A more precise result, taking into account a more precise
4392: * curvature will be obtained if estepm is as small as stepm. */
4393:
4394: /* For example we decided to compute the life expectancy with the smallest unit */
4395: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4396: nhstepm is the number of hstepm from age to agelim
4397: nstepm is the number of stepm from age to agelin.
4398: Look at hpijx to understand the reason of that which relies in memory size
4399: and note for a fixed period like estepm months */
4400: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4401: survival function given by stepm (the optimization length). Unfortunately it
4402: means that if the survival funtion is printed only each two years of age and if
4403: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4404: results. So we changed our mind and took the option of the best precision.
4405: */
4406: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4407:
4408: agelim=AGESUP;
4409: /* If stepm=6 months */
4410: /* Computed by stepm unit matrices, product of hstepm matrices, stored
4411: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
4412:
4413: /* nhstepm age range expressed in number of stepm */
4414: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4415: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4416: /* if (stepm >= YEARM) hstepm=1;*/
4417: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4418: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4419:
4420: for (age=bage; age<=fage; age ++){
4421: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4422: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4423: /* if (stepm >= YEARM) hstepm=1;*/
4424: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
4425:
4426: /* If stepm=6 months */
4427: /* Computed by stepm unit matrices, product of hstepma matrices, stored
4428: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
4429:
4430: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4431:
4432: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4433:
4434: printf("%d|",(int)age);fflush(stdout);
4435: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4436:
4437: /* Computing expectancies */
4438: for(i=1; i<=nlstate;i++)
4439: for(j=1; j<=nlstate;j++)
4440: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4441: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
4442:
4443: /* 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]);*/
4444:
4445: }
4446:
4447: fprintf(ficreseij,"%3.0f",age );
4448: for(i=1; i<=nlstate;i++){
4449: eip=0;
4450: for(j=1; j<=nlstate;j++){
4451: eip +=eij[i][j][(int)age];
4452: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
4453: }
4454: fprintf(ficreseij,"%9.4f", eip );
4455: }
4456: fprintf(ficreseij,"\n");
4457:
4458: }
4459: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4460: printf("\n");
4461: fprintf(ficlog,"\n");
4462:
4463: }
4464:
4465: 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[] )
4466:
4467: {
4468: /* Covariances of health expectancies eij and of total life expectancies according
4469: to initial status i, ei. .
4470: */
4471: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
4472: int nhstepma, nstepma; /* Decreasing with age */
4473: double age, agelim, hf;
4474: double ***p3matp, ***p3matm, ***varhe;
4475: double **dnewm,**doldm;
4476: double *xp, *xm;
4477: double **gp, **gm;
4478: double ***gradg, ***trgradg;
4479: int theta;
4480:
4481: double eip, vip;
4482:
4483: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
4484: xp=vector(1,npar);
4485: xm=vector(1,npar);
4486: dnewm=matrix(1,nlstate*nlstate,1,npar);
4487: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
4488:
4489: pstamp(ficresstdeij);
4490: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
4491: fprintf(ficresstdeij,"# Age");
4492: for(i=1; i<=nlstate;i++){
4493: for(j=1; j<=nlstate;j++)
4494: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
4495: fprintf(ficresstdeij," e%1d. ",i);
4496: }
4497: fprintf(ficresstdeij,"\n");
4498:
4499: pstamp(ficrescveij);
4500: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
4501: fprintf(ficrescveij,"# Age");
4502: for(i=1; i<=nlstate;i++)
4503: for(j=1; j<=nlstate;j++){
4504: cptj= (j-1)*nlstate+i;
4505: for(i2=1; i2<=nlstate;i2++)
4506: for(j2=1; j2<=nlstate;j2++){
4507: cptj2= (j2-1)*nlstate+i2;
4508: if(cptj2 <= cptj)
4509: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
4510: }
4511: }
4512: fprintf(ficrescveij,"\n");
4513:
4514: if(estepm < stepm){
4515: printf ("Problem %d lower than %d\n",estepm, stepm);
4516: }
4517: else hstepm=estepm;
4518: /* We compute the life expectancy from trapezoids spaced every estepm months
4519: * This is mainly to measure the difference between two models: for example
4520: * if stepm=24 months pijx are given only every 2 years and by summing them
4521: * we are calculating an estimate of the Life Expectancy assuming a linear
4522: * progression in between and thus overestimating or underestimating according
4523: * to the curvature of the survival function. If, for the same date, we
4524: * estimate the model with stepm=1 month, we can keep estepm to 24 months
4525: * to compare the new estimate of Life expectancy with the same linear
4526: * hypothesis. A more precise result, taking into account a more precise
4527: * curvature will be obtained if estepm is as small as stepm. */
4528:
4529: /* For example we decided to compute the life expectancy with the smallest unit */
4530: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4531: nhstepm is the number of hstepm from age to agelim
4532: nstepm is the number of stepm from age to agelin.
4533: Look at hpijx to understand the reason of that which relies in memory size
4534: and note for a fixed period like estepm months */
4535: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4536: survival function given by stepm (the optimization length). Unfortunately it
4537: means that if the survival funtion is printed only each two years of age and if
4538: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4539: results. So we changed our mind and took the option of the best precision.
4540: */
4541: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4542:
4543: /* If stepm=6 months */
4544: /* nhstepm age range expressed in number of stepm */
4545: agelim=AGESUP;
4546: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
4547: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4548: /* if (stepm >= YEARM) hstepm=1;*/
4549: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4550:
4551: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4552: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4553: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
4554: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
4555: gp=matrix(0,nhstepm,1,nlstate*nlstate);
4556: gm=matrix(0,nhstepm,1,nlstate*nlstate);
4557:
4558: for (age=bage; age<=fage; age ++){
4559: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4560: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4561: /* if (stepm >= YEARM) hstepm=1;*/
4562: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
4563:
4564: /* If stepm=6 months */
4565: /* Computed by stepm unit matrices, product of hstepma matrices, stored
4566: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
4567:
4568: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4569:
4570: /* Computing Variances of health expectancies */
4571: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
4572: decrease memory allocation */
4573: for(theta=1; theta <=npar; theta++){
4574: for(i=1; i<=npar; i++){
4575: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4576: xm[i] = x[i] - (i==theta ?delti[theta]:0);
4577: }
4578: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
4579: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
4580:
4581: for(j=1; j<= nlstate; j++){
4582: for(i=1; i<=nlstate; i++){
4583: for(h=0; h<=nhstepm-1; h++){
4584: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
4585: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
4586: }
4587: }
4588: }
4589:
4590: for(ij=1; ij<= nlstate*nlstate; ij++)
4591: for(h=0; h<=nhstepm-1; h++){
4592: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
4593: }
4594: }/* End theta */
4595:
4596:
4597: for(h=0; h<=nhstepm-1; h++)
4598: for(j=1; j<=nlstate*nlstate;j++)
4599: for(theta=1; theta <=npar; theta++)
4600: trgradg[h][j][theta]=gradg[h][theta][j];
4601:
4602:
4603: for(ij=1;ij<=nlstate*nlstate;ij++)
4604: for(ji=1;ji<=nlstate*nlstate;ji++)
4605: varhe[ij][ji][(int)age] =0.;
4606:
4607: printf("%d|",(int)age);fflush(stdout);
4608: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4609: for(h=0;h<=nhstepm-1;h++){
4610: for(k=0;k<=nhstepm-1;k++){
4611: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
4612: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
4613: for(ij=1;ij<=nlstate*nlstate;ij++)
4614: for(ji=1;ji<=nlstate*nlstate;ji++)
4615: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
4616: }
4617: }
4618:
4619: /* Computing expectancies */
4620: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4621: for(i=1; i<=nlstate;i++)
4622: for(j=1; j<=nlstate;j++)
4623: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4624: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
4625:
4626: /* 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]);*/
4627:
4628: }
4629:
4630: fprintf(ficresstdeij,"%3.0f",age );
4631: for(i=1; i<=nlstate;i++){
4632: eip=0.;
4633: vip=0.;
4634: for(j=1; j<=nlstate;j++){
4635: eip += eij[i][j][(int)age];
4636: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4637: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4638: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4639: }
4640: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4641: }
4642: fprintf(ficresstdeij,"\n");
4643:
4644: fprintf(ficrescveij,"%3.0f",age );
4645: for(i=1; i<=nlstate;i++)
4646: for(j=1; j<=nlstate;j++){
4647: cptj= (j-1)*nlstate+i;
4648: for(i2=1; i2<=nlstate;i2++)
4649: for(j2=1; j2<=nlstate;j2++){
4650: cptj2= (j2-1)*nlstate+i2;
4651: if(cptj2 <= cptj)
4652: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4653: }
4654: }
4655: fprintf(ficrescveij,"\n");
4656:
4657: }
4658: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4659: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4660: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4661: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4662: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4663: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4664: printf("\n");
4665: fprintf(ficlog,"\n");
4666:
4667: free_vector(xm,1,npar);
4668: free_vector(xp,1,npar);
4669: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4670: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4671: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4672: }
4673:
4674: /************ Variance ******************/
4675: 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[])
4676: {
4677: /* Variance of health expectancies */
4678: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4679: /* double **newm;*/
4680: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4681:
4682: /* int movingaverage(); */
4683: double **dnewm,**doldm;
4684: double **dnewmp,**doldmp;
4685: int i, j, nhstepm, hstepm, h, nstepm ;
4686: int k;
4687: double *xp;
4688: double **gp, **gm; /* for var eij */
4689: double ***gradg, ***trgradg; /*for var eij */
4690: double **gradgp, **trgradgp; /* for var p point j */
4691: double *gpp, *gmp; /* for var p point j */
4692: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4693: double ***p3mat;
4694: double age,agelim, hf;
4695: /* double ***mobaverage; */
4696: int theta;
4697: char digit[4];
4698: char digitp[25];
4699:
4700: char fileresprobmorprev[FILENAMELENGTH];
4701:
4702: if(popbased==1){
4703: if(mobilav!=0)
4704: strcpy(digitp,"-POPULBASED-MOBILAV_");
4705: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4706: }
4707: else
4708: strcpy(digitp,"-STABLBASED_");
4709:
4710: /* if (mobilav!=0) { */
4711: /* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
4712: /* if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
4713: /* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
4714: /* printf(" Error in movingaverage mobilav=%d\n",mobilav); */
4715: /* } */
4716: /* } */
4717:
4718: strcpy(fileresprobmorprev,"PRMORPREV-");
4719: sprintf(digit,"%-d",ij);
4720: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4721: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4722: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4723: strcat(fileresprobmorprev,fileresu);
4724: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4725: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4726: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4727: }
4728: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4729: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4730: pstamp(ficresprobmorprev);
4731: 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);
4732: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4733: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4734: fprintf(ficresprobmorprev," p.%-d SE",j);
4735: for(i=1; i<=nlstate;i++)
4736: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4737: }
4738: fprintf(ficresprobmorprev,"\n");
4739:
4740: fprintf(ficgp,"\n# Routine varevsij");
4741: fprintf(ficgp,"\nunset title \n");
4742: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4743: 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");
4744: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4745: /* } */
4746: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4747: pstamp(ficresvij);
4748: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4749: if(popbased==1)
4750: 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);
4751: else
4752: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4753: fprintf(ficresvij,"# Age");
4754: for(i=1; i<=nlstate;i++)
4755: for(j=1; j<=nlstate;j++)
4756: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4757: fprintf(ficresvij,"\n");
4758:
4759: xp=vector(1,npar);
4760: dnewm=matrix(1,nlstate,1,npar);
4761: doldm=matrix(1,nlstate,1,nlstate);
4762: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4763: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4764:
4765: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4766: gpp=vector(nlstate+1,nlstate+ndeath);
4767: gmp=vector(nlstate+1,nlstate+ndeath);
4768: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4769:
4770: if(estepm < stepm){
4771: printf ("Problem %d lower than %d\n",estepm, stepm);
4772: }
4773: else hstepm=estepm;
4774: /* For example we decided to compute the life expectancy with the smallest unit */
4775: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4776: nhstepm is the number of hstepm from age to agelim
4777: nstepm is the number of stepm from age to agelim.
4778: Look at function hpijx to understand why because of memory size limitations,
4779: we decided (b) to get a life expectancy respecting the most precise curvature of the
4780: survival function given by stepm (the optimization length). Unfortunately it
4781: means that if the survival funtion is printed every two years of age and if
4782: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4783: results. So we changed our mind and took the option of the best precision.
4784: */
4785: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4786: agelim = AGESUP;
4787: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4788: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4789: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4790: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4791: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4792: gp=matrix(0,nhstepm,1,nlstate);
4793: gm=matrix(0,nhstepm,1,nlstate);
4794:
4795:
4796: for(theta=1; theta <=npar; theta++){
4797: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4798: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4799: }
4800:
4801: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4802:
4803: if (popbased==1) {
4804: if(mobilav ==0){
4805: for(i=1; i<=nlstate;i++)
4806: prlim[i][i]=probs[(int)age][i][ij];
4807: }else{ /* mobilav */
4808: for(i=1; i<=nlstate;i++)
4809: prlim[i][i]=mobaverage[(int)age][i][ij];
4810: }
4811: }
4812:
4813: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
4814: for(j=1; j<= nlstate; j++){
4815: for(h=0; h<=nhstepm; h++){
4816: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4817: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4818: }
4819: }
4820: /* Next for computing probability of death (h=1 means
4821: computed over hstepm matrices product = hstepm*stepm months)
4822: as a weighted average of prlim.
4823: */
4824: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4825: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4826: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4827: }
4828: /* end probability of death */
4829:
4830: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4831: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4832:
4833: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
4834:
4835: if (popbased==1) {
4836: if(mobilav ==0){
4837: for(i=1; i<=nlstate;i++)
4838: prlim[i][i]=probs[(int)age][i][ij];
4839: }else{ /* mobilav */
4840: for(i=1; i<=nlstate;i++)
4841: prlim[i][i]=mobaverage[(int)age][i][ij];
4842: }
4843: }
4844:
4845: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4846:
4847: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4848: for(h=0; h<=nhstepm; h++){
4849: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4850: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4851: }
4852: }
4853: /* This for computing probability of death (h=1 means
4854: computed over hstepm matrices product = hstepm*stepm months)
4855: as a weighted average of prlim.
4856: */
4857: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4858: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4859: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4860: }
4861: /* end probability of death */
4862:
4863: for(j=1; j<= nlstate; j++) /* vareij */
4864: for(h=0; h<=nhstepm; h++){
4865: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4866: }
4867:
4868: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4869: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4870: }
4871:
4872: } /* End theta */
4873:
4874: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4875:
4876: for(h=0; h<=nhstepm; h++) /* veij */
4877: for(j=1; j<=nlstate;j++)
4878: for(theta=1; theta <=npar; theta++)
4879: trgradg[h][j][theta]=gradg[h][theta][j];
4880:
4881: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4882: for(theta=1; theta <=npar; theta++)
4883: trgradgp[j][theta]=gradgp[theta][j];
4884:
4885:
4886: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4887: for(i=1;i<=nlstate;i++)
4888: for(j=1;j<=nlstate;j++)
4889: vareij[i][j][(int)age] =0.;
4890:
4891: for(h=0;h<=nhstepm;h++){
4892: for(k=0;k<=nhstepm;k++){
4893: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4894: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4895: for(i=1;i<=nlstate;i++)
4896: for(j=1;j<=nlstate;j++)
4897: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4898: }
4899: }
4900:
4901: /* pptj */
4902: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4903: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4904: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4905: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4906: varppt[j][i]=doldmp[j][i];
4907: /* end ppptj */
4908: /* x centered again */
4909:
4910: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
4911:
4912: if (popbased==1) {
4913: if(mobilav ==0){
4914: for(i=1; i<=nlstate;i++)
4915: prlim[i][i]=probs[(int)age][i][ij];
4916: }else{ /* mobilav */
4917: for(i=1; i<=nlstate;i++)
4918: prlim[i][i]=mobaverage[(int)age][i][ij];
4919: }
4920: }
4921:
4922: /* This for computing probability of death (h=1 means
4923: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4924: as a weighted average of prlim.
4925: */
4926: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4927: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4928: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4929: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4930: }
4931: /* end probability of death */
4932:
4933: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4934: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4935: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4936: for(i=1; i<=nlstate;i++){
4937: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4938: }
4939: }
4940: fprintf(ficresprobmorprev,"\n");
4941:
4942: fprintf(ficresvij,"%.0f ",age );
4943: for(i=1; i<=nlstate;i++)
4944: for(j=1; j<=nlstate;j++){
4945: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4946: }
4947: fprintf(ficresvij,"\n");
4948: free_matrix(gp,0,nhstepm,1,nlstate);
4949: free_matrix(gm,0,nhstepm,1,nlstate);
4950: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4951: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4952: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4953: } /* End age */
4954: free_vector(gpp,nlstate+1,nlstate+ndeath);
4955: free_vector(gmp,nlstate+1,nlstate+ndeath);
4956: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4957: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4958: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4959: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4960: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4961: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4962: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4963: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4964: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4965: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4966: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4967: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4968: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4969: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4970: 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);
4971: /* 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);
4972: */
4973: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4974: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4975:
4976: free_vector(xp,1,npar);
4977: free_matrix(doldm,1,nlstate,1,nlstate);
4978: free_matrix(dnewm,1,nlstate,1,npar);
4979: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4980: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4981: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4982: /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
4983: fclose(ficresprobmorprev);
4984: fflush(ficgp);
4985: fflush(fichtm);
4986: } /* end varevsij */
4987:
4988: /************ Variance of prevlim ******************/
4989: 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[])
4990: {
4991: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4992: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4993:
4994: double **dnewm,**doldm;
4995: int i, j, nhstepm, hstepm;
4996: double *xp;
4997: double *gp, *gm;
4998: double **gradg, **trgradg;
4999: double **mgm, **mgp;
5000: double age,agelim;
5001: int theta;
5002:
5003: pstamp(ficresvpl);
5004: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
5005: fprintf(ficresvpl,"# Age");
5006: for(i=1; i<=nlstate;i++)
5007: fprintf(ficresvpl," %1d-%1d",i,i);
5008: fprintf(ficresvpl,"\n");
5009:
5010: xp=vector(1,npar);
5011: dnewm=matrix(1,nlstate,1,npar);
5012: doldm=matrix(1,nlstate,1,nlstate);
5013:
5014: hstepm=1*YEARM; /* Every year of age */
5015: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
5016: agelim = AGESUP;
5017: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
5018: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5019: if (stepm >= YEARM) hstepm=1;
5020: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5021: gradg=matrix(1,npar,1,nlstate);
5022: mgp=matrix(1,npar,1,nlstate);
5023: mgm=matrix(1,npar,1,nlstate);
5024: gp=vector(1,nlstate);
5025: gm=vector(1,nlstate);
5026:
5027: for(theta=1; theta <=npar; theta++){
5028: for(i=1; i<=npar; i++){ /* Computes gradient */
5029: xp[i] = x[i] + (i==theta ?delti[theta]:0);
5030: }
5031: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
5032: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
5033: else
5034: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
5035: for(i=1;i<=nlstate;i++){
5036: gp[i] = prlim[i][i];
5037: mgp[theta][i] = prlim[i][i];
5038: }
5039: for(i=1; i<=npar; i++) /* Computes gradient */
5040: xp[i] = x[i] - (i==theta ?delti[theta]:0);
5041: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
5042: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
5043: else
5044: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
5045: for(i=1;i<=nlstate;i++){
5046: gm[i] = prlim[i][i];
5047: mgm[theta][i] = prlim[i][i];
5048: }
5049: for(i=1;i<=nlstate;i++)
5050: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
5051: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
5052: } /* End theta */
5053:
5054: trgradg =matrix(1,nlstate,1,npar);
5055:
5056: for(j=1; j<=nlstate;j++)
5057: for(theta=1; theta <=npar; theta++)
5058: trgradg[j][theta]=gradg[theta][j];
5059: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
5060: /* printf("\nmgm mgp %d ",(int)age); */
5061: /* for(j=1; j<=nlstate;j++){ */
5062: /* printf(" %d ",j); */
5063: /* for(theta=1; theta <=npar; theta++) */
5064: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
5065: /* printf("\n "); */
5066: /* } */
5067: /* } */
5068: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
5069: /* printf("\n gradg %d ",(int)age); */
5070: /* for(j=1; j<=nlstate;j++){ */
5071: /* printf("%d ",j); */
5072: /* for(theta=1; theta <=npar; theta++) */
5073: /* printf("%d %lf ",theta,gradg[theta][j]); */
5074: /* printf("\n "); */
5075: /* } */
5076: /* } */
5077:
5078: for(i=1;i<=nlstate;i++)
5079: varpl[i][(int)age] =0.;
5080: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
5081: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
5082: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
5083: }else{
5084: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
5085: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
5086: }
5087: for(i=1;i<=nlstate;i++)
5088: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
5089:
5090: fprintf(ficresvpl,"%.0f ",age );
5091: for(i=1; i<=nlstate;i++)
5092: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
5093: fprintf(ficresvpl,"\n");
5094: free_vector(gp,1,nlstate);
5095: free_vector(gm,1,nlstate);
5096: free_matrix(mgm,1,npar,1,nlstate);
5097: free_matrix(mgp,1,npar,1,nlstate);
5098: free_matrix(gradg,1,npar,1,nlstate);
5099: free_matrix(trgradg,1,nlstate,1,npar);
5100: } /* End age */
5101:
5102: free_vector(xp,1,npar);
5103: free_matrix(doldm,1,nlstate,1,npar);
5104: free_matrix(dnewm,1,nlstate,1,nlstate);
5105:
5106: }
5107:
5108: /************ Variance of one-step probabilities ******************/
5109: 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[])
5110: {
5111: int i, j=0, k1, l1, tj;
5112: int k2, l2, j1, z1;
5113: int k=0, l;
5114: int first=1, first1, first2;
5115: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
5116: double **dnewm,**doldm;
5117: double *xp;
5118: double *gp, *gm;
5119: double **gradg, **trgradg;
5120: double **mu;
5121: double age, cov[NCOVMAX+1];
5122: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
5123: int theta;
5124: char fileresprob[FILENAMELENGTH];
5125: char fileresprobcov[FILENAMELENGTH];
5126: char fileresprobcor[FILENAMELENGTH];
5127: double ***varpij;
5128:
5129: strcpy(fileresprob,"PROB_");
5130: strcat(fileresprob,fileres);
5131: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
5132: printf("Problem with resultfile: %s\n", fileresprob);
5133: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
5134: }
5135: strcpy(fileresprobcov,"PROBCOV_");
5136: strcat(fileresprobcov,fileresu);
5137: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
5138: printf("Problem with resultfile: %s\n", fileresprobcov);
5139: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
5140: }
5141: strcpy(fileresprobcor,"PROBCOR_");
5142: strcat(fileresprobcor,fileresu);
5143: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
5144: printf("Problem with resultfile: %s\n", fileresprobcor);
5145: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
5146: }
5147: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
5148: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
5149: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
5150: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
5151: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
5152: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
5153: pstamp(ficresprob);
5154: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
5155: fprintf(ficresprob,"# Age");
5156: pstamp(ficresprobcov);
5157: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
5158: fprintf(ficresprobcov,"# Age");
5159: pstamp(ficresprobcor);
5160: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
5161: fprintf(ficresprobcor,"# Age");
5162:
5163:
5164: for(i=1; i<=nlstate;i++)
5165: for(j=1; j<=(nlstate+ndeath);j++){
5166: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
5167: fprintf(ficresprobcov," p%1d-%1d ",i,j);
5168: fprintf(ficresprobcor," p%1d-%1d ",i,j);
5169: }
5170: /* fprintf(ficresprob,"\n");
5171: fprintf(ficresprobcov,"\n");
5172: fprintf(ficresprobcor,"\n");
5173: */
5174: xp=vector(1,npar);
5175: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
5176: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
5177: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
5178: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
5179: first=1;
5180: fprintf(ficgp,"\n# Routine varprob");
5181: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
5182: fprintf(fichtm,"\n");
5183:
5184: 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);
5185: 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);
5186: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
5187: and drawn. It helps understanding how is the covariance between two incidences.\
5188: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
5189: 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. \
5190: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
5191: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
5192: standard deviations wide on each axis. <br>\
5193: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
5194: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
5195: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
5196:
5197: cov[1]=1;
5198: /* tj=cptcoveff; */
5199: tj = (int) pow(2,cptcoveff);
5200: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
5201: j1=0;
5202: for(j1=1; j1<=tj;j1++){
5203: /*for(i1=1; i1<=ncodemax[t];i1++){ */
5204: /*j1++;*/
5205: if (cptcovn>0) {
5206: fprintf(ficresprob, "\n#********** Variable ");
5207: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5208: fprintf(ficresprob, "**********\n#\n");
5209: fprintf(ficresprobcov, "\n#********** Variable ");
5210: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5211: fprintf(ficresprobcov, "**********\n#\n");
5212:
5213: fprintf(ficgp, "\n#********** Variable ");
5214: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5215: fprintf(ficgp, "**********\n#\n");
5216:
5217:
5218: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
5219: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5220: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
5221:
5222: fprintf(ficresprobcor, "\n#********** Variable ");
5223: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
5224: fprintf(ficresprobcor, "**********\n#");
5225: }
5226:
5227: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
5228: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
5229: gp=vector(1,(nlstate)*(nlstate+ndeath));
5230: gm=vector(1,(nlstate)*(nlstate+ndeath));
5231: for (age=bage; age<=fage; age ++){
5232: cov[2]=age;
5233: if(nagesqr==1)
5234: cov[3]= age*age;
5235: for (k=1; k<=cptcovn;k++) {
5236: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
5237: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
5238: * 1 1 1 1 1
5239: * 2 2 1 1 1
5240: * 3 1 2 1 1
5241: */
5242: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
5243: }
5244: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5245: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
5246: for (k=1; k<=cptcovprod;k++)
5247: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
5248:
5249:
5250: for(theta=1; theta <=npar; theta++){
5251: for(i=1; i<=npar; i++)
5252: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
5253:
5254: pmij(pmmij,cov,ncovmodel,xp,nlstate);
5255:
5256: k=0;
5257: for(i=1; i<= (nlstate); i++){
5258: for(j=1; j<=(nlstate+ndeath);j++){
5259: k=k+1;
5260: gp[k]=pmmij[i][j];
5261: }
5262: }
5263:
5264: for(i=1; i<=npar; i++)
5265: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
5266:
5267: pmij(pmmij,cov,ncovmodel,xp,nlstate);
5268: k=0;
5269: for(i=1; i<=(nlstate); i++){
5270: for(j=1; j<=(nlstate+ndeath);j++){
5271: k=k+1;
5272: gm[k]=pmmij[i][j];
5273: }
5274: }
5275:
5276: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
5277: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
5278: }
5279:
5280: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
5281: for(theta=1; theta <=npar; theta++)
5282: trgradg[j][theta]=gradg[theta][j];
5283:
5284: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
5285: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
5286:
5287: pmij(pmmij,cov,ncovmodel,x,nlstate);
5288:
5289: k=0;
5290: for(i=1; i<=(nlstate); i++){
5291: for(j=1; j<=(nlstate+ndeath);j++){
5292: k=k+1;
5293: mu[k][(int) age]=pmmij[i][j];
5294: }
5295: }
5296: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
5297: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
5298: varpij[i][j][(int)age] = doldm[i][j];
5299:
5300: /*printf("\n%d ",(int)age);
5301: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
5302: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
5303: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
5304: }*/
5305:
5306: fprintf(ficresprob,"\n%d ",(int)age);
5307: fprintf(ficresprobcov,"\n%d ",(int)age);
5308: fprintf(ficresprobcor,"\n%d ",(int)age);
5309:
5310: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
5311: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
5312: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
5313: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
5314: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
5315: }
5316: i=0;
5317: for (k=1; k<=(nlstate);k++){
5318: for (l=1; l<=(nlstate+ndeath);l++){
5319: i++;
5320: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
5321: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
5322: for (j=1; j<=i;j++){
5323: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
5324: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
5325: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
5326: }
5327: }
5328: }/* end of loop for state */
5329: } /* end of loop for age */
5330: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
5331: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
5332: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
5333: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
5334:
5335: /* Confidence intervalle of pij */
5336: /*
5337: fprintf(ficgp,"\nunset parametric;unset label");
5338: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
5339: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
5340: 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);
5341: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
5342: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
5343: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
5344: */
5345:
5346: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
5347: first1=1;first2=2;
5348: for (k2=1; k2<=(nlstate);k2++){
5349: for (l2=1; l2<=(nlstate+ndeath);l2++){
5350: if(l2==k2) continue;
5351: j=(k2-1)*(nlstate+ndeath)+l2;
5352: for (k1=1; k1<=(nlstate);k1++){
5353: for (l1=1; l1<=(nlstate+ndeath);l1++){
5354: if(l1==k1) continue;
5355: i=(k1-1)*(nlstate+ndeath)+l1;
5356: if(i<=j) continue;
5357: for (age=bage; age<=fage; age ++){
5358: if ((int)age %5==0){
5359: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
5360: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
5361: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
5362: mu1=mu[i][(int) age]/stepm*YEARM ;
5363: mu2=mu[j][(int) age]/stepm*YEARM;
5364: c12=cv12/sqrt(v1*v2);
5365: /* Computing eigen value of matrix of covariance */
5366: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
5367: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
5368: if ((lc2 <0) || (lc1 <0) ){
5369: if(first2==1){
5370: first1=0;
5371: 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);
5372: }
5373: 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);
5374: /* lc1=fabs(lc1); */ /* If we want to have them positive */
5375: /* lc2=fabs(lc2); */
5376: }
5377:
5378: /* Eigen vectors */
5379: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
5380: /*v21=sqrt(1.-v11*v11); *//* error */
5381: v21=(lc1-v1)/cv12*v11;
5382: v12=-v21;
5383: v22=v11;
5384: tnalp=v21/v11;
5385: if(first1==1){
5386: first1=0;
5387: 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);
5388: }
5389: 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);
5390: /*printf(fignu*/
5391: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
5392: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
5393: if(first==1){
5394: first=0;
5395: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
5396: fprintf(ficgp,"\nset parametric;unset label");
5397: 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);
5398: fprintf(ficgp,"\nset ter svg size 640, 480");
5399: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
5400: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
5401: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
5402: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
5403: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5404: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5405: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
5406: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5407: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
5408: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
5409: 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",\
5410: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
5411: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
5412: }else{
5413: first=0;
5414: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
5415: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
5416: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
5417: 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",\
5418: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
5419: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
5420: }/* if first */
5421: } /* age mod 5 */
5422: } /* end loop age */
5423: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
5424: first=1;
5425: } /*l12 */
5426: } /* k12 */
5427: } /*l1 */
5428: }/* k1 */
5429: /* } */ /* loop covariates */
5430: }
5431: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
5432: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
5433: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
5434: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
5435: free_vector(xp,1,npar);
5436: fclose(ficresprob);
5437: fclose(ficresprobcov);
5438: fclose(ficresprobcor);
5439: fflush(ficgp);
5440: fflush(fichtmcov);
5441: }
5442:
5443:
5444: /******************* Printing html file ***********/
5445: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
5446: int lastpass, int stepm, int weightopt, char model[],\
5447: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
5448: int popforecast, int prevfcast, int backcast, int estepm , \
5449: double jprev1, double mprev1,double anprev1, double dateprev1, \
5450: double jprev2, double mprev2,double anprev2, double dateprev2){
5451: int jj1, k1, i1, cpt;
5452:
5453: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
5454: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
5455: </ul>");
5456: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
5457: 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",
5458: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
5459: 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) ",
5460: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
5461: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
5462: fprintf(fichtm,"\
5463: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
5464: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
5465: fprintf(fichtm,"\
5466: - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
5467: stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
5468: fprintf(fichtm,"\
5469: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
5470: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
5471: fprintf(fichtm,"\
5472: - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
5473: subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
5474: fprintf(fichtm,"\
5475: - (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): \
5476: <a href=\"%s\">%s</a> <br>\n",
5477: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
5478: if(prevfcast==1){
5479: fprintf(fichtm,"\
5480: - Prevalence projections by age and states: \
5481: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
5482: }
5483:
5484: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
5485:
5486: m=pow(2,cptcoveff);
5487: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5488:
5489: jj1=0;
5490: for(k1=1; k1<=m;k1++){
5491: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5492: jj1++;
5493: if (cptcovn > 0) {
5494: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5495: for (cpt=1; cpt<=cptcoveff;cpt++){
5496: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5497: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
5498: }
5499: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5500: }
5501: /* aij, bij */
5502: 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> \
5503: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5504: /* Pij */
5505: 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> \
5506: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5507: /* Quasi-incidences */
5508: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
5509: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
5510: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
5511: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
5512: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5513: /* Survival functions (period) in state j */
5514: for(cpt=1; cpt<=nlstate;cpt++){
5515: 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> \
5516: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
5517: }
5518: /* State specific survival functions (period) */
5519: for(cpt=1; cpt<=nlstate;cpt++){
5520: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
5521: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
5522: <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);
5523: }
5524: /* Period (stable) prevalence in each health state */
5525: for(cpt=1; cpt<=nlstate;cpt++){
5526: 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> \
5527: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
5528: }
5529: if(backcast==1){
5530: /* Period (stable) back prevalence in each health state */
5531: for(cpt=1; cpt<=nlstate;cpt++){
5532: 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> \
5533: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
5534: }
5535: }
5536: if(prevfcast==1){
5537: /* Projection of prevalence up to period (stable) prevalence in each health state */
5538: for(cpt=1; cpt<=nlstate;cpt++){
5539: 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> \
5540: <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);
5541: }
5542: }
5543:
5544: for(cpt=1; cpt<=nlstate;cpt++) {
5545: 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> \
5546: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
5547: }
5548: /* } /\* end i1 *\/ */
5549: }/* End k1 */
5550: fprintf(fichtm,"</ul>");
5551:
5552: fprintf(fichtm,"\
5553: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
5554: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
5555: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
5556: But because parameters are usually highly correlated (a higher incidence of disability \
5557: and a higher incidence of recovery can give very close observed transition) it might \
5558: be very useful to look not only at linear confidence intervals estimated from the \
5559: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
5560: (parameters) of the logistic regression, it might be more meaningful to visualize the \
5561: covariance matrix of the one-step probabilities. \
5562: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
5563:
5564: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5565: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
5566: fprintf(fichtm,"\
5567: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5568: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
5569:
5570: fprintf(fichtm,"\
5571: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5572: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
5573: fprintf(fichtm,"\
5574: - 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): \
5575: <a href=\"%s\">%s</a> <br>\n</li>",
5576: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
5577: fprintf(fichtm,"\
5578: - (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): \
5579: <a href=\"%s\">%s</a> <br>\n</li>",
5580: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
5581: fprintf(fichtm,"\
5582: - 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",
5583: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
5584: fprintf(fichtm,"\
5585: - 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",
5586: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
5587: fprintf(fichtm,"\
5588: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
5589: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
5590:
5591: /* if(popforecast==1) fprintf(fichtm,"\n */
5592: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
5593: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
5594: /* <br>",fileres,fileres,fileres,fileres); */
5595: /* else */
5596: /* 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); */
5597: fflush(fichtm);
5598: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
5599:
5600: m=pow(2,cptcoveff);
5601: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5602:
5603: jj1=0;
5604: for(k1=1; k1<=m;k1++){
5605: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5606: jj1++;
5607: if (cptcovn > 0) {
5608: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5609: for (cpt=1; cpt<=cptcoveff;cpt++)
5610: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5611: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5612: }
5613: for(cpt=1; cpt<=nlstate;cpt++) {
5614: fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
5615: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
5616: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
5617: }
5618: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
5619: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
5620: true period expectancies (those weighted with period prevalences are also\
5621: drawn in addition to the population based expectancies computed using\
5622: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
5623: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
5624: /* } /\* end i1 *\/ */
5625: }/* End k1 */
5626: fprintf(fichtm,"</ul>");
5627: fflush(fichtm);
5628: }
5629:
5630: /******************* Gnuplot file **************/
5631: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
5632:
5633: char dirfileres[132],optfileres[132];
5634: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
5635: int lv=0, vlv=0, kl=0;
5636: int ng=0;
5637: int vpopbased;
5638: int ioffset; /* variable offset for columns */
5639:
5640: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
5641: /* printf("Problem with file %s",optionfilegnuplot); */
5642: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
5643: /* } */
5644:
5645: /*#ifdef windows */
5646: fprintf(ficgp,"cd \"%s\" \n",pathc);
5647: /*#endif */
5648: m=pow(2,cptcoveff);
5649:
5650: /* Contribution to likelihood */
5651: /* Plot the probability implied in the likelihood */
5652: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5653: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5654: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
5655: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
5656: /* nice for mle=4 plot by number of matrix products.
5657: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5658: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5659: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
5660: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
5661: 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));
5662: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
5663: 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));
5664: for (i=1; i<= nlstate ; i ++) {
5665: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
5666: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5667: 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);
5668: for (j=2; j<= nlstate+ndeath ; j ++) {
5669: 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);
5670: }
5671: fprintf(ficgp,";\nset out; unset ylabel;\n");
5672: }
5673: /* 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 */
5674: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5675: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
5676: fprintf(ficgp,"\nset out;unset log\n");
5677: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5678:
5679: strcpy(dirfileres,optionfilefiname);
5680: strcpy(optfileres,"vpl");
5681: /* 1eme*/
5682: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5683: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5684: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5685: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5686: for (k=1; k<=cptcoveff; k++){ /* For each covariate k get corresponding value lv for combination k1 */
5687: lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
5688: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5689: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5690: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5691: vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
5692: /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
5693: fprintf(ficgp," V%d=%d ",k,vlv);
5694: }
5695: fprintf(ficgp,"\n#\n");
5696:
5697: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5698: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5699: fprintf(ficgp,"set xlabel \"Age\" \n\
5700: set ylabel \"Probability\" \n \
5701: set ter svg size 640, 480\n \
5702: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5703:
5704: for (i=1; i<= nlstate ; i ++) {
5705: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5706: else fprintf(ficgp," %%*lf (%%*lf)");
5707: }
5708: 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);
5709: for (i=1; i<= nlstate ; i ++) {
5710: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5711: else fprintf(ficgp," %%*lf (%%*lf)");
5712: }
5713: 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);
5714: for (i=1; i<= nlstate ; i ++) {
5715: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5716: else fprintf(ficgp," %%*lf (%%*lf)");
5717: }
5718: 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));
5719: if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
5720: /* 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); */
5721: fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
5722: kl=0;
5723: for (k=1; k<=cptcoveff; k++){ /* For each combination of covariate */
5724: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5725: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5726: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5727: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5728: vlv= nbcode[Tvaraff[k]][lv];
5729: kl++;
5730: /* 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 *\/ */
5731: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5732: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5733: /* '' 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*/
5734: if(k==cptcoveff){
5735: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, k,kl+1+1,nbcode[Tvaraff[k]][lv], \
5736: 4+(cpt-1), cpt );
5737: }else{
5738: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, k,kl+1+1,nbcode[Tvaraff[k]][lv]);
5739: kl++;
5740: }
5741: } /* end covariate */
5742: }
5743: fprintf(ficgp,"\nset out \n");
5744: } /* k1 */
5745: } /* cpt */
5746: /*2 eme*/
5747: for (k1=1; k1<= m ; k1 ++) {
5748: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5749: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5750: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5751: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5752: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5753: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5754: vlv= nbcode[Tvaraff[k]][lv];
5755: fprintf(ficgp," V%d=%d ",k,vlv);
5756: }
5757: fprintf(ficgp,"\n#\n");
5758:
5759: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5760: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5761: if(vpopbased==0)
5762: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5763: else
5764: fprintf(ficgp,"\nreplot ");
5765: for (i=1; i<= nlstate+1 ; i ++) {
5766: k=2*i;
5767: 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);
5768: for (j=1; j<= nlstate+1 ; j ++) {
5769: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5770: else fprintf(ficgp," %%*lf (%%*lf)");
5771: }
5772: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5773: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5774: 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);
5775: for (j=1; j<= nlstate+1 ; j ++) {
5776: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5777: else fprintf(ficgp," %%*lf (%%*lf)");
5778: }
5779: fprintf(ficgp,"\" t\"\" w l lt 0,");
5780: 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);
5781: for (j=1; j<= nlstate+1 ; j ++) {
5782: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5783: else fprintf(ficgp," %%*lf (%%*lf)");
5784: }
5785: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5786: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5787: } /* state */
5788: } /* vpopbased */
5789: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5790: } /* k1 */
5791:
5792:
5793: /*3eme*/
5794: for (k1=1; k1<= m ; k1 ++) {
5795: for (cpt=1; cpt<= nlstate ; cpt ++) {
5796: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5797: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5798: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5799: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5800: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5801: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5802: vlv= nbcode[Tvaraff[k]][lv];
5803: fprintf(ficgp," V%d=%d ",k,vlv);
5804: }
5805: fprintf(ficgp,"\n#\n");
5806:
5807: /* k=2+nlstate*(2*cpt-2); */
5808: k=2+(nlstate+1)*(cpt-1);
5809: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5810: fprintf(ficgp,"set ter svg size 640, 480\n\
5811: 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);
5812: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5813: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5814: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5815: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5816: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5817: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5818:
5819: */
5820: for (i=1; i< nlstate ; i ++) {
5821: 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);
5822: /* 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);*/
5823:
5824: }
5825: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5826: }
5827: }
5828:
5829: /* Survival functions (period) from state i in state j by initial state i */
5830: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5831: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5832: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5833: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5834: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5835: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5836: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5837: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5838: vlv= nbcode[Tvaraff[k]][lv];
5839: fprintf(ficgp," V%d=%d ",k,vlv);
5840: }
5841: fprintf(ficgp,"\n#\n");
5842:
5843: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5844: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5845: set ter svg size 640, 480\n\
5846: unset log y\n\
5847: plot [%.f:%.f] ", ageminpar, agemaxpar);
5848: k=3;
5849: for (i=1; i<= nlstate ; i ++){
5850: if(i==1){
5851: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5852: }else{
5853: fprintf(ficgp,", '' ");
5854: }
5855: l=(nlstate+ndeath)*(i-1)+1;
5856: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5857: for (j=2; j<= nlstate+ndeath ; j ++)
5858: fprintf(ficgp,"+$%d",k+l+j-1);
5859: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5860: } /* nlstate */
5861: fprintf(ficgp,"\nset out\n");
5862: } /* end cpt state*/
5863: } /* end covariate */
5864:
5865: /* Survival functions (period) from state i in state j by final state j */
5866: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5867: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5868: 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);
5869: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5870: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5871: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5872: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5873: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5874: vlv= nbcode[Tvaraff[k]][lv];
5875: fprintf(ficgp," V%d=%d ",k,vlv);
5876: }
5877: fprintf(ficgp,"\n#\n");
5878:
5879: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5880: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5881: set ter svg size 640, 480\n\
5882: unset log y\n\
5883: plot [%.f:%.f] ", ageminpar, agemaxpar);
5884: k=3;
5885: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5886: if(j==1)
5887: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5888: else
5889: fprintf(ficgp,", '' ");
5890: l=(nlstate+ndeath)*(cpt-1) +j;
5891: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5892: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5893: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5894: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5895: } /* nlstate */
5896: fprintf(ficgp,", '' ");
5897: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5898: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5899: l=(nlstate+ndeath)*(cpt-1) +j;
5900: if(j < nlstate)
5901: fprintf(ficgp,"$%d +",k+l);
5902: else
5903: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5904: }
5905: fprintf(ficgp,"\nset out\n");
5906: } /* end cpt state*/
5907: } /* end covariate */
5908:
5909: /* CV preval stable (period) for each covariate */
5910: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5911: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5912: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5913: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5914: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5915: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5916: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5917: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5918: vlv= nbcode[Tvaraff[k]][lv];
5919: fprintf(ficgp," V%d=%d ",k,vlv);
5920: }
5921: fprintf(ficgp,"\n#\n");
5922:
5923: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5924: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5925: set ter svg size 640, 480\n\
5926: unset log y\n\
5927: plot [%.f:%.f] ", ageminpar, agemaxpar);
5928: k=3; /* Offset */
5929: for (i=1; i<= nlstate ; i ++){
5930: if(i==1)
5931: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5932: else
5933: fprintf(ficgp,", '' ");
5934: l=(nlstate+ndeath)*(i-1)+1;
5935: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5936: for (j=2; j<= nlstate ; j ++)
5937: fprintf(ficgp,"+$%d",k+l+j-1);
5938: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5939: } /* nlstate */
5940: fprintf(ficgp,"\nset out\n");
5941: } /* end cpt state*/
5942: } /* end covariate */
5943: if(backcast == 1){
5944: /* CV back preval stable (period) for each covariate */
5945: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5946: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5947: fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5948: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5949: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5950: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5951: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5952: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5953: vlv= nbcode[Tvaraff[k]][lv];
5954: fprintf(ficgp," V%d=%d ",k,vlv);
5955: }
5956: fprintf(ficgp,"\n#\n");
5957:
5958: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
5959: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5960: set ter svg size 640, 480\n \
5961: unset log y\n \
5962: plot [%.f:%.f] ", ageminpar, agemaxpar);
5963: k=3; /* Offset */
5964: for (i=1; i<= nlstate ; i ++){
5965: if(i==1)
5966: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
5967: else
5968: fprintf(ficgp,", '' ");
5969: /* l=(nlstate+ndeath)*(i-1)+1; */
5970: l=(nlstate+ndeath)*(cpt-1)+1;
5971: /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
5972: /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
5973: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
5974: /* for (j=2; j<= nlstate ; j ++) */
5975: /* fprintf(ficgp,"+$%d",k+l+j-1); */
5976: /* /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
5977: fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
5978: } /* nlstate */
5979: fprintf(ficgp,"\nset out\n");
5980: } /* end cpt state*/
5981: } /* end covariate */
5982: } /* End if backcast */
5983:
5984: if(prevfcast==1){
5985: /* Projection from cross-sectional to stable (period) for each covariate */
5986:
5987: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5988: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5989: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5990: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5991: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5992: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5993: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5994: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5995: vlv= nbcode[Tvaraff[k]][lv];
5996: fprintf(ficgp," V%d=%d ",k,vlv);
5997: }
5998: fprintf(ficgp,"\n#\n");
5999:
6000: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
6001: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
6002: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
6003: set ter svg size 640, 480\n \
6004: unset log y\n \
6005: plot [%.f:%.f] ", ageminpar, agemaxpar);
6006: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
6007: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6008: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6009: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6010: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6011: if(i==1){
6012: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
6013: }else{
6014: fprintf(ficgp,",\\\n '' ");
6015: }
6016: if(cptcoveff ==0){ /* No covariate */
6017: ioffset=2; /* Age is in 2 */
6018: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
6019: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
6020: /*# V1 = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
6021: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
6022: fprintf(ficgp," u %d:(", ioffset);
6023: if(i==nlstate+1)
6024: fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ", \
6025: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
6026: else
6027: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
6028: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
6029: }else{ /* more than 2 covariates */
6030: if(cptcoveff ==1){
6031: ioffset=4; /* Age is in 4 */
6032: }else{
6033: ioffset=6; /* Age is in 6 */
6034: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
6035: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
6036: }
6037: fprintf(ficgp," u %d:((",ioffset);
6038: kl=0;
6039: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
6040: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
6041: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
6042: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
6043: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
6044: vlv= nbcode[Tvaraff[k]][lv];
6045: kl++;
6046: /* 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 *\/ */
6047: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
6048: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
6049: /* '' 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*/
6050: if(k==cptcoveff){
6051: if(i==nlstate+1){
6052: if(cptcoveff ==1){
6053: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
6054: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
6055: }else{
6056: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
6057: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
6058: }
6059: }else{
6060: if(cptcoveff ==1){
6061: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
6062: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
6063: }else{
6064: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[k]][lv], \
6065: ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
6066: }
6067: }
6068: }else{ /* k < cptcoveff */
6069: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[k]][lv]);
6070: kl++;
6071: }
6072: } /* end covariate */
6073: } /* end if covariate */
6074: } /* nlstate */
6075: fprintf(ficgp,"\nset out\n");
6076: } /* end cpt state*/
6077: } /* end covariate */
6078: } /* End if prevfcast */
6079:
6080:
6081: /* proba elementaires */
6082: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
6083: for(i=1,jk=1; i <=nlstate; i++){
6084: fprintf(ficgp,"# initial state %d\n",i);
6085: for(k=1; k <=(nlstate+ndeath); k++){
6086: if (k != i) {
6087: fprintf(ficgp,"# current state %d\n",k);
6088: for(j=1; j <=ncovmodel; j++){
6089: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
6090: jk++;
6091: }
6092: fprintf(ficgp,"\n");
6093: }
6094: }
6095: }
6096: fprintf(ficgp,"##############\n#\n");
6097:
6098: /*goto avoid;*/
6099: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
6100: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
6101: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
6102: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
6103: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
6104: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6105: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
6106: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6107: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
6108: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
6109: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
6110: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
6111: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
6112: fprintf(ficgp,"#\n");
6113: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
6114: fprintf(ficgp,"# ng=%d\n",ng);
6115: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
6116: for(jk=1; jk <=m; jk++) {
6117: fprintf(ficgp,"# jk=%d\n",jk);
6118: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
6119: fprintf(ficgp,"\nset ter svg size 640, 480 ");
6120: if (ng==1){
6121: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
6122: fprintf(ficgp,"\nunset log y");
6123: }else if (ng==2){
6124: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
6125: fprintf(ficgp,"\nset log y");
6126: }else if (ng==3){
6127: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
6128: fprintf(ficgp,"\nset log y");
6129: }else
6130: fprintf(ficgp,"\nunset title ");
6131: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
6132: i=1;
6133: for(k2=1; k2<=nlstate; k2++) {
6134: k3=i;
6135: for(k=1; k<=(nlstate+ndeath); k++) {
6136: if (k != k2){
6137: switch( ng) {
6138: case 1:
6139: if(nagesqr==0)
6140: fprintf(ficgp," p%d+p%d*x",i,i+1);
6141: else /* nagesqr =1 */
6142: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
6143: break;
6144: case 2: /* ng=2 */
6145: if(nagesqr==0)
6146: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
6147: else /* nagesqr =1 */
6148: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
6149: break;
6150: case 3:
6151: if(nagesqr==0)
6152: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
6153: else /* nagesqr =1 */
6154: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
6155: break;
6156: }
6157: ij=1;/* To be checked else nbcode[0][0] wrong */
6158: for(j=3; j <=ncovmodel-nagesqr; j++) {
6159: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
6160: if(ij <=cptcovage) { /* Bug valgrind */
6161: if((j-2)==Tage[ij]) { /* Bug valgrind */
6162: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
6163: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
6164: ij++;
6165: }
6166: }
6167: else
6168: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
6169: }
6170: }else{
6171: i=i-ncovmodel;
6172: if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
6173: fprintf(ficgp," (1.");
6174: }
6175:
6176: if(ng != 1){
6177: fprintf(ficgp,")/(1");
6178:
6179: for(k1=1; k1 <=nlstate; k1++){
6180: if(nagesqr==0)
6181: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
6182: else /* nagesqr =1 */
6183: 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);
6184:
6185: ij=1;
6186: for(j=3; j <=ncovmodel-nagesqr; j++){
6187: if(ij <=cptcovage) { /* Bug valgrind */
6188: if((j-2)==Tage[ij]) { /* Bug valgrind */
6189: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
6190: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
6191: ij++;
6192: }
6193: }
6194: else
6195: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
6196: }
6197: fprintf(ficgp,")");
6198: }
6199: fprintf(ficgp,")");
6200: if(ng ==2)
6201: fprintf(ficgp," t \"p%d%d\" ", k2,k);
6202: else /* ng= 3 */
6203: fprintf(ficgp," t \"i%d%d\" ", k2,k);
6204: }else{ /* end ng <> 1 */
6205: if( k !=k2) /* logit p11 is hard to draw */
6206: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
6207: }
6208: if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
6209: fprintf(ficgp,",");
6210: if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
6211: fprintf(ficgp,",");
6212: i=i+ncovmodel;
6213: } /* end k */
6214: } /* end k2 */
6215: fprintf(ficgp,"\n set out\n");
6216: } /* end jk */
6217: } /* end ng */
6218: /* avoid: */
6219: fflush(ficgp);
6220: } /* end gnuplot */
6221:
6222:
6223: /*************** Moving average **************/
6224: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
6225: int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
6226:
6227: int i, cpt, cptcod;
6228: int modcovmax =1;
6229: int mobilavrange, mob;
6230: int iage=0;
6231:
6232: double sum=0.;
6233: double age;
6234: double *sumnewp, *sumnewm;
6235: double *agemingood, *agemaxgood; /* Currently identical for all covariates */
6236:
6237:
6238: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
6239: a covariate has 2 modalities, should be equal to ncovcombmax */
6240:
6241: sumnewp = vector(1,modcovmax);
6242: sumnewm = vector(1,modcovmax);
6243: agemingood = vector(1,modcovmax);
6244: agemaxgood = vector(1,modcovmax);
6245:
6246: for (cptcod=1;cptcod<=modcovmax;cptcod++){
6247: sumnewm[cptcod]=0.;
6248: sumnewp[cptcod]=0.;
6249: agemingood[cptcod]=0;
6250: agemaxgood[cptcod]=0;
6251: }
6252: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
6253:
6254: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
6255: if(mobilav==1) mobilavrange=5; /* default */
6256: else mobilavrange=mobilav;
6257: for (age=bage; age<=fage; age++)
6258: for (i=1; i<=nlstate;i++)
6259: for (cptcod=1;cptcod<=modcovmax;cptcod++)
6260: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
6261: /* We keep the original values on the extreme ages bage, fage and for
6262: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
6263: we use a 5 terms etc. until the borders are no more concerned.
6264: */
6265: for (mob=3;mob <=mobilavrange;mob=mob+2){
6266: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
6267: for (i=1; i<=nlstate;i++){
6268: for (cptcod=1;cptcod<=modcovmax;cptcod++){
6269: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
6270: for (cpt=1;cpt<=(mob-1)/2;cpt++){
6271: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
6272: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
6273: }
6274: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
6275: }
6276: }
6277: }/* end age */
6278: }/* end mob */
6279: }else
6280: return -1;
6281: for (cptcod=1;cptcod<=modcovmax;cptcod++){
6282: /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
6283: agemingood[cptcod]=fage-(mob-1)/2;
6284: for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
6285: sumnewm[cptcod]=0.;
6286: for (i=1; i<=nlstate;i++){
6287: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
6288: }
6289: if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
6290: agemingood[cptcod]=age;
6291: }else{ /* bad */
6292: for (i=1; i<=nlstate;i++){
6293: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
6294: } /* i */
6295: } /* end bad */
6296: }/* age */
6297: sum=0.;
6298: for (i=1; i<=nlstate;i++){
6299: sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
6300: }
6301: if(fabs(sum - 1.) > 1.e-3) { /* bad */
6302: 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);
6303: /* for (i=1; i<=nlstate;i++){ */
6304: /* mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
6305: /* } /\* i *\/ */
6306: } /* end bad */
6307: /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
6308: /* From youngest, finding the oldest wrong */
6309: agemaxgood[cptcod]=bage+(mob-1)/2;
6310: for (age=bage+(mob-1)/2; age<=fage; age++){
6311: sumnewm[cptcod]=0.;
6312: for (i=1; i<=nlstate;i++){
6313: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
6314: }
6315: if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
6316: agemaxgood[cptcod]=age;
6317: }else{ /* bad */
6318: for (i=1; i<=nlstate;i++){
6319: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
6320: } /* i */
6321: } /* end bad */
6322: }/* age */
6323: sum=0.;
6324: for (i=1; i<=nlstate;i++){
6325: sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
6326: }
6327: if(fabs(sum - 1.) > 1.e-3) { /* bad */
6328: 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);
6329: /* for (i=1; i<=nlstate;i++){ */
6330: /* mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
6331: /* } /\* i *\/ */
6332: } /* end bad */
6333:
6334: for (age=bage; age<=fage; age++){
6335: printf("%d %d ", cptcod, (int)age);
6336: sumnewp[cptcod]=0.;
6337: sumnewm[cptcod]=0.;
6338: for (i=1; i<=nlstate;i++){
6339: sumnewp[cptcod]+=probs[(int)age][i][cptcod];
6340: sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
6341: /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
6342: }
6343: /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
6344: }
6345: /* printf("\n"); */
6346: /* } */
6347: /* brutal averaging */
6348: for (i=1; i<=nlstate;i++){
6349: for (age=1; age<=bage; age++){
6350: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
6351: /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
6352: }
6353: for (age=fage; age<=AGESUP; age++){
6354: mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
6355: /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
6356: }
6357: } /* end i status */
6358: for (i=nlstate+1; i<=nlstate+ndeath;i++){
6359: for (age=1; age<=AGESUP; age++){
6360: /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
6361: mobaverage[(int)age][i][cptcod]=0.;
6362: }
6363: }
6364: }/* end cptcod */
6365: free_vector(sumnewm,1, modcovmax);
6366: free_vector(sumnewp,1, modcovmax);
6367: free_vector(agemaxgood,1, modcovmax);
6368: free_vector(agemingood,1, modcovmax);
6369: return 0;
6370: }/* End movingaverage */
6371:
6372:
6373: /************** Forecasting ******************/
6374: 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){
6375: /* proj1, year, month, day of starting projection
6376: agemin, agemax range of age
6377: dateprev1 dateprev2 range of dates during which prevalence is computed
6378: anproj2 year of en of projection (same day and month as proj1).
6379: */
6380: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
6381: double agec; /* generic age */
6382: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
6383: double *popeffectif,*popcount;
6384: double ***p3mat;
6385: /* double ***mobaverage; */
6386: char fileresf[FILENAMELENGTH];
6387:
6388: agelim=AGESUP;
6389: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
6390: in each health status at the date of interview (if between dateprev1 and dateprev2).
6391: We still use firstpass and lastpass as another selection.
6392: */
6393: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
6394: /* firstpass, lastpass, stepm, weightopt, model); */
6395:
6396: strcpy(fileresf,"F_");
6397: strcat(fileresf,fileresu);
6398: if((ficresf=fopen(fileresf,"w"))==NULL) {
6399: printf("Problem with forecast resultfile: %s\n", fileresf);
6400: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
6401: }
6402: printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
6403: fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
6404:
6405: if (cptcoveff==0) ncodemax[cptcoveff]=1;
6406:
6407:
6408: stepsize=(int) (stepm+YEARM-1)/YEARM;
6409: if (stepm<=12) stepsize=1;
6410: if(estepm < stepm){
6411: printf ("Problem %d lower than %d\n",estepm, stepm);
6412: }
6413: else hstepm=estepm;
6414:
6415: hstepm=hstepm/stepm;
6416: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
6417: fractional in yp1 */
6418: anprojmean=yp;
6419: yp2=modf((yp1*12),&yp);
6420: mprojmean=yp;
6421: yp1=modf((yp2*30.5),&yp);
6422: jprojmean=yp;
6423: if(jprojmean==0) jprojmean=1;
6424: if(mprojmean==0) jprojmean=1;
6425:
6426: i1=cptcoveff;
6427: if (cptcovn < 1){i1=1;}
6428:
6429: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
6430:
6431: fprintf(ficresf,"#****** Routine prevforecast **\n");
6432:
6433: /* if (h==(int)(YEARM*yearp)){ */
6434: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
6435: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
6436: k=k+1;
6437: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
6438: for(j=1;j<=cptcoveff;j++) {
6439: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6440: }
6441: fprintf(ficresf," yearproj age");
6442: for(j=1; j<=nlstate+ndeath;j++){
6443: for(i=1; i<=nlstate;i++)
6444: fprintf(ficresf," p%d%d",i,j);
6445: fprintf(ficresf," wp.%d",j);
6446: }
6447: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
6448: fprintf(ficresf,"\n");
6449: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
6450: for (agec=fage; agec>=(ageminpar-1); agec--){
6451: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
6452: nhstepm = nhstepm/hstepm;
6453: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6454: oldm=oldms;savm=savms;
6455: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
6456:
6457: for (h=0; h<=nhstepm; h++){
6458: if (h*hstepm/YEARM*stepm ==yearp) {
6459: fprintf(ficresf,"\n");
6460: for(j=1;j<=cptcoveff;j++)
6461: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6462: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
6463: }
6464: for(j=1; j<=nlstate+ndeath;j++) {
6465: ppij=0.;
6466: for(i=1; i<=nlstate;i++) {
6467: if (mobilav==1)
6468: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
6469: else {
6470: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
6471: }
6472: if (h*hstepm/YEARM*stepm== yearp) {
6473: fprintf(ficresf," %.3f", p3mat[i][j][h]);
6474: }
6475: } /* end i */
6476: if (h*hstepm/YEARM*stepm==yearp) {
6477: fprintf(ficresf," %.3f", ppij);
6478: }
6479: }/* end j */
6480: } /* end h */
6481: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6482: } /* end agec */
6483: } /* end yearp */
6484: } /* end cptcod */
6485: } /* end cptcov */
6486:
6487: fclose(ficresf);
6488: printf("End of Computing forecasting \n");
6489: fprintf(ficlog,"End of Computing forecasting\n");
6490:
6491: }
6492:
6493: /* /\************** Back Forecasting ******************\/ */
6494: /* 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){ */
6495: /* /\* back1, year, month, day of starting backection */
6496: /* agemin, agemax range of age */
6497: /* dateprev1 dateprev2 range of dates during which prevalence is computed */
6498: /* anback2 year of en of backection (same day and month as back1). */
6499: /* *\/ */
6500: /* int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
6501: /* double agec; /\* generic age *\/ */
6502: /* double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
6503: /* double *popeffectif,*popcount; */
6504: /* double ***p3mat; */
6505: /* /\* double ***mobaverage; *\/ */
6506: /* char fileresfb[FILENAMELENGTH]; */
6507:
6508: /* agelim=AGESUP; */
6509: /* /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
6510: /* in each health status at the date of interview (if between dateprev1 and dateprev2). */
6511: /* We still use firstpass and lastpass as another selection. */
6512: /* *\/ */
6513: /* /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
6514: /* /\* firstpass, lastpass, stepm, weightopt, model); *\/ */
6515: /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
6516:
6517: /* strcpy(fileresfb,"FB_"); */
6518: /* strcat(fileresfb,fileresu); */
6519: /* if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
6520: /* printf("Problem with back forecast resultfile: %s\n", fileresfb); */
6521: /* fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
6522: /* } */
6523: /* printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
6524: /* fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
6525:
6526: /* if (cptcoveff==0) ncodemax[cptcoveff]=1; */
6527:
6528: /* /\* if (mobilav!=0) { *\/ */
6529: /* /\* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
6530: /* /\* if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
6531: /* /\* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
6532: /* /\* printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
6533: /* /\* } *\/ */
6534: /* /\* } *\/ */
6535:
6536: /* stepsize=(int) (stepm+YEARM-1)/YEARM; */
6537: /* if (stepm<=12) stepsize=1; */
6538: /* if(estepm < stepm){ */
6539: /* printf ("Problem %d lower than %d\n",estepm, stepm); */
6540: /* } */
6541: /* else hstepm=estepm; */
6542:
6543: /* hstepm=hstepm/stepm; */
6544: /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp and */
6545: /* fractional in yp1 *\/ */
6546: /* anprojmean=yp; */
6547: /* yp2=modf((yp1*12),&yp); */
6548: /* mprojmean=yp; */
6549: /* yp1=modf((yp2*30.5),&yp); */
6550: /* jprojmean=yp; */
6551: /* if(jprojmean==0) jprojmean=1; */
6552: /* if(mprojmean==0) jprojmean=1; */
6553:
6554: /* i1=cptcoveff; */
6555: /* if (cptcovn < 1){i1=1;} */
6556:
6557: /* fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); */
6558:
6559: /* fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
6560:
6561: /* /\* if (h==(int)(YEARM*yearp)){ *\/ */
6562: /* for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
6563: /* for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
6564: /* k=k+1; */
6565: /* fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
6566: /* for(j=1;j<=cptcoveff;j++) { */
6567: /* fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
6568: /* } */
6569: /* fprintf(ficresfb," yearbproj age"); */
6570: /* for(j=1; j<=nlstate+ndeath;j++){ */
6571: /* for(i=1; i<=nlstate;i++) */
6572: /* fprintf(ficresfb," p%d%d",i,j); */
6573: /* fprintf(ficresfb," p.%d",j); */
6574: /* } */
6575: /* for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) { */
6576: /* /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { *\/ */
6577: /* fprintf(ficresfb,"\n"); */
6578: /* fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
6579: /* for (agec=fage; agec>=(ageminpar-1); agec--){ */
6580: /* nhstepm=(int) rint((agelim-agec)*YEARM/stepm); */
6581: /* nhstepm = nhstepm/hstepm; */
6582: /* p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
6583: /* oldm=oldms;savm=savms; */
6584: /* hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); */
6585: /* for (h=0; h<=nhstepm; h++){ */
6586: /* if (h*hstepm/YEARM*stepm ==yearp) { */
6587: /* fprintf(ficresfb,"\n"); */
6588: /* for(j=1;j<=cptcoveff;j++) */
6589: /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
6590: /* fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
6591: /* } */
6592: /* for(j=1; j<=nlstate+ndeath;j++) { */
6593: /* ppij=0.; */
6594: /* for(i=1; i<=nlstate;i++) { */
6595: /* if (mobilav==1) */
6596: /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
6597: /* else { */
6598: /* ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
6599: /* } */
6600: /* if (h*hstepm/YEARM*stepm== yearp) { */
6601: /* fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
6602: /* } */
6603: /* } /\* end i *\/ */
6604: /* if (h*hstepm/YEARM*stepm==yearp) { */
6605: /* fprintf(ficresfb," %.3f", ppij); */
6606: /* } */
6607: /* }/\* end j *\/ */
6608: /* } /\* end h *\/ */
6609: /* free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
6610: /* } /\* end agec *\/ */
6611: /* } /\* end yearp *\/ */
6612: /* } /\* end cptcod *\/ */
6613: /* } /\* end cptcov *\/ */
6614:
6615: /* /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
6616:
6617: /* fclose(ficresfb); */
6618: /* printf("End of Computing Back forecasting \n"); */
6619: /* fprintf(ficlog,"End of Computing Back forecasting\n"); */
6620:
6621: /* } */
6622:
6623: /************** Forecasting *****not tested NB*************/
6624: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
6625:
6626: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
6627: int *popage;
6628: double calagedatem, agelim, kk1, kk2;
6629: double *popeffectif,*popcount;
6630: double ***p3mat,***tabpop,***tabpopprev;
6631: /* double ***mobaverage; */
6632: char filerespop[FILENAMELENGTH];
6633:
6634: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6635: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6636: agelim=AGESUP;
6637: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
6638:
6639: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6640:
6641:
6642: strcpy(filerespop,"POP_");
6643: strcat(filerespop,fileresu);
6644: if((ficrespop=fopen(filerespop,"w"))==NULL) {
6645: printf("Problem with forecast resultfile: %s\n", filerespop);
6646: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
6647: }
6648: printf("Computing forecasting: result on file '%s' \n", filerespop);
6649: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
6650:
6651: if (cptcoveff==0) ncodemax[cptcoveff]=1;
6652:
6653: /* if (mobilav!=0) { */
6654: /* mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
6655: /* if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
6656: /* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
6657: /* printf(" Error in movingaverage mobilav=%d\n",mobilav); */
6658: /* } */
6659: /* } */
6660:
6661: stepsize=(int) (stepm+YEARM-1)/YEARM;
6662: if (stepm<=12) stepsize=1;
6663:
6664: agelim=AGESUP;
6665:
6666: hstepm=1;
6667: hstepm=hstepm/stepm;
6668:
6669: if (popforecast==1) {
6670: if((ficpop=fopen(popfile,"r"))==NULL) {
6671: printf("Problem with population file : %s\n",popfile);exit(0);
6672: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
6673: }
6674: popage=ivector(0,AGESUP);
6675: popeffectif=vector(0,AGESUP);
6676: popcount=vector(0,AGESUP);
6677:
6678: i=1;
6679: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
6680:
6681: imx=i;
6682: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
6683: }
6684:
6685: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
6686: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
6687: k=k+1;
6688: fprintf(ficrespop,"\n#******");
6689: for(j=1;j<=cptcoveff;j++) {
6690: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6691: }
6692: fprintf(ficrespop,"******\n");
6693: fprintf(ficrespop,"# Age");
6694: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
6695: if (popforecast==1) fprintf(ficrespop," [Population]");
6696:
6697: for (cpt=0; cpt<=0;cpt++) {
6698: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
6699:
6700: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
6701: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
6702: nhstepm = nhstepm/hstepm;
6703:
6704: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6705: oldm=oldms;savm=savms;
6706: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6707:
6708: for (h=0; h<=nhstepm; h++){
6709: if (h==(int) (calagedatem+YEARM*cpt)) {
6710: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
6711: }
6712: for(j=1; j<=nlstate+ndeath;j++) {
6713: kk1=0.;kk2=0;
6714: for(i=1; i<=nlstate;i++) {
6715: if (mobilav==1)
6716: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
6717: else {
6718: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
6719: }
6720: }
6721: if (h==(int)(calagedatem+12*cpt)){
6722: tabpop[(int)(agedeb)][j][cptcod]=kk1;
6723: /*fprintf(ficrespop," %.3f", kk1);
6724: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
6725: }
6726: }
6727: for(i=1; i<=nlstate;i++){
6728: kk1=0.;
6729: for(j=1; j<=nlstate;j++){
6730: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
6731: }
6732: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
6733: }
6734:
6735: if (h==(int)(calagedatem+12*cpt))
6736: for(j=1; j<=nlstate;j++)
6737: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
6738: }
6739: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6740: }
6741: }
6742:
6743: /******/
6744:
6745: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
6746: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
6747: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
6748: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
6749: nhstepm = nhstepm/hstepm;
6750:
6751: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6752: oldm=oldms;savm=savms;
6753: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6754: for (h=0; h<=nhstepm; h++){
6755: if (h==(int) (calagedatem+YEARM*cpt)) {
6756: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
6757: }
6758: for(j=1; j<=nlstate+ndeath;j++) {
6759: kk1=0.;kk2=0;
6760: for(i=1; i<=nlstate;i++) {
6761: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
6762: }
6763: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
6764: }
6765: }
6766: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6767: }
6768: }
6769: }
6770: }
6771:
6772: /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
6773:
6774: if (popforecast==1) {
6775: free_ivector(popage,0,AGESUP);
6776: free_vector(popeffectif,0,AGESUP);
6777: free_vector(popcount,0,AGESUP);
6778: }
6779: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6780: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6781: fclose(ficrespop);
6782: } /* End of popforecast */
6783:
6784: int fileappend(FILE *fichier, char *optionfich)
6785: {
6786: if((fichier=fopen(optionfich,"a"))==NULL) {
6787: printf("Problem with file: %s\n", optionfich);
6788: fprintf(ficlog,"Problem with file: %s\n", optionfich);
6789: return (0);
6790: }
6791: fflush(fichier);
6792: return (1);
6793: }
6794:
6795:
6796: /**************** function prwizard **********************/
6797: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
6798: {
6799:
6800: /* Wizard to print covariance matrix template */
6801:
6802: char ca[32], cb[32];
6803: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
6804: int numlinepar;
6805:
6806: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6807: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6808: for(i=1; i <=nlstate; i++){
6809: jj=0;
6810: for(j=1; j <=nlstate+ndeath; j++){
6811: if(j==i) continue;
6812: jj++;
6813: /*ca[0]= k+'a'-1;ca[1]='\0';*/
6814: printf("%1d%1d",i,j);
6815: fprintf(ficparo,"%1d%1d",i,j);
6816: for(k=1; k<=ncovmodel;k++){
6817: /* printf(" %lf",param[i][j][k]); */
6818: /* fprintf(ficparo," %lf",param[i][j][k]); */
6819: printf(" 0.");
6820: fprintf(ficparo," 0.");
6821: }
6822: printf("\n");
6823: fprintf(ficparo,"\n");
6824: }
6825: }
6826: printf("# Scales (for hessian or gradient estimation)\n");
6827: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
6828: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
6829: for(i=1; i <=nlstate; i++){
6830: jj=0;
6831: for(j=1; j <=nlstate+ndeath; j++){
6832: if(j==i) continue;
6833: jj++;
6834: fprintf(ficparo,"%1d%1d",i,j);
6835: printf("%1d%1d",i,j);
6836: fflush(stdout);
6837: for(k=1; k<=ncovmodel;k++){
6838: /* printf(" %le",delti3[i][j][k]); */
6839: /* fprintf(ficparo," %le",delti3[i][j][k]); */
6840: printf(" 0.");
6841: fprintf(ficparo," 0.");
6842: }
6843: numlinepar++;
6844: printf("\n");
6845: fprintf(ficparo,"\n");
6846: }
6847: }
6848: printf("# Covariance matrix\n");
6849: /* # 121 Var(a12)\n\ */
6850: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6851: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6852: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6853: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6854: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6855: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6856: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6857: fflush(stdout);
6858: fprintf(ficparo,"# Covariance matrix\n");
6859: /* # 121 Var(a12)\n\ */
6860: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6861: /* # ...\n\ */
6862: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6863:
6864: for(itimes=1;itimes<=2;itimes++){
6865: jj=0;
6866: for(i=1; i <=nlstate; i++){
6867: for(j=1; j <=nlstate+ndeath; j++){
6868: if(j==i) continue;
6869: for(k=1; k<=ncovmodel;k++){
6870: jj++;
6871: ca[0]= k+'a'-1;ca[1]='\0';
6872: if(itimes==1){
6873: printf("#%1d%1d%d",i,j,k);
6874: fprintf(ficparo,"#%1d%1d%d",i,j,k);
6875: }else{
6876: printf("%1d%1d%d",i,j,k);
6877: fprintf(ficparo,"%1d%1d%d",i,j,k);
6878: /* printf(" %.5le",matcov[i][j]); */
6879: }
6880: ll=0;
6881: for(li=1;li <=nlstate; li++){
6882: for(lj=1;lj <=nlstate+ndeath; lj++){
6883: if(lj==li) continue;
6884: for(lk=1;lk<=ncovmodel;lk++){
6885: ll++;
6886: if(ll<=jj){
6887: cb[0]= lk +'a'-1;cb[1]='\0';
6888: if(ll<jj){
6889: if(itimes==1){
6890: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6891: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6892: }else{
6893: printf(" 0.");
6894: fprintf(ficparo," 0.");
6895: }
6896: }else{
6897: if(itimes==1){
6898: printf(" Var(%s%1d%1d)",ca,i,j);
6899: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
6900: }else{
6901: printf(" 0.");
6902: fprintf(ficparo," 0.");
6903: }
6904: }
6905: }
6906: } /* end lk */
6907: } /* end lj */
6908: } /* end li */
6909: printf("\n");
6910: fprintf(ficparo,"\n");
6911: numlinepar++;
6912: } /* end k*/
6913: } /*end j */
6914: } /* end i */
6915: } /* end itimes */
6916:
6917: } /* end of prwizard */
6918: /******************* Gompertz Likelihood ******************************/
6919: double gompertz(double x[])
6920: {
6921: double A,B,L=0.0,sump=0.,num=0.;
6922: int i,n=0; /* n is the size of the sample */
6923:
6924: for (i=0;i<=imx-1 ; i++) {
6925: sump=sump+weight[i];
6926: /* sump=sump+1;*/
6927: num=num+1;
6928: }
6929:
6930:
6931: /* for (i=0; i<=imx; i++)
6932: 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]);*/
6933:
6934: for (i=1;i<=imx ; i++)
6935: {
6936: if (cens[i] == 1 && wav[i]>1)
6937: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
6938:
6939: if (cens[i] == 0 && wav[i]>1)
6940: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
6941: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
6942:
6943: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6944: if (wav[i] > 1 ) { /* ??? */
6945: L=L+A*weight[i];
6946: /* 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]);*/
6947: }
6948: }
6949:
6950: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6951:
6952: return -2*L*num/sump;
6953: }
6954:
6955: #ifdef GSL
6956: /******************* Gompertz_f Likelihood ******************************/
6957: double gompertz_f(const gsl_vector *v, void *params)
6958: {
6959: double A,B,LL=0.0,sump=0.,num=0.;
6960: double *x= (double *) v->data;
6961: int i,n=0; /* n is the size of the sample */
6962:
6963: for (i=0;i<=imx-1 ; i++) {
6964: sump=sump+weight[i];
6965: /* sump=sump+1;*/
6966: num=num+1;
6967: }
6968:
6969:
6970: /* for (i=0; i<=imx; i++)
6971: 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]);*/
6972: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
6973: for (i=1;i<=imx ; i++)
6974: {
6975: if (cens[i] == 1 && wav[i]>1)
6976: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
6977:
6978: if (cens[i] == 0 && wav[i]>1)
6979: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6980: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6981:
6982: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6983: if (wav[i] > 1 ) { /* ??? */
6984: LL=LL+A*weight[i];
6985: /* 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]);*/
6986: }
6987: }
6988:
6989: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6990: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6991:
6992: return -2*LL*num/sump;
6993: }
6994: #endif
6995:
6996: /******************* Printing html file ***********/
6997: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
6998: int lastpass, int stepm, int weightopt, char model[],\
6999: int imx, double p[],double **matcov,double agemortsup){
7000: int i,k;
7001:
7002: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
7003: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
7004: for (i=1;i<=2;i++)
7005: 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]));
7006: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
7007: fprintf(fichtm,"</ul>");
7008:
7009: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
7010:
7011: 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>");
7012:
7013: for (k=agegomp;k<(agemortsup-2);k++)
7014: 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]);
7015:
7016:
7017: fflush(fichtm);
7018: }
7019:
7020: /******************* Gnuplot file **************/
7021: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
7022:
7023: char dirfileres[132],optfileres[132];
7024:
7025: int ng;
7026:
7027:
7028: /*#ifdef windows */
7029: fprintf(ficgp,"cd \"%s\" \n",pathc);
7030: /*#endif */
7031:
7032:
7033: strcpy(dirfileres,optionfilefiname);
7034: strcpy(optfileres,"vpl");
7035: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
7036: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
7037: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
7038: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
7039: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
7040:
7041: }
7042:
7043: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
7044: {
7045:
7046: /*-------- data file ----------*/
7047: FILE *fic;
7048: char dummy[]=" ";
7049: int i=0, j=0, n=0;
7050: int linei, month, year,iout;
7051: char line[MAXLINE], linetmp[MAXLINE];
7052: char stra[MAXLINE], strb[MAXLINE];
7053: char *stratrunc;
7054: int lstra;
7055:
7056:
7057: if((fic=fopen(datafile,"r"))==NULL) {
7058: printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
7059: fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
7060: }
7061:
7062: i=1;
7063: linei=0;
7064: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
7065: linei=linei+1;
7066: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
7067: if(line[j] == '\t')
7068: line[j] = ' ';
7069: }
7070: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
7071: ;
7072: };
7073: line[j+1]=0; /* Trims blanks at end of line */
7074: if(line[0]=='#'){
7075: fprintf(ficlog,"Comment line\n%s\n",line);
7076: printf("Comment line\n%s\n",line);
7077: continue;
7078: }
7079: trimbb(linetmp,line); /* Trims multiple blanks in line */
7080: strcpy(line, linetmp);
7081:
7082:
7083: for (j=maxwav;j>=1;j--){
7084: cutv(stra, strb, line, ' ');
7085: if(strb[0]=='.') { /* Missing status */
7086: lval=-1;
7087: }else{
7088: errno=0;
7089: lval=strtol(strb,&endptr,10);
7090: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
7091: if( strb[0]=='\0' || (*endptr != '\0')){
7092: 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);
7093: 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);
7094: return 1;
7095: }
7096: }
7097: s[j][i]=lval;
7098:
7099: strcpy(line,stra);
7100: cutv(stra, strb,line,' ');
7101: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7102: }
7103: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
7104: month=99;
7105: year=9999;
7106: }else{
7107: 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);
7108: 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);
7109: return 1;
7110: }
7111: anint[j][i]= (double) year;
7112: mint[j][i]= (double)month;
7113: strcpy(line,stra);
7114: } /* ENd Waves */
7115:
7116: cutv(stra, strb,line,' ');
7117: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7118: }
7119: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
7120: month=99;
7121: year=9999;
7122: }else{
7123: 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);
7124: 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);
7125: return 1;
7126: }
7127: andc[i]=(double) year;
7128: moisdc[i]=(double) month;
7129: strcpy(line,stra);
7130:
7131: cutv(stra, strb,line,' ');
7132: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
7133: }
7134: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
7135: month=99;
7136: year=9999;
7137: }else{
7138: 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);
7139: 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);
7140: return 1;
7141: }
7142: if (year==9999) {
7143: 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);
7144: 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);
7145: return 1;
7146:
7147: }
7148: annais[i]=(double)(year);
7149: moisnais[i]=(double)(month);
7150: strcpy(line,stra);
7151:
7152: cutv(stra, strb,line,' ');
7153: errno=0;
7154: dval=strtod(strb,&endptr);
7155: if( strb[0]=='\0' || (*endptr != '\0')){
7156: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
7157: 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);
7158: fflush(ficlog);
7159: return 1;
7160: }
7161: weight[i]=dval;
7162: strcpy(line,stra);
7163:
7164: for (j=ncovcol;j>=1;j--){
7165: cutv(stra, strb,line,' ');
7166: if(strb[0]=='.') { /* Missing status */
7167: lval=-1;
7168: }else{
7169: errno=0;
7170: lval=strtol(strb,&endptr,10);
7171: if( strb[0]=='\0' || (*endptr != '\0')){
7172: 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);
7173: 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);
7174: return 1;
7175: }
7176: }
7177: if(lval <-1 || lval >1){
7178: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
7179: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
7180: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
7181: For example, for multinomial values like 1, 2 and 3,\n \
7182: build V1=0 V2=0 for the reference value (1),\n \
7183: V1=1 V2=0 for (2) \n \
7184: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
7185: output of IMaCh is often meaningless.\n \
7186: Exiting.\n",lval,linei, i,line,j);
7187: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
7188: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
7189: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
7190: For example, for multinomial values like 1, 2 and 3,\n \
7191: build V1=0 V2=0 for the reference value (1),\n \
7192: V1=1 V2=0 for (2) \n \
7193: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
7194: output of IMaCh is often meaningless.\n \
7195: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
7196: return 1;
7197: }
7198: covar[j][i]=(double)(lval);
7199: strcpy(line,stra);
7200: }
7201: lstra=strlen(stra);
7202:
7203: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
7204: stratrunc = &(stra[lstra-9]);
7205: num[i]=atol(stratrunc);
7206: }
7207: else
7208: num[i]=atol(stra);
7209: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
7210: 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;}*/
7211:
7212: i=i+1;
7213: } /* End loop reading data */
7214:
7215: *imax=i-1; /* Number of individuals */
7216: fclose(fic);
7217:
7218: return (0);
7219: /* endread: */
7220: printf("Exiting readdata: ");
7221: fclose(fic);
7222: return (1);
7223:
7224:
7225:
7226: }
7227: void removespace(char *str) {
7228: char *p1 = str, *p2 = str;
7229: do
7230: while (*p2 == ' ')
7231: p2++;
7232: while (*p1++ == *p2++);
7233: }
7234:
7235: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
7236: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
7237: * - nagesqr = 1 if age*age in the model, otherwise 0.
7238: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
7239: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
7240: * - cptcovage number of covariates with age*products =2
7241: * - cptcovs number of simple covariates
7242: * - 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
7243: * which is a new column after the 9 (ncovcol) variables.
7244: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
7245: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
7246: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
7247: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
7248: */
7249: {
7250: int i, j, k, ks;
7251: int j1, k1, k2;
7252: char modelsav[80];
7253: char stra[80], strb[80], strc[80], strd[80],stre[80];
7254: char *strpt;
7255:
7256: /*removespace(model);*/
7257: if (strlen(model) >1){ /* If there is at least 1 covariate */
7258: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
7259: if (strstr(model,"AGE") !=0){
7260: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
7261: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
7262: return 1;
7263: }
7264: if (strstr(model,"v") !=0){
7265: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
7266: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
7267: return 1;
7268: }
7269: strcpy(modelsav,model);
7270: if ((strpt=strstr(model,"age*age")) !=0){
7271: printf(" strpt=%s, model=%s\n",strpt, model);
7272: if(strpt != model){
7273: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
7274: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
7275: corresponding column of parameters.\n",model);
7276: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
7277: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
7278: corresponding column of parameters.\n",model); fflush(ficlog);
7279: return 1;
7280: }
7281:
7282: nagesqr=1;
7283: if (strstr(model,"+age*age") !=0)
7284: substrchaine(modelsav, model, "+age*age");
7285: else if (strstr(model,"age*age+") !=0)
7286: substrchaine(modelsav, model, "age*age+");
7287: else
7288: substrchaine(modelsav, model, "age*age");
7289: }else
7290: nagesqr=0;
7291: if (strlen(modelsav) >1){
7292: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
7293: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
7294: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
7295: cptcovt= j+1; /* Number of total covariates in the model, not including
7296: * cst, age and age*age
7297: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
7298: /* including age products which are counted in cptcovage.
7299: * but the covariates which are products must be treated
7300: * separately: ncovn=4- 2=2 (V1+V3). */
7301: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
7302: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
7303:
7304:
7305: /* Design
7306: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
7307: * < ncovcol=8 >
7308: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
7309: * k= 1 2 3 4 5 6 7 8
7310: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
7311: * covar[k,i], value of kth covariate if not including age for individual i:
7312: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
7313: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
7314: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
7315: * Tage[++cptcovage]=k
7316: * if products, new covar are created after ncovcol with k1
7317: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
7318: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
7319: * 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
7320: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
7321: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
7322: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
7323: * < ncovcol=8 >
7324: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
7325: * k= 1 2 3 4 5 6 7 8 9 10 11 12
7326: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
7327: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
7328: * p Tprod[1]@2={ 6, 5}
7329: *p Tvard[1][1]@4= {7, 8, 5, 6}
7330: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
7331: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
7332: *How to reorganize?
7333: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
7334: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
7335: * {2, 1, 4, 8, 5, 6, 3, 7}
7336: * Struct []
7337: */
7338:
7339: /* This loop fills the array Tvar from the string 'model'.*/
7340: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
7341: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
7342: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
7343: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
7344: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
7345: /* k=1 Tvar[1]=2 (from V2) */
7346: /* k=5 Tvar[5] */
7347: /* for (k=1; k<=cptcovn;k++) { */
7348: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
7349: /* } */
7350: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
7351: /*
7352: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
7353: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
7354: Tvar[k]=0;
7355: cptcovage=0;
7356: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
7357: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
7358: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
7359: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
7360: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
7361: /*scanf("%d",i);*/
7362: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
7363: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
7364: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
7365: /* covar is not filled and then is empty */
7366: cptcovprod--;
7367: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
7368: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
7369: cptcovage++; /* Sums the number of covariates which include age as a product */
7370: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
7371: /*printf("stre=%s ", stre);*/
7372: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
7373: cptcovprod--;
7374: cutl(stre,strb,strc,'V');
7375: Tvar[k]=atoi(stre);
7376: cptcovage++;
7377: Tage[cptcovage]=k;
7378: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
7379: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
7380: cptcovn++;
7381: cptcovprodnoage++;k1++;
7382: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
7383: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
7384: because this model-covariate is a construction we invent a new column
7385: ncovcol + k1
7386: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
7387: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
7388: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
7389: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
7390: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
7391: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
7392: k2=k2+2;
7393: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
7394: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
7395: for (i=1; i<=lastobs;i++){
7396: /* Computes the new covariate which is a product of
7397: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
7398: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
7399: }
7400: } /* End age is not in the model */
7401: } /* End if model includes a product */
7402: else { /* no more sum */
7403: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
7404: /* scanf("%d",i);*/
7405: cutl(strd,strc,strb,'V');
7406: ks++; /**< Number of simple covariates */
7407: cptcovn++;
7408: Tvar[k]=atoi(strd);
7409: }
7410: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
7411: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
7412: scanf("%d",i);*/
7413: } /* end of loop + on total covariates */
7414: } /* end if strlen(modelsave == 0) age*age might exist */
7415: } /* end if strlen(model == 0) */
7416:
7417: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
7418: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
7419:
7420: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
7421: printf("cptcovprod=%d ", cptcovprod);
7422: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
7423:
7424: scanf("%d ",i);*/
7425:
7426:
7427: return (0); /* with covar[new additional covariate if product] and Tage if age */
7428: /*endread:*/
7429: printf("Exiting decodemodel: ");
7430: return (1);
7431: }
7432:
7433: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
7434: {
7435: int i, m;
7436: int firstone=0;
7437:
7438: for (i=1; i<=imx; i++) {
7439: for(m=2; (m<= maxwav); m++) {
7440: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
7441: anint[m][i]=9999;
7442: if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
7443: s[m][i]=-1;
7444: }
7445: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
7446: *nberr = *nberr + 1;
7447: if(firstone == 0){
7448: firstone=1;
7449: 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);
7450: }
7451: 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);
7452: s[m][i]=-1;
7453: }
7454: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
7455: (*nberr)++;
7456: 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]);
7457: 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]);
7458: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
7459: }
7460: }
7461: }
7462:
7463: for (i=1; i<=imx; i++) {
7464: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
7465: for(m=firstpass; (m<= lastpass); m++){
7466: 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 */
7467: if (s[m][i] >= nlstate+1) {
7468: if(agedc[i]>0){
7469: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
7470: agev[m][i]=agedc[i];
7471: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
7472: }else {
7473: if ((int)andc[i]!=9999){
7474: nbwarn++;
7475: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
7476: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
7477: agev[m][i]=-1;
7478: }
7479: }
7480: } /* agedc > 0 */
7481: } /* end if */
7482: else if(s[m][i] !=9){ /* Standard case, age in fractional
7483: years but with the precision of a month */
7484: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
7485: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
7486: agev[m][i]=1;
7487: else if(agev[m][i] < *agemin){
7488: *agemin=agev[m][i];
7489: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
7490: }
7491: else if(agev[m][i] >*agemax){
7492: *agemax=agev[m][i];
7493: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
7494: }
7495: /*agev[m][i]=anint[m][i]-annais[i];*/
7496: /* agev[m][i] = age[i]+2*m;*/
7497: } /* en if 9*/
7498: else { /* =9 */
7499: /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
7500: agev[m][i]=1;
7501: s[m][i]=-1;
7502: }
7503: }
7504: else if(s[m][i]==0) /*= 0 Unknown */
7505: agev[m][i]=1;
7506: else{
7507: printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
7508: fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
7509: agev[m][i]=0;
7510: }
7511: } /* End for lastpass */
7512: }
7513:
7514: for (i=1; i<=imx; i++) {
7515: for(m=firstpass; (m<=lastpass); m++){
7516: if (s[m][i] > (nlstate+ndeath)) {
7517: (*nberr)++;
7518: 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);
7519: 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);
7520: return 1;
7521: }
7522: }
7523: }
7524:
7525: /*for (i=1; i<=imx; i++){
7526: for (m=firstpass; (m<lastpass); m++){
7527: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
7528: }
7529:
7530: }*/
7531:
7532:
7533: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
7534: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
7535:
7536: return (0);
7537: /* endread:*/
7538: printf("Exiting calandcheckages: ");
7539: return (1);
7540: }
7541:
7542: #if defined(_MSC_VER)
7543: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
7544: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
7545: //#include "stdafx.h"
7546: //#include <stdio.h>
7547: //#include <tchar.h>
7548: //#include <windows.h>
7549: //#include <iostream>
7550: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
7551:
7552: LPFN_ISWOW64PROCESS fnIsWow64Process;
7553:
7554: BOOL IsWow64()
7555: {
7556: BOOL bIsWow64 = FALSE;
7557:
7558: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
7559: // (HANDLE, PBOOL);
7560:
7561: //LPFN_ISWOW64PROCESS fnIsWow64Process;
7562:
7563: HMODULE module = GetModuleHandle(_T("kernel32"));
7564: const char funcName[] = "IsWow64Process";
7565: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
7566: GetProcAddress(module, funcName);
7567:
7568: if (NULL != fnIsWow64Process)
7569: {
7570: if (!fnIsWow64Process(GetCurrentProcess(),
7571: &bIsWow64))
7572: //throw std::exception("Unknown error");
7573: printf("Unknown error\n");
7574: }
7575: return bIsWow64 != FALSE;
7576: }
7577: #endif
7578:
7579: void syscompilerinfo(int logged)
7580: {
7581: /* #include "syscompilerinfo.h"*/
7582: /* command line Intel compiler 32bit windows, XP compatible:*/
7583: /* /GS /W3 /Gy
7584: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
7585: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
7586: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
7587: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
7588: */
7589: /* 64 bits */
7590: /*
7591: /GS /W3 /Gy
7592: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
7593: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
7594: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
7595: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
7596: /* Optimization are useless and O3 is slower than O2 */
7597: /*
7598: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
7599: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
7600: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
7601: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
7602: */
7603: /* Link is */ /* /OUT:"visual studio
7604: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
7605: /PDB:"visual studio
7606: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
7607: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
7608: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
7609: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
7610: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
7611: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
7612: uiAccess='false'"
7613: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
7614: /NOLOGO /TLBID:1
7615: */
7616: #if defined __INTEL_COMPILER
7617: #if defined(__GNUC__)
7618: struct utsname sysInfo; /* For Intel on Linux and OS/X */
7619: #endif
7620: #elif defined(__GNUC__)
7621: #ifndef __APPLE__
7622: #include <gnu/libc-version.h> /* Only on gnu */
7623: #endif
7624: struct utsname sysInfo;
7625: int cross = CROSS;
7626: if (cross){
7627: printf("Cross-");
7628: if(logged) fprintf(ficlog, "Cross-");
7629: }
7630: #endif
7631:
7632: #include <stdint.h>
7633:
7634: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
7635: #if defined(__clang__)
7636: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
7637: #endif
7638: #if defined(__ICC) || defined(__INTEL_COMPILER)
7639: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
7640: #endif
7641: #if defined(__GNUC__) || defined(__GNUG__)
7642: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
7643: #endif
7644: #if defined(__HP_cc) || defined(__HP_aCC)
7645: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
7646: #endif
7647: #if defined(__IBMC__) || defined(__IBMCPP__)
7648: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
7649: #endif
7650: #if defined(_MSC_VER)
7651: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
7652: #endif
7653: #if defined(__PGI)
7654: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
7655: #endif
7656: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
7657: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
7658: #endif
7659: printf(" for "); if (logged) fprintf(ficlog, " for ");
7660:
7661: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
7662: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
7663: // Windows (x64 and x86)
7664: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
7665: #elif __unix__ // all unices, not all compilers
7666: // Unix
7667: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
7668: #elif __linux__
7669: // linux
7670: printf("linux ");if(logged) fprintf(ficlog,"linux ");
7671: #elif __APPLE__
7672: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
7673: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
7674: #endif
7675:
7676: /* __MINGW32__ */
7677: /* __CYGWIN__ */
7678: /* __MINGW64__ */
7679: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
7680: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
7681: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
7682: /* _WIN64 // Defined for applications for Win64. */
7683: /* _M_X64 // Defined for compilations that target x64 processors. */
7684: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
7685:
7686: #if UINTPTR_MAX == 0xffffffff
7687: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
7688: #elif UINTPTR_MAX == 0xffffffffffffffff
7689: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
7690: #else
7691: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
7692: #endif
7693:
7694: #if defined(__GNUC__)
7695: # if defined(__GNUC_PATCHLEVEL__)
7696: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
7697: + __GNUC_MINOR__ * 100 \
7698: + __GNUC_PATCHLEVEL__)
7699: # else
7700: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
7701: + __GNUC_MINOR__ * 100)
7702: # endif
7703: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
7704: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
7705:
7706: if (uname(&sysInfo) != -1) {
7707: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
7708: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
7709: }
7710: else
7711: perror("uname() error");
7712: //#ifndef __INTEL_COMPILER
7713: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
7714: printf("GNU libc version: %s\n", gnu_get_libc_version());
7715: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
7716: #endif
7717: #endif
7718:
7719: // void main()
7720: // {
7721: #if defined(_MSC_VER)
7722: if (IsWow64()){
7723: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
7724: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
7725: }
7726: else{
7727: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
7728: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
7729: }
7730: // printf("\nPress Enter to continue...");
7731: // getchar();
7732: // }
7733:
7734: #endif
7735:
7736:
7737: }
7738:
7739: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
7740: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
7741: int i, j, k, i1 ;
7742: /* double ftolpl = 1.e-10; */
7743: double age, agebase, agelim;
7744: double tot;
7745:
7746: strcpy(filerespl,"PL_");
7747: strcat(filerespl,fileresu);
7748: if((ficrespl=fopen(filerespl,"w"))==NULL) {
7749: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
7750: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
7751: }
7752: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
7753: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
7754: pstamp(ficrespl);
7755: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
7756: fprintf(ficrespl,"#Age ");
7757: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
7758: fprintf(ficrespl,"\n");
7759:
7760: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
7761:
7762: agebase=ageminpar;
7763: agelim=agemaxpar;
7764:
7765: i1=pow(2,cptcoveff);
7766: if (cptcovn < 1){i1=1;}
7767:
7768: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7769: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
7770: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
7771: k=k+1;
7772: /* to clean */
7773: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
7774: fprintf(ficrespl,"#******");
7775: printf("#******");
7776: fprintf(ficlog,"#******");
7777: for(j=1;j<=cptcoveff;j++) {
7778: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7779: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7780: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7781: }
7782: fprintf(ficrespl,"******\n");
7783: printf("******\n");
7784: fprintf(ficlog,"******\n");
7785:
7786: fprintf(ficrespl,"#Age ");
7787: for(j=1;j<=cptcoveff;j++) {
7788: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7789: }
7790: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
7791: fprintf(ficrespl,"Total Years_to_converge\n");
7792:
7793: for (age=agebase; age<=agelim; age++){
7794: /* for (age=agebase; age<=agebase; age++){ */
7795: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
7796: fprintf(ficrespl,"%.0f ",age );
7797: for(j=1;j<=cptcoveff;j++)
7798: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7799: tot=0.;
7800: for(i=1; i<=nlstate;i++){
7801: tot += prlim[i][i];
7802: fprintf(ficrespl," %.5f", prlim[i][i]);
7803: }
7804: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
7805: } /* Age */
7806: /* was end of cptcod */
7807: } /* cptcov */
7808: return 0;
7809: }
7810:
7811: 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){
7812: /*--------------- Back Prevalence limit (period or stable prevalence) --------------*/
7813:
7814: /* Computes the back prevalence limit for any combination of covariate values
7815: * at any age between ageminpar and agemaxpar
7816: */
7817: int i, j, k, i1 ;
7818: /* double ftolpl = 1.e-10; */
7819: double age, agebase, agelim;
7820: double tot;
7821: /* double ***mobaverage; */
7822: /* double **dnewm, **doldm, **dsavm; /\* for use *\/ */
7823:
7824: strcpy(fileresplb,"PLB_");
7825: strcat(fileresplb,fileresu);
7826: if((ficresplb=fopen(fileresplb,"w"))==NULL) {
7827: printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
7828: fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
7829: }
7830: printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
7831: fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
7832: pstamp(ficresplb);
7833: fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
7834: fprintf(ficresplb,"#Age ");
7835: for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
7836: fprintf(ficresplb,"\n");
7837:
7838:
7839: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
7840:
7841: agebase=ageminpar;
7842: agelim=agemaxpar;
7843:
7844:
7845: i1=pow(2,cptcoveff);
7846: if (cptcovn < 1){i1=1;}
7847:
7848: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7849: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
7850: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
7851: k=k+1;
7852: /* to clean */
7853: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
7854: fprintf(ficresplb,"#******");
7855: printf("#******");
7856: fprintf(ficlog,"#******");
7857: for(j=1;j<=cptcoveff;j++) {
7858: fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7859: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7860: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7861: }
7862: fprintf(ficresplb,"******\n");
7863: printf("******\n");
7864: fprintf(ficlog,"******\n");
7865:
7866: fprintf(ficresplb,"#Age ");
7867: for(j=1;j<=cptcoveff;j++) {
7868: fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7869: }
7870: for(i=1; i<=nlstate;i++) fprintf(ficresplb," %d-%d ",i,i);
7871: fprintf(ficresplb,"Total Years_to_converge\n");
7872:
7873:
7874: for (age=agebase; age<=agelim; age++){
7875: /* for (age=agebase; age<=agebase; age++){ */
7876: if(mobilavproj > 0){
7877: /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
7878: /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
7879: bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
7880: }else if (mobilavproj == 0){
7881: 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);
7882: 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);
7883: exit(1);
7884: }else{
7885: /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
7886: bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
7887: }
7888: fprintf(ficresplb,"%.0f ",age );
7889: for(j=1;j<=cptcoveff;j++)
7890: fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7891: tot=0.;
7892: for(i=1; i<=nlstate;i++){
7893: tot += bprlim[i][i];
7894: fprintf(ficresplb," %.5f", bprlim[i][i]);
7895: }
7896: fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
7897: } /* Age */
7898: /* was end of cptcod */
7899: } /* cptcov */
7900:
7901: /* hBijx(p, bage, fage); */
7902: /* fclose(ficrespijb); */
7903:
7904: return 0;
7905: }
7906:
7907: int hPijx(double *p, int bage, int fage){
7908: /*------------- h Pij x at various ages ------------*/
7909:
7910: int stepsize;
7911: int agelim;
7912: int hstepm;
7913: int nhstepm;
7914: int h, i, i1, j, k;
7915:
7916: double agedeb;
7917: double ***p3mat;
7918:
7919: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
7920: if((ficrespij=fopen(filerespij,"w"))==NULL) {
7921: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
7922: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
7923: }
7924: printf("Computing pij: result on file '%s' \n", filerespij);
7925: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
7926:
7927: stepsize=(int) (stepm+YEARM-1)/YEARM;
7928: /*if (stepm<=24) stepsize=2;*/
7929:
7930: agelim=AGESUP;
7931: hstepm=stepsize*YEARM; /* Every year of age */
7932: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
7933:
7934: /* hstepm=1; aff par mois*/
7935: pstamp(ficrespij);
7936: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
7937: i1= pow(2,cptcoveff);
7938: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
7939: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
7940: /* k=k+1; */
7941: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7942: fprintf(ficrespij,"\n#****** ");
7943: for(j=1;j<=cptcoveff;j++)
7944: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7945: fprintf(ficrespij,"******\n");
7946:
7947: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
7948: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
7949: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
7950:
7951: /* nhstepm=nhstepm*YEARM; aff par mois*/
7952:
7953: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7954: oldm=oldms;savm=savms;
7955: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
7956: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
7957: for(i=1; i<=nlstate;i++)
7958: for(j=1; j<=nlstate+ndeath;j++)
7959: fprintf(ficrespij," %1d-%1d",i,j);
7960: fprintf(ficrespij,"\n");
7961: for (h=0; h<=nhstepm; h++){
7962: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
7963: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
7964: for(i=1; i<=nlstate;i++)
7965: for(j=1; j<=nlstate+ndeath;j++)
7966: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
7967: fprintf(ficrespij,"\n");
7968: }
7969: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7970: fprintf(ficrespij,"\n");
7971: }
7972: /*}*/
7973: }
7974: return 0;
7975: }
7976:
7977: int hBijx(double *p, int bage, int fage, double ***prevacurrent){
7978: /*------------- h Bij x at various ages ------------*/
7979:
7980: int stepsize;
7981: /* int agelim; */
7982: int ageminl;
7983: int hstepm;
7984: int nhstepm;
7985: int h, i, i1, j, k;
7986:
7987: double agedeb;
7988: double ***p3mat;
7989:
7990: strcpy(filerespijb,"PIJB_"); strcat(filerespijb,fileresu);
7991: if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
7992: printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
7993: fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
7994: }
7995: printf("Computing pij back: result on file '%s' \n", filerespijb);
7996: fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
7997:
7998: stepsize=(int) (stepm+YEARM-1)/YEARM;
7999: /*if (stepm<=24) stepsize=2;*/
8000:
8001: /* agelim=AGESUP; */
8002: ageminl=30;
8003: hstepm=stepsize*YEARM; /* Every year of age */
8004: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
8005:
8006: /* hstepm=1; aff par mois*/
8007: pstamp(ficrespijb);
8008: fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
8009: i1= pow(2,cptcoveff);
8010: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
8011: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
8012: /* k=k+1; */
8013: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8014: fprintf(ficrespijb,"\n#****** ");
8015: for(j=1;j<=cptcoveff;j++)
8016: fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8017: fprintf(ficrespijb,"******\n");
8018:
8019: /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
8020: for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
8021: /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
8022: nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
8023: nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
8024:
8025: /* nhstepm=nhstepm*YEARM; aff par mois*/
8026:
8027: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
8028: /* oldm=oldms;savm=savms; */
8029: /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); */
8030: hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
8031: /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
8032: fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
8033: for(i=1; i<=nlstate;i++)
8034: for(j=1; j<=nlstate+ndeath;j++)
8035: fprintf(ficrespijb," %1d-%1d",i,j);
8036: fprintf(ficrespijb,"\n");
8037: for (h=0; h<=nhstepm; h++){
8038: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
8039: fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
8040: /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
8041: for(i=1; i<=nlstate;i++)
8042: for(j=1; j<=nlstate+ndeath;j++)
8043: fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
8044: fprintf(ficrespijb,"\n");
8045: }
8046: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
8047: fprintf(ficrespijb,"\n");
8048: }
8049: /*}*/
8050: }
8051: return 0;
8052: } /* hBijx */
8053:
8054:
8055: /***********************************************/
8056: /**************** Main Program *****************/
8057: /***********************************************/
8058:
8059: int main(int argc, char *argv[])
8060: {
8061: #ifdef GSL
8062: const gsl_multimin_fminimizer_type *T;
8063: size_t iteri = 0, it;
8064: int rval = GSL_CONTINUE;
8065: int status = GSL_SUCCESS;
8066: double ssval;
8067: #endif
8068: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
8069: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
8070: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
8071: int jj, ll, li, lj, lk;
8072: int numlinepar=0; /* Current linenumber of parameter file */
8073: int num_filled;
8074: int itimes;
8075: int NDIM=2;
8076: int vpopbased=0;
8077:
8078: char ca[32], cb[32];
8079: /* FILE *fichtm; *//* Html File */
8080: /* FILE *ficgp;*/ /*Gnuplot File */
8081: struct stat info;
8082: double agedeb=0.;
8083:
8084: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
8085: double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
8086:
8087: double fret;
8088: double dum=0.; /* Dummy variable */
8089: double ***p3mat;
8090: /* double ***mobaverage; */
8091:
8092: char line[MAXLINE];
8093: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
8094:
8095: char model[MAXLINE], modeltemp[MAXLINE];
8096: char pathr[MAXLINE], pathimach[MAXLINE];
8097: char *tok, *val; /* pathtot */
8098: int firstobs=1, lastobs=10;
8099: int c, h , cpt, c2;
8100: int jl=0;
8101: int i1, j1, jk, stepsize=0;
8102: int count=0;
8103:
8104: int *tab;
8105: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
8106: int backcast=0;
8107: int mobilav=0,popforecast=0;
8108: int hstepm=0, nhstepm=0;
8109: int agemortsup;
8110: float sumlpop=0.;
8111: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
8112: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
8113:
8114: double bage=0, fage=110., age, agelim=0., agebase=0.;
8115: double ftolpl=FTOL;
8116: double **prlim;
8117: double **bprlim;
8118: double ***param; /* Matrix of parameters */
8119: double *p;
8120: double **matcov; /* Matrix of covariance */
8121: double **hess; /* Hessian matrix */
8122: double ***delti3; /* Scale */
8123: double *delti; /* Scale */
8124: double ***eij, ***vareij;
8125: double **varpl; /* Variances of prevalence limits by age */
8126: double *epj, vepp;
8127:
8128: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
8129: double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
8130:
8131: double **ximort;
8132: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
8133: int *dcwave;
8134:
8135: char z[1]="c";
8136:
8137: /*char *strt;*/
8138: char strtend[80];
8139:
8140:
8141: /* setlocale (LC_ALL, ""); */
8142: /* bindtextdomain (PACKAGE, LOCALEDIR); */
8143: /* textdomain (PACKAGE); */
8144: /* setlocale (LC_CTYPE, ""); */
8145: /* setlocale (LC_MESSAGES, ""); */
8146:
8147: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
8148: rstart_time = time(NULL);
8149: /* (void) gettimeofday(&start_time,&tzp);*/
8150: start_time = *localtime(&rstart_time);
8151: curr_time=start_time;
8152: /*tml = *localtime(&start_time.tm_sec);*/
8153: /* strcpy(strstart,asctime(&tml)); */
8154: strcpy(strstart,asctime(&start_time));
8155:
8156: /* printf("Localtime (at start)=%s",strstart); */
8157: /* tp.tm_sec = tp.tm_sec +86400; */
8158: /* tm = *localtime(&start_time.tm_sec); */
8159: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
8160: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
8161: /* tmg.tm_hour=tmg.tm_hour + 1; */
8162: /* tp.tm_sec = mktime(&tmg); */
8163: /* strt=asctime(&tmg); */
8164: /* printf("Time(after) =%s",strstart); */
8165: /* (void) time (&time_value);
8166: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
8167: * tm = *localtime(&time_value);
8168: * strstart=asctime(&tm);
8169: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
8170: */
8171:
8172: nberr=0; /* Number of errors and warnings */
8173: nbwarn=0;
8174: #ifdef WIN32
8175: _getcwd(pathcd, size);
8176: #else
8177: getcwd(pathcd, size);
8178: #endif
8179: syscompilerinfo(0);
8180: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
8181: if(argc <=1){
8182: printf("\nEnter the parameter file name: ");
8183: if(!fgets(pathr,FILENAMELENGTH,stdin)){
8184: printf("ERROR Empty parameter file name\n");
8185: goto end;
8186: }
8187: i=strlen(pathr);
8188: if(pathr[i-1]=='\n')
8189: pathr[i-1]='\0';
8190: i=strlen(pathr);
8191: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
8192: pathr[i-1]='\0';
8193: }
8194: i=strlen(pathr);
8195: if( i==0 ){
8196: printf("ERROR Empty parameter file name\n");
8197: goto end;
8198: }
8199: for (tok = pathr; tok != NULL; ){
8200: printf("Pathr |%s|\n",pathr);
8201: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
8202: printf("val= |%s| pathr=%s\n",val,pathr);
8203: strcpy (pathtot, val);
8204: if(pathr[0] == '\0') break; /* Dirty */
8205: }
8206: }
8207: else{
8208: strcpy(pathtot,argv[1]);
8209: }
8210: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
8211: /*cygwin_split_path(pathtot,path,optionfile);
8212: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
8213: /* cutv(path,optionfile,pathtot,'\\');*/
8214:
8215: /* Split argv[0], imach program to get pathimach */
8216: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
8217: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
8218: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
8219: /* strcpy(pathimach,argv[0]); */
8220: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
8221: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
8222: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
8223: #ifdef WIN32
8224: _chdir(path); /* Can be a relative path */
8225: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
8226: #else
8227: chdir(path); /* Can be a relative path */
8228: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
8229: #endif
8230: printf("Current directory %s!\n",pathcd);
8231: strcpy(command,"mkdir ");
8232: strcat(command,optionfilefiname);
8233: if((outcmd=system(command)) != 0){
8234: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
8235: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
8236: /* fclose(ficlog); */
8237: /* exit(1); */
8238: }
8239: /* if((imk=mkdir(optionfilefiname))<0){ */
8240: /* perror("mkdir"); */
8241: /* } */
8242:
8243: /*-------- arguments in the command line --------*/
8244:
8245: /* Main Log file */
8246: strcat(filelog, optionfilefiname);
8247: strcat(filelog,".log"); /* */
8248: if((ficlog=fopen(filelog,"w"))==NULL) {
8249: printf("Problem with logfile %s\n",filelog);
8250: goto end;
8251: }
8252: fprintf(ficlog,"Log filename:%s\n",filelog);
8253: fprintf(ficlog,"Version %s %s",version,fullversion);
8254: fprintf(ficlog,"\nEnter the parameter file name: \n");
8255: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
8256: path=%s \n\
8257: optionfile=%s\n\
8258: optionfilext=%s\n\
8259: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
8260:
8261: syscompilerinfo(1);
8262:
8263: printf("Local time (at start):%s",strstart);
8264: fprintf(ficlog,"Local time (at start): %s",strstart);
8265: fflush(ficlog);
8266: /* (void) gettimeofday(&curr_time,&tzp); */
8267: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
8268:
8269: /* */
8270: strcpy(fileres,"r");
8271: strcat(fileres, optionfilefiname);
8272: strcat(fileresu, optionfilefiname); /* Without r in front */
8273: strcat(fileres,".txt"); /* Other files have txt extension */
8274: strcat(fileresu,".txt"); /* Other files have txt extension */
8275:
8276: /* Main ---------arguments file --------*/
8277:
8278: if((ficpar=fopen(optionfile,"r"))==NULL) {
8279: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
8280: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
8281: fflush(ficlog);
8282: /* goto end; */
8283: exit(70);
8284: }
8285:
8286:
8287:
8288: strcpy(filereso,"o");
8289: strcat(filereso,fileresu);
8290: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
8291: printf("Problem with Output resultfile: %s\n", filereso);
8292: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
8293: fflush(ficlog);
8294: goto end;
8295: }
8296:
8297: /* Reads comments: lines beginning with '#' */
8298: numlinepar=0;
8299:
8300: /* First parameter line */
8301: while(fgets(line, MAXLINE, ficpar)) {
8302: /* If line starts with a # it is a comment */
8303: if (line[0] == '#') {
8304: numlinepar++;
8305: fputs(line,stdout);
8306: fputs(line,ficparo);
8307: fputs(line,ficlog);
8308: continue;
8309: }else
8310: break;
8311: }
8312: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
8313: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
8314: if (num_filled != 5) {
8315: printf("Should be 5 parameters\n");
8316: }
8317: numlinepar++;
8318: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
8319: }
8320: /* Second parameter line */
8321: while(fgets(line, MAXLINE, ficpar)) {
8322: /* If line starts with a # it is a comment */
8323: if (line[0] == '#') {
8324: numlinepar++;
8325: fputs(line,stdout);
8326: fputs(line,ficparo);
8327: fputs(line,ficlog);
8328: continue;
8329: }else
8330: break;
8331: }
8332: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
8333: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
8334: if (num_filled != 8) {
8335: printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
8336: printf("but line=%s\n",line);
8337: }
8338: printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
8339: }
8340: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8341: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8342: /* Third parameter line */
8343: while(fgets(line, MAXLINE, ficpar)) {
8344: /* If line starts with a # it is a comment */
8345: if (line[0] == '#') {
8346: numlinepar++;
8347: fputs(line,stdout);
8348: fputs(line,ficparo);
8349: fputs(line,ficlog);
8350: continue;
8351: }else
8352: break;
8353: }
8354: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
8355: if (num_filled == 0)
8356: model[0]='\0';
8357: else if (num_filled != 1){
8358: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
8359: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
8360: model[0]='\0';
8361: goto end;
8362: }
8363: else{
8364: if (model[0]=='+'){
8365: for(i=1; i<=strlen(model);i++)
8366: modeltemp[i-1]=model[i];
8367: strcpy(model,modeltemp);
8368: }
8369: }
8370: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
8371: printf("model=1+age+%s\n",model);fflush(stdout);
8372: }
8373: /* 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); */
8374: /* numlinepar=numlinepar+3; /\* In general *\/ */
8375: /* 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); */
8376: fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
8377: fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
8378: fflush(ficlog);
8379: /* if(model[0]=='#'|| model[0]== '\0'){ */
8380: if(model[0]=='#'){
8381: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
8382: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
8383: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
8384: if(mle != -1){
8385: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
8386: exit(1);
8387: }
8388: }
8389: while((c=getc(ficpar))=='#' && c!= EOF){
8390: ungetc(c,ficpar);
8391: fgets(line, MAXLINE, ficpar);
8392: numlinepar++;
8393: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
8394: z[0]=line[1];
8395: }
8396: /* printf("****line [1] = %c \n",line[1]); */
8397: fputs(line, stdout);
8398: //puts(line);
8399: fputs(line,ficparo);
8400: fputs(line,ficlog);
8401: }
8402: ungetc(c,ficpar);
8403:
8404:
8405: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
8406: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
8407: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
8408: v1+v2*age+v2*v3 makes cptcovn = 3
8409: */
8410: if (strlen(model)>1)
8411: 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*/
8412: else
8413: ncovmodel=2; /* Constant and age */
8414: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
8415: npar= nforce*ncovmodel; /* Number of parameters like aij*/
8416: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
8417: 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);
8418: 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);
8419: fflush(stdout);
8420: fclose (ficlog);
8421: goto end;
8422: }
8423: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
8424: delti=delti3[1][1];
8425: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
8426: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
8427: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
8428: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
8429: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
8430: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8431: fclose (ficparo);
8432: fclose (ficlog);
8433: goto end;
8434: exit(0);
8435: }
8436: else if(mle==-3) { /* Main Wizard */
8437: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
8438: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
8439: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
8440: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
8441: matcov=matrix(1,npar,1,npar);
8442: hess=matrix(1,npar,1,npar);
8443: }
8444: else{
8445: /* Read guessed parameters */
8446: /* Reads comments: lines beginning with '#' */
8447: while((c=getc(ficpar))=='#' && c!= EOF){
8448: ungetc(c,ficpar);
8449: fgets(line, MAXLINE, ficpar);
8450: numlinepar++;
8451: fputs(line,stdout);
8452: fputs(line,ficparo);
8453: fputs(line,ficlog);
8454: }
8455: ungetc(c,ficpar);
8456:
8457: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
8458: for(i=1; i <=nlstate; i++){
8459: j=0;
8460: for(jj=1; jj <=nlstate+ndeath; jj++){
8461: if(jj==i) continue;
8462: j++;
8463: fscanf(ficpar,"%1d%1d",&i1,&j1);
8464: if ((i1 != i) || (j1 != jj)){
8465: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
8466: It might be a problem of design; if ncovcol and the model are correct\n \
8467: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
8468: exit(1);
8469: }
8470: fprintf(ficparo,"%1d%1d",i1,j1);
8471: if(mle==1)
8472: printf("%1d%1d",i,jj);
8473: fprintf(ficlog,"%1d%1d",i,jj);
8474: for(k=1; k<=ncovmodel;k++){
8475: fscanf(ficpar," %lf",¶m[i][j][k]);
8476: if(mle==1){
8477: printf(" %lf",param[i][j][k]);
8478: fprintf(ficlog," %lf",param[i][j][k]);
8479: }
8480: else
8481: fprintf(ficlog," %lf",param[i][j][k]);
8482: fprintf(ficparo," %lf",param[i][j][k]);
8483: }
8484: fscanf(ficpar,"\n");
8485: numlinepar++;
8486: if(mle==1)
8487: printf("\n");
8488: fprintf(ficlog,"\n");
8489: fprintf(ficparo,"\n");
8490: }
8491: }
8492: fflush(ficlog);
8493:
8494: /* Reads scales values */
8495: p=param[1][1];
8496:
8497: /* Reads comments: lines beginning with '#' */
8498: while((c=getc(ficpar))=='#' && c!= EOF){
8499: ungetc(c,ficpar);
8500: fgets(line, MAXLINE, ficpar);
8501: numlinepar++;
8502: fputs(line,stdout);
8503: fputs(line,ficparo);
8504: fputs(line,ficlog);
8505: }
8506: ungetc(c,ficpar);
8507:
8508: for(i=1; i <=nlstate; i++){
8509: for(j=1; j <=nlstate+ndeath-1; j++){
8510: fscanf(ficpar,"%1d%1d",&i1,&j1);
8511: if ( (i1-i) * (j1-j) != 0){
8512: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
8513: exit(1);
8514: }
8515: printf("%1d%1d",i,j);
8516: fprintf(ficparo,"%1d%1d",i1,j1);
8517: fprintf(ficlog,"%1d%1d",i1,j1);
8518: for(k=1; k<=ncovmodel;k++){
8519: fscanf(ficpar,"%le",&delti3[i][j][k]);
8520: printf(" %le",delti3[i][j][k]);
8521: fprintf(ficparo," %le",delti3[i][j][k]);
8522: fprintf(ficlog," %le",delti3[i][j][k]);
8523: }
8524: fscanf(ficpar,"\n");
8525: numlinepar++;
8526: printf("\n");
8527: fprintf(ficparo,"\n");
8528: fprintf(ficlog,"\n");
8529: }
8530: }
8531: fflush(ficlog);
8532:
8533: /* Reads covariance matrix */
8534: delti=delti3[1][1];
8535:
8536:
8537: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
8538:
8539: /* Reads comments: lines beginning with '#' */
8540: while((c=getc(ficpar))=='#' && c!= EOF){
8541: ungetc(c,ficpar);
8542: fgets(line, MAXLINE, ficpar);
8543: numlinepar++;
8544: fputs(line,stdout);
8545: fputs(line,ficparo);
8546: fputs(line,ficlog);
8547: }
8548: ungetc(c,ficpar);
8549:
8550: matcov=matrix(1,npar,1,npar);
8551: hess=matrix(1,npar,1,npar);
8552: for(i=1; i <=npar; i++)
8553: for(j=1; j <=npar; j++) matcov[i][j]=0.;
8554:
8555: /* Scans npar lines */
8556: for(i=1; i <=npar; i++){
8557: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
8558: if(count != 3){
8559: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
8560: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
8561: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
8562: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
8563: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
8564: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
8565: exit(1);
8566: }else
8567: if(mle==1)
8568: printf("%1d%1d%1d",i1,j1,jk);
8569: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
8570: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
8571: for(j=1; j <=i; j++){
8572: fscanf(ficpar," %le",&matcov[i][j]);
8573: if(mle==1){
8574: printf(" %.5le",matcov[i][j]);
8575: }
8576: fprintf(ficlog," %.5le",matcov[i][j]);
8577: fprintf(ficparo," %.5le",matcov[i][j]);
8578: }
8579: fscanf(ficpar,"\n");
8580: numlinepar++;
8581: if(mle==1)
8582: printf("\n");
8583: fprintf(ficlog,"\n");
8584: fprintf(ficparo,"\n");
8585: }
8586: /* End of read covariance matrix npar lines */
8587: for(i=1; i <=npar; i++)
8588: for(j=i+1;j<=npar;j++)
8589: matcov[i][j]=matcov[j][i];
8590:
8591: if(mle==1)
8592: printf("\n");
8593: fprintf(ficlog,"\n");
8594:
8595: fflush(ficlog);
8596:
8597: /*-------- Rewriting parameter file ----------*/
8598: strcpy(rfileres,"r"); /* "Rparameterfile */
8599: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
8600: strcat(rfileres,"."); /* */
8601: strcat(rfileres,optionfilext); /* Other files have txt extension */
8602: if((ficres =fopen(rfileres,"w"))==NULL) {
8603: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
8604: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
8605: }
8606: fprintf(ficres,"#%s\n",version);
8607: } /* End of mle != -3 */
8608:
8609: /* Main data
8610: */
8611: n= lastobs;
8612: num=lvector(1,n);
8613: moisnais=vector(1,n);
8614: annais=vector(1,n);
8615: moisdc=vector(1,n);
8616: andc=vector(1,n);
8617: agedc=vector(1,n);
8618: cod=ivector(1,n);
8619: weight=vector(1,n);
8620: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
8621: mint=matrix(1,maxwav,1,n);
8622: anint=matrix(1,maxwav,1,n);
8623: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
8624: tab=ivector(1,NCOVMAX);
8625: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
8626: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
8627:
8628: /* Reads data from file datafile */
8629: if (readdata(datafile, firstobs, lastobs, &imx)==1)
8630: goto end;
8631:
8632: /* Calculation of the number of parameters from char model */
8633: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
8634: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
8635: k=3 V4 Tvar[k=3]= 4 (from V4)
8636: k=2 V1 Tvar[k=2]= 1 (from V1)
8637: k=1 Tvar[1]=2 (from V2)
8638: */
8639: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
8640: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
8641: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
8642: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
8643: */
8644: /* For model-covariate k tells which data-covariate to use but
8645: because this model-covariate is a construction we invent a new column
8646: ncovcol + k1
8647: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
8648: Tvar[3=V1*V4]=4+1 etc */
8649: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
8650: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
8651: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
8652: */
8653: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
8654: 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
8655: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
8656: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
8657: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
8658: 4 covariates (3 plus signs)
8659: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
8660: */
8661:
8662: /* Main decodemodel */
8663:
8664:
8665: if(decodemodel(model, lastobs) == 1)
8666: goto end;
8667:
8668: if((double)(lastobs-imx)/(double)imx > 1.10){
8669: nbwarn++;
8670: 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);
8671: 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);
8672: }
8673: /* if(mle==1){*/
8674: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
8675: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
8676: }
8677:
8678: /*-calculation of age at interview from date of interview and age at death -*/
8679: agev=matrix(1,maxwav,1,imx);
8680:
8681: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
8682: goto end;
8683:
8684:
8685: agegomp=(int)agemin;
8686: free_vector(moisnais,1,n);
8687: free_vector(annais,1,n);
8688: /* free_matrix(mint,1,maxwav,1,n);
8689: free_matrix(anint,1,maxwav,1,n);*/
8690: /* free_vector(moisdc,1,n); */
8691: /* free_vector(andc,1,n); */
8692: /* */
8693:
8694: wav=ivector(1,imx);
8695: /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
8696: /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
8697: /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
8698: 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.*/
8699: bh=imatrix(1,lastpass-firstpass+2,1,imx);
8700: mw=imatrix(1,lastpass-firstpass+2,1,imx);
8701:
8702: /* Concatenates waves */
8703: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
8704: Death is a valid wave (if date is known).
8705: mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
8706: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
8707: and mw[mi+1][i]. dh depends on stepm.
8708: */
8709:
8710: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
8711: /* */
8712:
8713: free_vector(moisdc,1,n);
8714: free_vector(andc,1,n);
8715:
8716: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
8717:
8718: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
8719: ncodemax[1]=1;
8720: Ndum =ivector(-1,NCOVMAX);
8721: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
8722: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
8723: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
8724: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
8725: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
8726:
8727: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
8728: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
8729: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
8730: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
8731: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
8732: * (currently 0 or 1) in the data.
8733: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
8734: * corresponding modality (h,j).
8735: */
8736:
8737: h=0;
8738:
8739:
8740: /*if (cptcovn > 0) */
8741:
8742:
8743: m=pow(2,cptcoveff);
8744:
8745: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
8746: * For k=4 covariates, h goes from 1 to m=2**k
8747: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
8748: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
8749: * h\k 1 2 3 4
8750: *______________________________
8751: * 1 i=1 1 i=1 1 i=1 1 i=1 1
8752: * 2 2 1 1 1
8753: * 3 i=2 1 2 1 1
8754: * 4 2 2 1 1
8755: * 5 i=3 1 i=2 1 2 1
8756: * 6 2 1 2 1
8757: * 7 i=4 1 2 2 1
8758: * 8 2 2 2 1
8759: * 9 i=5 1 i=3 1 i=2 1 2
8760: * 10 2 1 1 2
8761: * 11 i=6 1 2 1 2
8762: * 12 2 2 1 2
8763: * 13 i=7 1 i=4 1 2 2
8764: * 14 2 1 2 2
8765: * 15 i=8 1 2 2 2
8766: * 16 2 2 2 2
8767: */
8768: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
8769: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
8770: * and the value of each covariate?
8771: * V1=1, V2=1, V3=2, V4=1 ?
8772: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
8773: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
8774: * In order to get the real value in the data, we use nbcode
8775: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
8776: * We are keeping this crazy system in order to be able (in the future?)
8777: * to have more than 2 values (0 or 1) for a covariate.
8778: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
8779: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
8780: * bbbbbbbb
8781: * 76543210
8782: * h-1 00000101 (6-1=5)
8783: *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
8784: * &
8785: * 1 00000001 (1)
8786: * 00000000 = 1 & ((h-1) >> (k-1))
8787: * +1= 00000001 =1
8788: *
8789: * h=14, k=3 => h'=h-1=13, k'=k-1=2
8790: * h' 1101 =2^3+2^2+0x2^1+2^0
8791: * >>k' 11
8792: * & 00000001
8793: * = 00000001
8794: * +1 = 00000010=2 = codtabm(14,3)
8795: * Reverse h=6 and m=16?
8796: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
8797: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
8798: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
8799: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
8800: * V3=decodtabm(14,3,2**4)=2
8801: * h'=13 1101 =2^3+2^2+0x2^1+2^0
8802: *(h-1) >> (j-1) 0011 =13 >> 2
8803: * &1 000000001
8804: * = 000000001
8805: * +1= 000000010 =2
8806: * 2211
8807: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
8808: * V3=2
8809: */
8810:
8811: /* /\* for(h=1; h <=100 ;h++){ *\/ */
8812: /* /\* printf("h=%2d ", h); *\/ */
8813: /* /\* for(k=1; k <=10; k++){ *\/ */
8814: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
8815: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
8816: /* /\* } *\/ */
8817: /* /\* printf("\n"); *\/ */
8818: /* } */
8819: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
8820: /* for(i=1; i <=pow(2,cptcoveff-k);i++){ /\* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 *\/ */
8821: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
8822: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
8823: /* h++; */
8824: /* if (h>m) */
8825: /* h=1; */
8826: /* codtab[h][k]=j; */
8827: /* /\* codtab[12][3]=1; *\/ */
8828: /* /\*codtab[h][Tvar[k]]=j;*\/ */
8829: /* /\* printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]); *\/ */
8830: /* } */
8831: /* } */
8832: /* } */
8833: /* } */
8834: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
8835: codtab[1][2]=1;codtab[2][2]=2; */
8836: /* for(i=1; i <=m ;i++){ */
8837: /* for(k=1; k <=cptcovn; k++){ */
8838: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
8839: /* } */
8840: /* printf("\n"); */
8841: /* } */
8842: /* scanf("%d",i);*/
8843:
8844: free_ivector(Ndum,-1,NCOVMAX);
8845:
8846:
8847:
8848: /* Initialisation of ----------- gnuplot -------------*/
8849: strcpy(optionfilegnuplot,optionfilefiname);
8850: if(mle==-3)
8851: strcat(optionfilegnuplot,"-MORT_");
8852: strcat(optionfilegnuplot,".gp");
8853:
8854: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
8855: printf("Problem with file %s",optionfilegnuplot);
8856: }
8857: else{
8858: fprintf(ficgp,"\n# IMaCh-%s\n", version);
8859: fprintf(ficgp,"# %s\n", optionfilegnuplot);
8860: //fprintf(ficgp,"set missing 'NaNq'\n");
8861: fprintf(ficgp,"set datafile missing 'NaNq'\n");
8862: }
8863: /* fclose(ficgp);*/
8864:
8865:
8866: /* Initialisation of --------- index.htm --------*/
8867:
8868: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
8869: if(mle==-3)
8870: strcat(optionfilehtm,"-MORT_");
8871: strcat(optionfilehtm,".htm");
8872: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
8873: printf("Problem with %s \n",optionfilehtm);
8874: exit(0);
8875: }
8876:
8877: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
8878: strcat(optionfilehtmcov,"-cov.htm");
8879: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
8880: printf("Problem with %s \n",optionfilehtmcov), exit(0);
8881: }
8882: else{
8883: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
8884: <hr size=\"2\" color=\"#EC5E5E\"> \n\
8885: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
8886: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
8887: }
8888:
8889: 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> \
8890: <hr size=\"2\" color=\"#EC5E5E\"> \n\
8891: <font size=\"2\">IMaCh-%s <br> %s</font> \
8892: <hr size=\"2\" color=\"#EC5E5E\"> \n\
8893: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
8894: \n\
8895: <hr size=\"2\" color=\"#EC5E5E\">\
8896: <ul><li><h4>Parameter files</h4>\n\
8897: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
8898: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
8899: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
8900: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
8901: - Date and time at start: %s</ul>\n",\
8902: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
8903: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
8904: fileres,fileres,\
8905: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
8906: fflush(fichtm);
8907:
8908: strcpy(pathr,path);
8909: strcat(pathr,optionfilefiname);
8910: #ifdef WIN32
8911: _chdir(optionfilefiname); /* Move to directory named optionfile */
8912: #else
8913: chdir(optionfilefiname); /* Move to directory named optionfile */
8914: #endif
8915:
8916:
8917: /* Calculates basic frequencies. Computes observed prevalence at single age
8918: and prints on file fileres'p'. */
8919: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
8920: firstpass, lastpass, stepm, weightopt, model);
8921:
8922: fprintf(fichtm,"\n");
8923: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
8924: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
8925: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
8926: imx,agemin,agemax,jmin,jmax,jmean);
8927: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
8928: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
8929: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
8930: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
8931: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
8932:
8933: /* For Powell, parameters are in a vector p[] starting at p[1]
8934: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
8935: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
8936:
8937: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
8938: /* For mortality only */
8939: if (mle==-3){
8940: ximort=matrix(1,NDIM,1,NDIM);
8941: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
8942: cens=ivector(1,n);
8943: ageexmed=vector(1,n);
8944: agecens=vector(1,n);
8945: dcwave=ivector(1,n);
8946:
8947: for (i=1; i<=imx; i++){
8948: dcwave[i]=-1;
8949: for (m=firstpass; m<=lastpass; m++)
8950: if (s[m][i]>nlstate) {
8951: dcwave[i]=m;
8952: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
8953: break;
8954: }
8955: }
8956:
8957: for (i=1; i<=imx; i++) {
8958: if (wav[i]>0){
8959: ageexmed[i]=agev[mw[1][i]][i];
8960: j=wav[i];
8961: agecens[i]=1.;
8962:
8963: if (ageexmed[i]> 1 && wav[i] > 0){
8964: agecens[i]=agev[mw[j][i]][i];
8965: cens[i]= 1;
8966: }else if (ageexmed[i]< 1)
8967: cens[i]= -1;
8968: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
8969: cens[i]=0 ;
8970: }
8971: else cens[i]=-1;
8972: }
8973:
8974: for (i=1;i<=NDIM;i++) {
8975: for (j=1;j<=NDIM;j++)
8976: ximort[i][j]=(i == j ? 1.0 : 0.0);
8977: }
8978:
8979: /*p[1]=0.0268; p[NDIM]=0.083;*/
8980: /*printf("%lf %lf", p[1], p[2]);*/
8981:
8982:
8983: #ifdef GSL
8984: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
8985: #else
8986: printf("Powell\n"); fprintf(ficlog,"Powell\n");
8987: #endif
8988: strcpy(filerespow,"POW-MORT_");
8989: strcat(filerespow,fileresu);
8990: if((ficrespow=fopen(filerespow,"w"))==NULL) {
8991: printf("Problem with resultfile: %s\n", filerespow);
8992: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
8993: }
8994: #ifdef GSL
8995: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
8996: #else
8997: fprintf(ficrespow,"# Powell\n# iter -2*LL");
8998: #endif
8999: /* for (i=1;i<=nlstate;i++)
9000: for(j=1;j<=nlstate+ndeath;j++)
9001: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
9002: */
9003: fprintf(ficrespow,"\n");
9004: #ifdef GSL
9005: /* gsl starts here */
9006: T = gsl_multimin_fminimizer_nmsimplex;
9007: gsl_multimin_fminimizer *sfm = NULL;
9008: gsl_vector *ss, *x;
9009: gsl_multimin_function minex_func;
9010:
9011: /* Initial vertex size vector */
9012: ss = gsl_vector_alloc (NDIM);
9013:
9014: if (ss == NULL){
9015: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
9016: }
9017: /* Set all step sizes to 1 */
9018: gsl_vector_set_all (ss, 0.001);
9019:
9020: /* Starting point */
9021:
9022: x = gsl_vector_alloc (NDIM);
9023:
9024: if (x == NULL){
9025: gsl_vector_free(ss);
9026: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
9027: }
9028:
9029: /* Initialize method and iterate */
9030: /* p[1]=0.0268; p[NDIM]=0.083; */
9031: /* gsl_vector_set(x, 0, 0.0268); */
9032: /* gsl_vector_set(x, 1, 0.083); */
9033: gsl_vector_set(x, 0, p[1]);
9034: gsl_vector_set(x, 1, p[2]);
9035:
9036: minex_func.f = &gompertz_f;
9037: minex_func.n = NDIM;
9038: minex_func.params = (void *)&p; /* ??? */
9039:
9040: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
9041: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
9042:
9043: printf("Iterations beginning .....\n\n");
9044: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
9045:
9046: iteri=0;
9047: while (rval == GSL_CONTINUE){
9048: iteri++;
9049: status = gsl_multimin_fminimizer_iterate(sfm);
9050:
9051: if (status) printf("error: %s\n", gsl_strerror (status));
9052: fflush(0);
9053:
9054: if (status)
9055: break;
9056:
9057: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
9058: ssval = gsl_multimin_fminimizer_size (sfm);
9059:
9060: if (rval == GSL_SUCCESS)
9061: printf ("converged to a local maximum at\n");
9062:
9063: printf("%5d ", iteri);
9064: for (it = 0; it < NDIM; it++){
9065: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
9066: }
9067: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
9068: }
9069:
9070: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
9071:
9072: gsl_vector_free(x); /* initial values */
9073: gsl_vector_free(ss); /* inital step size */
9074: for (it=0; it<NDIM; it++){
9075: p[it+1]=gsl_vector_get(sfm->x,it);
9076: fprintf(ficrespow," %.12lf", p[it]);
9077: }
9078: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
9079: #endif
9080: #ifdef POWELL
9081: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
9082: #endif
9083: fclose(ficrespow);
9084:
9085: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
9086:
9087: for(i=1; i <=NDIM; i++)
9088: for(j=i+1;j<=NDIM;j++)
9089: matcov[i][j]=matcov[j][i];
9090:
9091: printf("\nCovariance matrix\n ");
9092: fprintf(ficlog,"\nCovariance matrix\n ");
9093: for(i=1; i <=NDIM; i++) {
9094: for(j=1;j<=NDIM;j++){
9095: printf("%f ",matcov[i][j]);
9096: fprintf(ficlog,"%f ",matcov[i][j]);
9097: }
9098: printf("\n "); fprintf(ficlog,"\n ");
9099: }
9100:
9101: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
9102: for (i=1;i<=NDIM;i++) {
9103: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
9104: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
9105: }
9106: lsurv=vector(1,AGESUP);
9107: lpop=vector(1,AGESUP);
9108: tpop=vector(1,AGESUP);
9109: lsurv[agegomp]=100000;
9110:
9111: for (k=agegomp;k<=AGESUP;k++) {
9112: agemortsup=k;
9113: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
9114: }
9115:
9116: for (k=agegomp;k<agemortsup;k++)
9117: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
9118:
9119: for (k=agegomp;k<agemortsup;k++){
9120: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
9121: sumlpop=sumlpop+lpop[k];
9122: }
9123:
9124: tpop[agegomp]=sumlpop;
9125: for (k=agegomp;k<(agemortsup-3);k++){
9126: /* tpop[k+1]=2;*/
9127: tpop[k+1]=tpop[k]-lpop[k];
9128: }
9129:
9130:
9131: printf("\nAge lx qx dx Lx Tx e(x)\n");
9132: for (k=agegomp;k<(agemortsup-2);k++)
9133: 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]);
9134:
9135:
9136: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
9137: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
9138: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
9139: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
9140: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
9141: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
9142: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
9143: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
9144: }else
9145: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
9146: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
9147: stepm, weightopt,\
9148: model,imx,p,matcov,agemortsup);
9149:
9150: free_vector(lsurv,1,AGESUP);
9151: free_vector(lpop,1,AGESUP);
9152: free_vector(tpop,1,AGESUP);
9153: #ifdef GSL
9154: free_ivector(cens,1,n);
9155: free_vector(agecens,1,n);
9156: free_ivector(dcwave,1,n);
9157: free_matrix(ximort,1,NDIM,1,NDIM);
9158: #endif
9159: } /* Endof if mle==-3 mortality only */
9160: /* Standard */
9161: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
9162: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
9163: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
9164: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
9165: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
9166: for (k=1; k<=npar;k++)
9167: printf(" %d %8.5f",k,p[k]);
9168: printf("\n");
9169: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
9170: /* mlikeli uses func not funcone */
9171: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
9172: }
9173: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
9174: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
9175: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
9176: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
9177: }
9178: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
9179: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
9180: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
9181: for (k=1; k<=npar;k++)
9182: printf(" %d %8.5f",k,p[k]);
9183: printf("\n");
9184:
9185: /*--------- results files --------------*/
9186: fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
9187:
9188:
9189: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
9190: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
9191: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
9192: for(i=1,jk=1; i <=nlstate; i++){
9193: for(k=1; k <=(nlstate+ndeath); k++){
9194: if (k != i) {
9195: printf("%d%d ",i,k);
9196: fprintf(ficlog,"%d%d ",i,k);
9197: fprintf(ficres,"%1d%1d ",i,k);
9198: for(j=1; j <=ncovmodel; j++){
9199: printf("%12.7f ",p[jk]);
9200: fprintf(ficlog,"%12.7f ",p[jk]);
9201: fprintf(ficres,"%12.7f ",p[jk]);
9202: jk++;
9203: }
9204: printf("\n");
9205: fprintf(ficlog,"\n");
9206: fprintf(ficres,"\n");
9207: }
9208: }
9209: }
9210: if(mle != 0){
9211: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
9212: ftolhess=ftol; /* Usually correct */
9213: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
9214: 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");
9215: 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");
9216: for(i=1,jk=1; i <=nlstate; i++){
9217: for(k=1; k <=(nlstate+ndeath); k++){
9218: if (k != i) {
9219: printf("%d%d ",i,k);
9220: fprintf(ficlog,"%d%d ",i,k);
9221: for(j=1; j <=ncovmodel; j++){
9222: 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]));
9223: 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]));
9224: jk++;
9225: }
9226: printf("\n");
9227: fprintf(ficlog,"\n");
9228: }
9229: }
9230: }
9231: } /* end of hesscov and Wald tests */
9232:
9233: /* */
9234: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
9235: printf("# Scales (for hessian or gradient estimation)\n");
9236: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
9237: for(i=1,jk=1; i <=nlstate; i++){
9238: for(j=1; j <=nlstate+ndeath; j++){
9239: if (j!=i) {
9240: fprintf(ficres,"%1d%1d",i,j);
9241: printf("%1d%1d",i,j);
9242: fprintf(ficlog,"%1d%1d",i,j);
9243: for(k=1; k<=ncovmodel;k++){
9244: printf(" %.5e",delti[jk]);
9245: fprintf(ficlog," %.5e",delti[jk]);
9246: fprintf(ficres," %.5e",delti[jk]);
9247: jk++;
9248: }
9249: printf("\n");
9250: fprintf(ficlog,"\n");
9251: fprintf(ficres,"\n");
9252: }
9253: }
9254: }
9255:
9256: 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");
9257: if(mle >= 1) /* To big for the screen */
9258: 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");
9259: 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");
9260: /* # 121 Var(a12)\n\ */
9261: /* # 122 Cov(b12,a12) Var(b12)\n\ */
9262: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
9263: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
9264: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
9265: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
9266: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
9267: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
9268:
9269:
9270: /* Just to have a covariance matrix which will be more understandable
9271: even is we still don't want to manage dictionary of variables
9272: */
9273: for(itimes=1;itimes<=2;itimes++){
9274: jj=0;
9275: for(i=1; i <=nlstate; i++){
9276: for(j=1; j <=nlstate+ndeath; j++){
9277: if(j==i) continue;
9278: for(k=1; k<=ncovmodel;k++){
9279: jj++;
9280: ca[0]= k+'a'-1;ca[1]='\0';
9281: if(itimes==1){
9282: if(mle>=1)
9283: printf("#%1d%1d%d",i,j,k);
9284: fprintf(ficlog,"#%1d%1d%d",i,j,k);
9285: fprintf(ficres,"#%1d%1d%d",i,j,k);
9286: }else{
9287: if(mle>=1)
9288: printf("%1d%1d%d",i,j,k);
9289: fprintf(ficlog,"%1d%1d%d",i,j,k);
9290: fprintf(ficres,"%1d%1d%d",i,j,k);
9291: }
9292: ll=0;
9293: for(li=1;li <=nlstate; li++){
9294: for(lj=1;lj <=nlstate+ndeath; lj++){
9295: if(lj==li) continue;
9296: for(lk=1;lk<=ncovmodel;lk++){
9297: ll++;
9298: if(ll<=jj){
9299: cb[0]= lk +'a'-1;cb[1]='\0';
9300: if(ll<jj){
9301: if(itimes==1){
9302: if(mle>=1)
9303: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
9304: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
9305: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
9306: }else{
9307: if(mle>=1)
9308: printf(" %.5e",matcov[jj][ll]);
9309: fprintf(ficlog," %.5e",matcov[jj][ll]);
9310: fprintf(ficres," %.5e",matcov[jj][ll]);
9311: }
9312: }else{
9313: if(itimes==1){
9314: if(mle>=1)
9315: printf(" Var(%s%1d%1d)",ca,i,j);
9316: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
9317: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
9318: }else{
9319: if(mle>=1)
9320: printf(" %.7e",matcov[jj][ll]);
9321: fprintf(ficlog," %.7e",matcov[jj][ll]);
9322: fprintf(ficres," %.7e",matcov[jj][ll]);
9323: }
9324: }
9325: }
9326: } /* end lk */
9327: } /* end lj */
9328: } /* end li */
9329: if(mle>=1)
9330: printf("\n");
9331: fprintf(ficlog,"\n");
9332: fprintf(ficres,"\n");
9333: numlinepar++;
9334: } /* end k*/
9335: } /*end j */
9336: } /* end i */
9337: } /* end itimes */
9338:
9339: fflush(ficlog);
9340: fflush(ficres);
9341: while(fgets(line, MAXLINE, ficpar)) {
9342: /* If line starts with a # it is a comment */
9343: if (line[0] == '#') {
9344: numlinepar++;
9345: fputs(line,stdout);
9346: fputs(line,ficparo);
9347: fputs(line,ficlog);
9348: continue;
9349: }else
9350: break;
9351: }
9352:
9353: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
9354: /* ungetc(c,ficpar); */
9355: /* fgets(line, MAXLINE, ficpar); */
9356: /* fputs(line,stdout); */
9357: /* fputs(line,ficparo); */
9358: /* } */
9359: /* ungetc(c,ficpar); */
9360:
9361: estepm=0;
9362: 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){
9363:
9364: if (num_filled != 6) {
9365: 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);
9366: 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);
9367: goto end;
9368: }
9369: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
9370: }
9371: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
9372: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
9373:
9374: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
9375: if (estepm==0 || estepm < stepm) estepm=stepm;
9376: if (fage <= 2) {
9377: bage = ageminpar;
9378: fage = agemaxpar;
9379: }
9380:
9381: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
9382: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
9383: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
9384:
9385: /* Other stuffs, more or less useful */
9386: while((c=getc(ficpar))=='#' && c!= EOF){
9387: ungetc(c,ficpar);
9388: fgets(line, MAXLINE, ficpar);
9389: fputs(line,stdout);
9390: fputs(line,ficparo);
9391: }
9392: ungetc(c,ficpar);
9393:
9394: 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);
9395: 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);
9396: 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);
9397: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
9398: 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);
9399:
9400: while((c=getc(ficpar))=='#' && c!= EOF){
9401: ungetc(c,ficpar);
9402: fgets(line, MAXLINE, ficpar);
9403: fputs(line,stdout);
9404: fputs(line,ficparo);
9405: }
9406: ungetc(c,ficpar);
9407:
9408:
9409: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
9410: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
9411:
9412: fscanf(ficpar,"pop_based=%d\n",&popbased);
9413: fprintf(ficlog,"pop_based=%d\n",popbased);
9414: fprintf(ficparo,"pop_based=%d\n",popbased);
9415: fprintf(ficres,"pop_based=%d\n",popbased);
9416:
9417: while((c=getc(ficpar))=='#' && c!= EOF){
9418: ungetc(c,ficpar);
9419: fgets(line, MAXLINE, ficpar);
9420: fputs(line,stdout);
9421: fputs(line,ficparo);
9422: }
9423: ungetc(c,ficpar);
9424:
9425: 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);
9426: 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);
9427: 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);
9428: 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);
9429: 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);
9430: /* day and month of proj2 are not used but only year anproj2.*/
9431:
9432: while((c=getc(ficpar))=='#' && c!= EOF){
9433: ungetc(c,ficpar);
9434: fgets(line, MAXLINE, ficpar);
9435: fputs(line,stdout);
9436: fputs(line,ficparo);
9437: }
9438: ungetc(c,ficpar);
9439:
9440: 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);
9441: 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);
9442: 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);
9443: 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);
9444: /* day and month of proj2 are not used but only year anproj2.*/
9445:
9446:
9447: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
9448: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
9449:
9450: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
9451: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
9452: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
9453: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
9454: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
9455: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
9456: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
9457: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
9458: }else
9459: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
9460:
9461: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
9462: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
9463: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
9464:
9465: /*------------ free_vector -------------*/
9466: /* chdir(path); */
9467:
9468: /* free_ivector(wav,1,imx); */ /* Moved after last prevalence call */
9469: /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
9470: /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
9471: /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx); */
9472: free_lvector(num,1,n);
9473: free_vector(agedc,1,n);
9474: /*free_matrix(covar,0,NCOVMAX,1,n);*/
9475: /*free_matrix(covar,1,NCOVMAX,1,n);*/
9476: fclose(ficparo);
9477: fclose(ficres);
9478:
9479:
9480: /* Other results (useful)*/
9481:
9482:
9483: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
9484: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
9485: prlim=matrix(1,nlstate,1,nlstate);
9486: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
9487: fclose(ficrespl);
9488:
9489: /*------------- h Pij x at various ages ------------*/
9490: /*#include "hpijx.h"*/
9491: hPijx(p, bage, fage);
9492: fclose(ficrespij);
9493:
9494: ncovcombmax= pow(2,cptcoveff);
9495: /*-------------- Variance of one-step probabilities---*/
9496: k=1;
9497: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
9498:
9499: /* Prevalence for each covariates in probs[age][status][cov] */
9500: probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
9501: for(i=1;i<=AGESUP;i++)
9502: for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
9503: for(k=1;k<=ncovcombmax;k++)
9504: probs[i][j][k]=0.;
9505: prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
9506: if (mobilav!=0 ||mobilavproj !=0 ) {
9507: mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
9508: for(i=1;i<=AGESUP;i++)
9509: for(j=1;j<=nlstate;j++)
9510: for(k=1;k<=ncovcombmax;k++)
9511: mobaverages[i][j][k]=0.;
9512: mobaverage=mobaverages;
9513: if (mobilav!=0) {
9514: if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
9515: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
9516: printf(" Error in movingaverage mobilav=%d\n",mobilav);
9517: }
9518: }
9519: /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
9520: /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
9521: else if (mobilavproj !=0) {
9522: if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
9523: fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
9524: printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
9525: }
9526: }
9527: }/* end if moving average */
9528:
9529: /*---------- Forecasting ------------------*/
9530: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
9531: if(prevfcast==1){
9532: /* if(stepm ==1){*/
9533: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
9534: }
9535: if(backcast==1){
9536: ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
9537: ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
9538: ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
9539:
9540: /*--------------- Back Prevalence limit (period or stable prevalence) --------------*/
9541:
9542: bprlim=matrix(1,nlstate,1,nlstate);
9543: back_prevalence_limit(p, bprlim, ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
9544: fclose(ficresplb);
9545:
9546: hBijx(p, bage, fage, mobaverage);
9547: fclose(ficrespijb);
9548: free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
9549:
9550: /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
9551: bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
9552: free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
9553: free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
9554: free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
9555: }
9556:
9557:
9558: /* ------ Other prevalence ratios------------ */
9559:
9560: free_ivector(wav,1,imx);
9561: free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
9562: free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
9563: free_imatrix(mw,1,lastpass-firstpass+2,1,imx);
9564:
9565:
9566: /*---------- Health expectancies, no variances ------------*/
9567:
9568: strcpy(filerese,"E_");
9569: strcat(filerese,fileresu);
9570: if((ficreseij=fopen(filerese,"w"))==NULL) {
9571: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
9572: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
9573: }
9574: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
9575: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
9576:
9577: for (k=1; k <= (int) pow(2,cptcoveff); k++){
9578: fprintf(ficreseij,"\n#****** ");
9579: for(j=1;j<=cptcoveff;j++) {
9580: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9581: }
9582: fprintf(ficreseij,"******\n");
9583:
9584: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
9585: oldm=oldms;savm=savms;
9586: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
9587:
9588: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
9589: }
9590: fclose(ficreseij);
9591: printf("done evsij\n");fflush(stdout);
9592: fprintf(ficlog,"done evsij\n");fflush(ficlog);
9593:
9594: /*---------- Health expectancies and variances ------------*/
9595:
9596:
9597: strcpy(filerest,"T_");
9598: strcat(filerest,fileresu);
9599: if((ficrest=fopen(filerest,"w"))==NULL) {
9600: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
9601: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
9602: }
9603: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
9604: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
9605:
9606:
9607: strcpy(fileresstde,"STDE_");
9608: strcat(fileresstde,fileresu);
9609: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
9610: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
9611: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
9612: }
9613: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
9614: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
9615:
9616: strcpy(filerescve,"CVE_");
9617: strcat(filerescve,fileresu);
9618: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
9619: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
9620: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
9621: }
9622: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
9623: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
9624:
9625: strcpy(fileresv,"V_");
9626: strcat(fileresv,fileresu);
9627: if((ficresvij=fopen(fileresv,"w"))==NULL) {
9628: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
9629: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
9630: }
9631: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
9632: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
9633:
9634: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
9635: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
9636:
9637: for (k=1; k <= (int) pow(2,cptcoveff); k++){
9638: fprintf(ficrest,"\n#****** ");
9639: for(j=1;j<=cptcoveff;j++)
9640: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9641: fprintf(ficrest,"******\n");
9642:
9643: fprintf(ficresstdeij,"\n#****** ");
9644: fprintf(ficrescveij,"\n#****** ");
9645: for(j=1;j<=cptcoveff;j++) {
9646: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9647: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9648: }
9649: fprintf(ficresstdeij,"******\n");
9650: fprintf(ficrescveij,"******\n");
9651:
9652: fprintf(ficresvij,"\n#****** ");
9653: for(j=1;j<=cptcoveff;j++)
9654: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9655: fprintf(ficresvij,"******\n");
9656:
9657: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
9658: oldm=oldms;savm=savms;
9659: printf(" cvevsij %d, ",k);
9660: fprintf(ficlog, " cvevsij %d, ",k);
9661: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
9662: printf(" end cvevsij \n ");
9663: fprintf(ficlog, " end cvevsij \n ");
9664:
9665: /*
9666: */
9667: /* goto endfree; */
9668:
9669: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
9670: pstamp(ficrest);
9671:
9672:
9673: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
9674: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
9675: cptcod= 0; /* To be deleted */
9676: printf("varevsij %d \n",vpopbased);
9677: fprintf(ficlog, "varevsij %d \n",vpopbased);
9678: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
9679: 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 ");
9680: if(vpopbased==1)
9681: 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);
9682: else
9683: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
9684: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
9685: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
9686: fprintf(ficrest,"\n");
9687: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
9688: epj=vector(1,nlstate+1);
9689: printf("Computing age specific period (stable) prevalences in each health state \n");
9690: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
9691: for(age=bage; age <=fage ;age++){
9692: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
9693: if (vpopbased==1) {
9694: if(mobilav ==0){
9695: for(i=1; i<=nlstate;i++)
9696: prlim[i][i]=probs[(int)age][i][k];
9697: }else{ /* mobilav */
9698: for(i=1; i<=nlstate;i++)
9699: prlim[i][i]=mobaverage[(int)age][i][k];
9700: }
9701: }
9702:
9703: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
9704: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
9705: /* printf(" age %4.0f ",age); */
9706: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
9707: for(i=1, epj[j]=0.;i <=nlstate;i++) {
9708: epj[j] += prlim[i][i]*eij[i][j][(int)age];
9709: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
9710: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
9711: }
9712: epj[nlstate+1] +=epj[j];
9713: }
9714: /* printf(" age %4.0f \n",age); */
9715:
9716: for(i=1, vepp=0.;i <=nlstate;i++)
9717: for(j=1;j <=nlstate;j++)
9718: vepp += vareij[i][j][(int)age];
9719: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
9720: for(j=1;j <=nlstate;j++){
9721: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
9722: }
9723: fprintf(ficrest,"\n");
9724: }
9725: } /* End vpopbased */
9726: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
9727: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
9728: free_vector(epj,1,nlstate+1);
9729: printf("done \n");fflush(stdout);
9730: fprintf(ficlog,"done\n");fflush(ficlog);
9731:
9732: /*}*/
9733: } /* End k */
9734: free_vector(weight,1,n);
9735: free_imatrix(Tvard,1,NCOVMAX,1,2);
9736: free_imatrix(s,1,maxwav+1,1,n);
9737: free_matrix(anint,1,maxwav,1,n);
9738: free_matrix(mint,1,maxwav,1,n);
9739: free_ivector(cod,1,n);
9740: free_ivector(tab,1,NCOVMAX);
9741: fclose(ficresstdeij);
9742: fclose(ficrescveij);
9743: fclose(ficresvij);
9744: fclose(ficrest);
9745: printf("done Health expectancies\n");fflush(stdout);
9746: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
9747: fclose(ficpar);
9748:
9749: /*------- Variance of period (stable) prevalence------*/
9750:
9751: strcpy(fileresvpl,"VPL_");
9752: strcat(fileresvpl,fileresu);
9753: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
9754: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
9755: exit(0);
9756: }
9757: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
9758: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
9759:
9760: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
9761: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
9762:
9763: for (k=1; k <= (int) pow(2,cptcoveff); k++){
9764: fprintf(ficresvpl,"\n#****** ");
9765: for(j=1;j<=cptcoveff;j++)
9766: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
9767: fprintf(ficresvpl,"******\n");
9768:
9769: varpl=matrix(1,nlstate,(int) bage, (int) fage);
9770: oldm=oldms;savm=savms;
9771: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
9772: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
9773: /*}*/
9774: }
9775:
9776: fclose(ficresvpl);
9777: printf("done variance-covariance of period prevalence\n");fflush(stdout);
9778: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
9779:
9780: /*---------- End : free ----------------*/
9781: if (mobilav!=0 ||mobilavproj !=0)
9782: free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
9783: free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
9784: } /* mle==-3 arrives here for freeing */
9785: /* endfree:*/
9786: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
9787: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
9788: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
9789: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
9790: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
9791: free_matrix(covar,0,NCOVMAX,1,n);
9792: free_matrix(matcov,1,npar,1,npar);
9793: free_matrix(hess,1,npar,1,npar);
9794: /*free_vector(delti,1,npar);*/
9795: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
9796: free_matrix(agev,1,maxwav,1,imx);
9797: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
9798:
9799: free_ivector(ncodemax,1,NCOVMAX);
9800: free_ivector(ncodemaxwundef,1,NCOVMAX);
9801: free_ivector(Tvar,1,NCOVMAX);
9802: free_ivector(Tprod,1,NCOVMAX);
9803: free_ivector(Tvaraff,1,NCOVMAX);
9804: free_ivector(Tage,1,NCOVMAX);
9805:
9806: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
9807: /* free_imatrix(codtab,1,100,1,10); */
9808: fflush(fichtm);
9809: fflush(ficgp);
9810:
9811:
9812: if((nberr >0) || (nbwarn>0)){
9813: printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
9814: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
9815: }else{
9816: printf("End of Imach\n");
9817: fprintf(ficlog,"End of Imach\n");
9818: }
9819: printf("See log file on %s\n",filelog);
9820: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
9821: /*(void) gettimeofday(&end_time,&tzp);*/
9822: rend_time = time(NULL);
9823: end_time = *localtime(&rend_time);
9824: /* tml = *localtime(&end_time.tm_sec); */
9825: strcpy(strtend,asctime(&end_time));
9826: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
9827: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
9828: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
9829:
9830: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
9831: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
9832: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
9833: /* printf("Total time was %d uSec.\n", total_usecs);*/
9834: /* if(fileappend(fichtm,optionfilehtm)){ */
9835: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
9836: fclose(fichtm);
9837: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
9838: fclose(fichtmcov);
9839: fclose(ficgp);
9840: fclose(ficlog);
9841: /*------ End -----------*/
9842:
9843:
9844: printf("Before Current directory %s!\n",pathcd);
9845: #ifdef WIN32
9846: if (_chdir(pathcd) != 0)
9847: printf("Can't move to directory %s!\n",path);
9848: if(_getcwd(pathcd,MAXLINE) > 0)
9849: #else
9850: if(chdir(pathcd) != 0)
9851: printf("Can't move to directory %s!\n", path);
9852: if (getcwd(pathcd, MAXLINE) > 0)
9853: #endif
9854: printf("Current directory %s!\n",pathcd);
9855: /*strcat(plotcmd,CHARSEPARATOR);*/
9856: sprintf(plotcmd,"gnuplot");
9857: #ifdef _WIN32
9858: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
9859: #endif
9860: if(!stat(plotcmd,&info)){
9861: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
9862: if(!stat(getenv("GNUPLOTBIN"),&info)){
9863: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
9864: }else
9865: strcpy(pplotcmd,plotcmd);
9866: #ifdef __unix
9867: strcpy(plotcmd,GNUPLOTPROGRAM);
9868: if(!stat(plotcmd,&info)){
9869: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
9870: }else
9871: strcpy(pplotcmd,plotcmd);
9872: #endif
9873: }else
9874: strcpy(pplotcmd,plotcmd);
9875:
9876: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
9877: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
9878:
9879: if((outcmd=system(plotcmd)) != 0){
9880: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
9881: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
9882: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
9883: if((outcmd=system(plotcmd)) != 0)
9884: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
9885: }
9886: printf(" Successful, please wait...");
9887: while (z[0] != 'q') {
9888: /* chdir(path); */
9889: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
9890: scanf("%s",z);
9891: /* if (z[0] == 'c') system("./imach"); */
9892: if (z[0] == 'e') {
9893: #ifdef __APPLE__
9894: sprintf(pplotcmd, "open %s", optionfilehtm);
9895: #elif __linux
9896: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
9897: #else
9898: sprintf(pplotcmd, "%s", optionfilehtm);
9899: #endif
9900: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
9901: system(pplotcmd);
9902: }
9903: else if (z[0] == 'g') system(plotcmd);
9904: else if (z[0] == 'q') exit(0);
9905: }
9906: end:
9907: while (z[0] != 'q') {
9908: printf("\nType q for exiting: "); fflush(stdout);
9909: scanf("%s",z);
9910: }
9911: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>