Annotation of imach/src/imach.c, revision 1.205
1.205 ! brouard 1: /* $Id: imach.c,v 1.204 2015/10/01 16:20:26 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.205 ! brouard 4: Revision 1.204 2015/10/01 16:20:26 brouard
! 5: Summary: Some new graphs of contribution to likelihood
! 6:
1.204 brouard 7: Revision 1.203 2015/09/30 17:45:14 brouard
8: Summary: looking at better estimation of the hessian
9:
10: Also a better criteria for convergence to the period prevalence And
11: therefore adding the number of years needed to converge. (The
12: prevalence in any alive state shold sum to one
13:
1.203 brouard 14: Revision 1.202 2015/09/22 19:45:16 brouard
15: Summary: Adding some overall graph on contribution to likelihood. Might change
16:
1.202 brouard 17: Revision 1.201 2015/09/15 17:34:58 brouard
18: Summary: 0.98r0
19:
20: - Some new graphs like suvival functions
21: - Some bugs fixed like model=1+age+V2.
22:
1.201 brouard 23: Revision 1.200 2015/09/09 16:53:55 brouard
24: Summary: Big bug thanks to Flavia
25:
26: Even model=1+age+V2. did not work anymore
27:
1.200 brouard 28: Revision 1.199 2015/09/07 14:09:23 brouard
29: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
30:
1.199 brouard 31: Revision 1.198 2015/09/03 07:14:39 brouard
32: Summary: 0.98q5 Flavia
33:
1.198 brouard 34: Revision 1.197 2015/09/01 18:24:39 brouard
35: *** empty log message ***
36:
1.197 brouard 37: Revision 1.196 2015/08/18 23:17:52 brouard
38: Summary: 0.98q5
39:
1.196 brouard 40: Revision 1.195 2015/08/18 16:28:39 brouard
41: Summary: Adding a hack for testing purpose
42:
43: After reading the title, ftol and model lines, if the comment line has
44: a q, starting with #q, the answer at the end of the run is quit. It
45: permits to run test files in batch with ctest. The former workaround was
46: $ echo q | imach foo.imach
47:
1.195 brouard 48: Revision 1.194 2015/08/18 13:32:00 brouard
49: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
50:
1.194 brouard 51: Revision 1.193 2015/08/04 07:17:42 brouard
52: Summary: 0.98q4
53:
1.193 brouard 54: Revision 1.192 2015/07/16 16:49:02 brouard
55: Summary: Fixing some outputs
56:
1.192 brouard 57: Revision 1.191 2015/07/14 10:00:33 brouard
58: Summary: Some fixes
59:
1.191 brouard 60: Revision 1.190 2015/05/05 08:51:13 brouard
61: Summary: Adding digits in output parameters (7 digits instead of 6)
62:
63: Fix 1+age+.
64:
1.190 brouard 65: Revision 1.189 2015/04/30 14:45:16 brouard
66: Summary: 0.98q2
67:
1.189 brouard 68: Revision 1.188 2015/04/30 08:27:53 brouard
69: *** empty log message ***
70:
1.188 brouard 71: Revision 1.187 2015/04/29 09:11:15 brouard
72: *** empty log message ***
73:
1.187 brouard 74: Revision 1.186 2015/04/23 12:01:52 brouard
75: Summary: V1*age is working now, version 0.98q1
76:
77: Some codes had been disabled in order to simplify and Vn*age was
78: working in the optimization phase, ie, giving correct MLE parameters,
79: but, as usual, outputs were not correct and program core dumped.
80:
1.186 brouard 81: Revision 1.185 2015/03/11 13:26:42 brouard
82: Summary: Inclusion of compile and links command line for Intel Compiler
83:
1.185 brouard 84: Revision 1.184 2015/03/11 11:52:39 brouard
85: Summary: Back from Windows 8. Intel Compiler
86:
1.184 brouard 87: Revision 1.183 2015/03/10 20:34:32 brouard
88: Summary: 0.98q0, trying with directest, mnbrak fixed
89:
90: We use directest instead of original Powell test; probably no
91: incidence on the results, but better justifications;
92: We fixed Numerical Recipes mnbrak routine which was wrong and gave
93: wrong results.
94:
1.183 brouard 95: Revision 1.182 2015/02/12 08:19:57 brouard
96: Summary: Trying to keep directest which seems simpler and more general
97: Author: Nicolas Brouard
98:
1.182 brouard 99: Revision 1.181 2015/02/11 23:22:24 brouard
100: Summary: Comments on Powell added
101:
102: Author:
103:
1.181 brouard 104: Revision 1.180 2015/02/11 17:33:45 brouard
105: Summary: Finishing move from main to function (hpijx and prevalence_limit)
106:
1.180 brouard 107: Revision 1.179 2015/01/04 09:57:06 brouard
108: Summary: back to OS/X
109:
1.179 brouard 110: Revision 1.178 2015/01/04 09:35:48 brouard
111: *** empty log message ***
112:
1.178 brouard 113: Revision 1.177 2015/01/03 18:40:56 brouard
114: Summary: Still testing ilc32 on OSX
115:
1.177 brouard 116: Revision 1.176 2015/01/03 16:45:04 brouard
117: *** empty log message ***
118:
1.176 brouard 119: Revision 1.175 2015/01/03 16:33:42 brouard
120: *** empty log message ***
121:
1.175 brouard 122: Revision 1.174 2015/01/03 16:15:49 brouard
123: Summary: Still in cross-compilation
124:
1.174 brouard 125: Revision 1.173 2015/01/03 12:06:26 brouard
126: Summary: trying to detect cross-compilation
127:
1.173 brouard 128: Revision 1.172 2014/12/27 12:07:47 brouard
129: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
130:
1.172 brouard 131: Revision 1.171 2014/12/23 13:26:59 brouard
132: Summary: Back from Visual C
133:
134: Still problem with utsname.h on Windows
135:
1.171 brouard 136: Revision 1.170 2014/12/23 11:17:12 brouard
137: Summary: Cleaning some \%% back to %%
138:
139: The escape was mandatory for a specific compiler (which one?), but too many warnings.
140:
1.170 brouard 141: Revision 1.169 2014/12/22 23:08:31 brouard
142: Summary: 0.98p
143:
144: Outputs some informations on compiler used, OS etc. Testing on different platforms.
145:
1.169 brouard 146: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 147: Summary: update
1.169 brouard 148:
1.168 brouard 149: Revision 1.167 2014/12/22 13:50:56 brouard
150: Summary: Testing uname and compiler version and if compiled 32 or 64
151:
152: Testing on Linux 64
153:
1.167 brouard 154: Revision 1.166 2014/12/22 11:40:47 brouard
155: *** empty log message ***
156:
1.166 brouard 157: Revision 1.165 2014/12/16 11:20:36 brouard
158: Summary: After compiling on Visual C
159:
160: * imach.c (Module): Merging 1.61 to 1.162
161:
1.165 brouard 162: Revision 1.164 2014/12/16 10:52:11 brouard
163: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
164:
165: * imach.c (Module): Merging 1.61 to 1.162
166:
1.164 brouard 167: Revision 1.163 2014/12/16 10:30:11 brouard
168: * imach.c (Module): Merging 1.61 to 1.162
169:
1.163 brouard 170: Revision 1.162 2014/09/25 11:43:39 brouard
171: Summary: temporary backup 0.99!
172:
1.162 brouard 173: Revision 1.1 2014/09/16 11:06:58 brouard
174: Summary: With some code (wrong) for nlopt
175:
176: Author:
177:
178: Revision 1.161 2014/09/15 20:41:41 brouard
179: Summary: Problem with macro SQR on Intel compiler
180:
1.161 brouard 181: Revision 1.160 2014/09/02 09:24:05 brouard
182: *** empty log message ***
183:
1.160 brouard 184: Revision 1.159 2014/09/01 10:34:10 brouard
185: Summary: WIN32
186: Author: Brouard
187:
1.159 brouard 188: Revision 1.158 2014/08/27 17:11:51 brouard
189: *** empty log message ***
190:
1.158 brouard 191: Revision 1.157 2014/08/27 16:26:55 brouard
192: Summary: Preparing windows Visual studio version
193: Author: Brouard
194:
195: In order to compile on Visual studio, time.h is now correct and time_t
196: and tm struct should be used. difftime should be used but sometimes I
197: just make the differences in raw time format (time(&now).
198: Trying to suppress #ifdef LINUX
199: Add xdg-open for __linux in order to open default browser.
200:
1.157 brouard 201: Revision 1.156 2014/08/25 20:10:10 brouard
202: *** empty log message ***
203:
1.156 brouard 204: Revision 1.155 2014/08/25 18:32:34 brouard
205: Summary: New compile, minor changes
206: Author: Brouard
207:
1.155 brouard 208: Revision 1.154 2014/06/20 17:32:08 brouard
209: Summary: Outputs now all graphs of convergence to period prevalence
210:
1.154 brouard 211: Revision 1.153 2014/06/20 16:45:46 brouard
212: Summary: If 3 live state, convergence to period prevalence on same graph
213: Author: Brouard
214:
1.153 brouard 215: Revision 1.152 2014/06/18 17:54:09 brouard
216: Summary: open browser, use gnuplot on same dir than imach if not found in the path
217:
1.152 brouard 218: Revision 1.151 2014/06/18 16:43:30 brouard
219: *** empty log message ***
220:
1.151 brouard 221: Revision 1.150 2014/06/18 16:42:35 brouard
222: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
223: Author: brouard
224:
1.150 brouard 225: Revision 1.149 2014/06/18 15:51:14 brouard
226: Summary: Some fixes in parameter files errors
227: Author: Nicolas Brouard
228:
1.149 brouard 229: Revision 1.148 2014/06/17 17:38:48 brouard
230: Summary: Nothing new
231: Author: Brouard
232:
233: Just a new packaging for OS/X version 0.98nS
234:
1.148 brouard 235: Revision 1.147 2014/06/16 10:33:11 brouard
236: *** empty log message ***
237:
1.147 brouard 238: Revision 1.146 2014/06/16 10:20:28 brouard
239: Summary: Merge
240: Author: Brouard
241:
242: Merge, before building revised version.
243:
1.146 brouard 244: Revision 1.145 2014/06/10 21:23:15 brouard
245: Summary: Debugging with valgrind
246: Author: Nicolas Brouard
247:
248: Lot of changes in order to output the results with some covariates
249: After the Edimburgh REVES conference 2014, it seems mandatory to
250: improve the code.
251: No more memory valgrind error but a lot has to be done in order to
252: continue the work of splitting the code into subroutines.
253: Also, decodemodel has been improved. Tricode is still not
254: optimal. nbcode should be improved. Documentation has been added in
255: the source code.
256:
1.144 brouard 257: Revision 1.143 2014/01/26 09:45:38 brouard
258: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
259:
260: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
261: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
262:
1.143 brouard 263: Revision 1.142 2014/01/26 03:57:36 brouard
264: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
265:
266: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
267:
1.142 brouard 268: Revision 1.141 2014/01/26 02:42:01 brouard
269: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
270:
1.141 brouard 271: Revision 1.140 2011/09/02 10:37:54 brouard
272: Summary: times.h is ok with mingw32 now.
273:
1.140 brouard 274: Revision 1.139 2010/06/14 07:50:17 brouard
275: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
276: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
277:
1.139 brouard 278: Revision 1.138 2010/04/30 18:19:40 brouard
279: *** empty log message ***
280:
1.138 brouard 281: Revision 1.137 2010/04/29 18:11:38 brouard
282: (Module): Checking covariates for more complex models
283: than V1+V2. A lot of change to be done. Unstable.
284:
1.137 brouard 285: Revision 1.136 2010/04/26 20:30:53 brouard
286: (Module): merging some libgsl code. Fixing computation
287: of likelione (using inter/intrapolation if mle = 0) in order to
288: get same likelihood as if mle=1.
289: Some cleaning of code and comments added.
290:
1.136 brouard 291: Revision 1.135 2009/10/29 15:33:14 brouard
292: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
293:
1.135 brouard 294: Revision 1.134 2009/10/29 13:18:53 brouard
295: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
296:
1.134 brouard 297: Revision 1.133 2009/07/06 10:21:25 brouard
298: just nforces
299:
1.133 brouard 300: Revision 1.132 2009/07/06 08:22:05 brouard
301: Many tings
302:
1.132 brouard 303: Revision 1.131 2009/06/20 16:22:47 brouard
304: Some dimensions resccaled
305:
1.131 brouard 306: Revision 1.130 2009/05/26 06:44:34 brouard
307: (Module): Max Covariate is now set to 20 instead of 8. A
308: lot of cleaning with variables initialized to 0. Trying to make
309: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
310:
1.130 brouard 311: Revision 1.129 2007/08/31 13:49:27 lievre
312: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
313:
1.129 lievre 314: Revision 1.128 2006/06/30 13:02:05 brouard
315: (Module): Clarifications on computing e.j
316:
1.128 brouard 317: Revision 1.127 2006/04/28 18:11:50 brouard
318: (Module): Yes the sum of survivors was wrong since
319: imach-114 because nhstepm was no more computed in the age
320: loop. Now we define nhstepma in the age loop.
321: (Module): In order to speed up (in case of numerous covariates) we
322: compute health expectancies (without variances) in a first step
323: and then all the health expectancies with variances or standard
324: deviation (needs data from the Hessian matrices) which slows the
325: computation.
326: In the future we should be able to stop the program is only health
327: expectancies and graph are needed without standard deviations.
328:
1.127 brouard 329: Revision 1.126 2006/04/28 17:23:28 brouard
330: (Module): Yes the sum of survivors was wrong since
331: imach-114 because nhstepm was no more computed in the age
332: loop. Now we define nhstepma in the age loop.
333: Version 0.98h
334:
1.126 brouard 335: Revision 1.125 2006/04/04 15:20:31 lievre
336: Errors in calculation of health expectancies. Age was not initialized.
337: Forecasting file added.
338:
339: Revision 1.124 2006/03/22 17:13:53 lievre
340: Parameters are printed with %lf instead of %f (more numbers after the comma).
341: The log-likelihood is printed in the log file
342:
343: Revision 1.123 2006/03/20 10:52:43 brouard
344: * imach.c (Module): <title> changed, corresponds to .htm file
345: name. <head> headers where missing.
346:
347: * imach.c (Module): Weights can have a decimal point as for
348: English (a comma might work with a correct LC_NUMERIC environment,
349: otherwise the weight is truncated).
350: Modification of warning when the covariates values are not 0 or
351: 1.
352: Version 0.98g
353:
354: Revision 1.122 2006/03/20 09:45:41 brouard
355: (Module): Weights can have a decimal point as for
356: English (a comma might work with a correct LC_NUMERIC environment,
357: otherwise the weight is truncated).
358: Modification of warning when the covariates values are not 0 or
359: 1.
360: Version 0.98g
361:
362: Revision 1.121 2006/03/16 17:45:01 lievre
363: * imach.c (Module): Comments concerning covariates added
364:
365: * imach.c (Module): refinements in the computation of lli if
366: status=-2 in order to have more reliable computation if stepm is
367: not 1 month. Version 0.98f
368:
369: Revision 1.120 2006/03/16 15:10:38 lievre
370: (Module): refinements in the computation of lli if
371: status=-2 in order to have more reliable computation if stepm is
372: not 1 month. Version 0.98f
373:
374: Revision 1.119 2006/03/15 17:42:26 brouard
375: (Module): Bug if status = -2, the loglikelihood was
376: computed as likelihood omitting the logarithm. Version O.98e
377:
378: Revision 1.118 2006/03/14 18:20:07 brouard
379: (Module): varevsij Comments added explaining the second
380: table of variances if popbased=1 .
381: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
382: (Module): Function pstamp added
383: (Module): Version 0.98d
384:
385: Revision 1.117 2006/03/14 17:16:22 brouard
386: (Module): varevsij Comments added explaining the second
387: table of variances if popbased=1 .
388: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
389: (Module): Function pstamp added
390: (Module): Version 0.98d
391:
392: Revision 1.116 2006/03/06 10:29:27 brouard
393: (Module): Variance-covariance wrong links and
394: varian-covariance of ej. is needed (Saito).
395:
396: Revision 1.115 2006/02/27 12:17:45 brouard
397: (Module): One freematrix added in mlikeli! 0.98c
398:
399: Revision 1.114 2006/02/26 12:57:58 brouard
400: (Module): Some improvements in processing parameter
401: filename with strsep.
402:
403: Revision 1.113 2006/02/24 14:20:24 brouard
404: (Module): Memory leaks checks with valgrind and:
405: datafile was not closed, some imatrix were not freed and on matrix
406: allocation too.
407:
408: Revision 1.112 2006/01/30 09:55:26 brouard
409: (Module): Back to gnuplot.exe instead of wgnuplot.exe
410:
411: Revision 1.111 2006/01/25 20:38:18 brouard
412: (Module): Lots of cleaning and bugs added (Gompertz)
413: (Module): Comments can be added in data file. Missing date values
414: can be a simple dot '.'.
415:
416: Revision 1.110 2006/01/25 00:51:50 brouard
417: (Module): Lots of cleaning and bugs added (Gompertz)
418:
419: Revision 1.109 2006/01/24 19:37:15 brouard
420: (Module): Comments (lines starting with a #) are allowed in data.
421:
422: Revision 1.108 2006/01/19 18:05:42 lievre
423: Gnuplot problem appeared...
424: To be fixed
425:
426: Revision 1.107 2006/01/19 16:20:37 brouard
427: Test existence of gnuplot in imach path
428:
429: Revision 1.106 2006/01/19 13:24:36 brouard
430: Some cleaning and links added in html output
431:
432: Revision 1.105 2006/01/05 20:23:19 lievre
433: *** empty log message ***
434:
435: Revision 1.104 2005/09/30 16:11:43 lievre
436: (Module): sump fixed, loop imx fixed, and simplifications.
437: (Module): If the status is missing at the last wave but we know
438: that the person is alive, then we can code his/her status as -2
439: (instead of missing=-1 in earlier versions) and his/her
440: contributions to the likelihood is 1 - Prob of dying from last
441: health status (= 1-p13= p11+p12 in the easiest case of somebody in
442: the healthy state at last known wave). Version is 0.98
443:
444: Revision 1.103 2005/09/30 15:54:49 lievre
445: (Module): sump fixed, loop imx fixed, and simplifications.
446:
447: Revision 1.102 2004/09/15 17:31:30 brouard
448: Add the possibility to read data file including tab characters.
449:
450: Revision 1.101 2004/09/15 10:38:38 brouard
451: Fix on curr_time
452:
453: Revision 1.100 2004/07/12 18:29:06 brouard
454: Add version for Mac OS X. Just define UNIX in Makefile
455:
456: Revision 1.99 2004/06/05 08:57:40 brouard
457: *** empty log message ***
458:
459: Revision 1.98 2004/05/16 15:05:56 brouard
460: New version 0.97 . First attempt to estimate force of mortality
461: directly from the data i.e. without the need of knowing the health
462: state at each age, but using a Gompertz model: log u =a + b*age .
463: This is the basic analysis of mortality and should be done before any
464: other analysis, in order to test if the mortality estimated from the
465: cross-longitudinal survey is different from the mortality estimated
466: from other sources like vital statistic data.
467:
468: The same imach parameter file can be used but the option for mle should be -3.
469:
1.133 brouard 470: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 471: former routines in order to include the new code within the former code.
472:
473: The output is very simple: only an estimate of the intercept and of
474: the slope with 95% confident intervals.
475:
476: Current limitations:
477: A) Even if you enter covariates, i.e. with the
478: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
479: B) There is no computation of Life Expectancy nor Life Table.
480:
481: Revision 1.97 2004/02/20 13:25:42 lievre
482: Version 0.96d. Population forecasting command line is (temporarily)
483: suppressed.
484:
485: Revision 1.96 2003/07/15 15:38:55 brouard
486: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
487: rewritten within the same printf. Workaround: many printfs.
488:
489: Revision 1.95 2003/07/08 07:54:34 brouard
490: * imach.c (Repository):
491: (Repository): Using imachwizard code to output a more meaningful covariance
492: matrix (cov(a12,c31) instead of numbers.
493:
494: Revision 1.94 2003/06/27 13:00:02 brouard
495: Just cleaning
496:
497: Revision 1.93 2003/06/25 16:33:55 brouard
498: (Module): On windows (cygwin) function asctime_r doesn't
499: exist so I changed back to asctime which exists.
500: (Module): Version 0.96b
501:
502: Revision 1.92 2003/06/25 16:30:45 brouard
503: (Module): On windows (cygwin) function asctime_r doesn't
504: exist so I changed back to asctime which exists.
505:
506: Revision 1.91 2003/06/25 15:30:29 brouard
507: * imach.c (Repository): Duplicated warning errors corrected.
508: (Repository): Elapsed time after each iteration is now output. It
509: helps to forecast when convergence will be reached. Elapsed time
510: is stamped in powell. We created a new html file for the graphs
511: concerning matrix of covariance. It has extension -cov.htm.
512:
513: Revision 1.90 2003/06/24 12:34:15 brouard
514: (Module): Some bugs corrected for windows. Also, when
515: mle=-1 a template is output in file "or"mypar.txt with the design
516: of the covariance matrix to be input.
517:
518: Revision 1.89 2003/06/24 12:30:52 brouard
519: (Module): Some bugs corrected for windows. Also, when
520: mle=-1 a template is output in file "or"mypar.txt with the design
521: of the covariance matrix to be input.
522:
523: Revision 1.88 2003/06/23 17:54:56 brouard
524: * 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.
525:
526: Revision 1.87 2003/06/18 12:26:01 brouard
527: Version 0.96
528:
529: Revision 1.86 2003/06/17 20:04:08 brouard
530: (Module): Change position of html and gnuplot routines and added
531: routine fileappend.
532:
533: Revision 1.85 2003/06/17 13:12:43 brouard
534: * imach.c (Repository): Check when date of death was earlier that
535: current date of interview. It may happen when the death was just
536: prior to the death. In this case, dh was negative and likelihood
537: was wrong (infinity). We still send an "Error" but patch by
538: assuming that the date of death was just one stepm after the
539: interview.
540: (Repository): Because some people have very long ID (first column)
541: we changed int to long in num[] and we added a new lvector for
542: memory allocation. But we also truncated to 8 characters (left
543: truncation)
544: (Repository): No more line truncation errors.
545:
546: Revision 1.84 2003/06/13 21:44:43 brouard
547: * imach.c (Repository): Replace "freqsummary" at a correct
548: place. It differs from routine "prevalence" which may be called
549: many times. Probs is memory consuming and must be used with
550: parcimony.
551: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
552:
553: Revision 1.83 2003/06/10 13:39:11 lievre
554: *** empty log message ***
555:
556: Revision 1.82 2003/06/05 15:57:20 brouard
557: Add log in imach.c and fullversion number is now printed.
558:
559: */
560: /*
561: Interpolated Markov Chain
562:
563: Short summary of the programme:
564:
565: This program computes Healthy Life Expectancies from
566: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
567: first survey ("cross") where individuals from different ages are
568: interviewed on their health status or degree of disability (in the
569: case of a health survey which is our main interest) -2- at least a
570: second wave of interviews ("longitudinal") which measure each change
571: (if any) in individual health status. Health expectancies are
572: computed from the time spent in each health state according to a
573: model. More health states you consider, more time is necessary to reach the
574: Maximum Likelihood of the parameters involved in the model. The
575: simplest model is the multinomial logistic model where pij is the
576: probability to be observed in state j at the second wave
577: conditional to be observed in state i at the first wave. Therefore
578: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
579: 'age' is age and 'sex' is a covariate. If you want to have a more
580: complex model than "constant and age", you should modify the program
581: where the markup *Covariates have to be included here again* invites
582: you to do it. More covariates you add, slower the
583: convergence.
584:
585: The advantage of this computer programme, compared to a simple
586: multinomial logistic model, is clear when the delay between waves is not
587: identical for each individual. Also, if a individual missed an
588: intermediate interview, the information is lost, but taken into
589: account using an interpolation or extrapolation.
590:
591: hPijx is the probability to be observed in state i at age x+h
592: conditional to the observed state i at age x. The delay 'h' can be
593: split into an exact number (nh*stepm) of unobserved intermediate
594: states. This elementary transition (by month, quarter,
595: semester or year) is modelled as a multinomial logistic. The hPx
596: matrix is simply the matrix product of nh*stepm elementary matrices
597: and the contribution of each individual to the likelihood is simply
598: hPijx.
599:
600: Also this programme outputs the covariance matrix of the parameters but also
601: of the life expectancies. It also computes the period (stable) prevalence.
602:
1.133 brouard 603: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
604: Institut national d'études démographiques, Paris.
1.126 brouard 605: This software have been partly granted by Euro-REVES, a concerted action
606: from the European Union.
607: It is copyrighted identically to a GNU software product, ie programme and
608: software can be distributed freely for non commercial use. Latest version
609: can be accessed at http://euroreves.ined.fr/imach .
610:
611: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
612: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
613:
614: **********************************************************************/
615: /*
616: main
617: read parameterfile
618: read datafile
619: concatwav
620: freqsummary
621: if (mle >= 1)
622: mlikeli
623: print results files
624: if mle==1
625: computes hessian
626: read end of parameter file: agemin, agemax, bage, fage, estepm
627: begin-prev-date,...
628: open gnuplot file
629: open html file
1.145 brouard 630: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
631: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
632: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
633: freexexit2 possible for memory heap.
634:
635: h Pij x | pij_nom ficrestpij
636: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
637: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
638: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
639:
640: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
641: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
642: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
643: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
644: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
645:
1.126 brouard 646: forecasting if prevfcast==1 prevforecast call prevalence()
647: health expectancies
648: Variance-covariance of DFLE
649: prevalence()
650: movingaverage()
651: varevsij()
652: if popbased==1 varevsij(,popbased)
653: total life expectancies
654: Variance of period (stable) prevalence
655: end
656: */
657:
1.187 brouard 658: /* #define DEBUG */
659: /* #define DEBUGBRENT */
1.203 brouard 660: /* #define DEBUGLINMIN */
661: /* #define DEBUGHESS */
662: #define DEBUGHESSIJ
663: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165 brouard 664: #define POWELL /* Instead of NLOPT */
1.192 brouard 665: #define POWELLF1F3 /* Skip test */
1.186 brouard 666: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
667: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 668:
669: #include <math.h>
670: #include <stdio.h>
671: #include <stdlib.h>
672: #include <string.h>
1.159 brouard 673:
674: #ifdef _WIN32
675: #include <io.h>
1.172 brouard 676: #include <windows.h>
677: #include <tchar.h>
1.159 brouard 678: #else
1.126 brouard 679: #include <unistd.h>
1.159 brouard 680: #endif
1.126 brouard 681:
682: #include <limits.h>
683: #include <sys/types.h>
1.171 brouard 684:
685: #if defined(__GNUC__)
686: #include <sys/utsname.h> /* Doesn't work on Windows */
687: #endif
688:
1.126 brouard 689: #include <sys/stat.h>
690: #include <errno.h>
1.159 brouard 691: /* extern int errno; */
1.126 brouard 692:
1.157 brouard 693: /* #ifdef LINUX */
694: /* #include <time.h> */
695: /* #include "timeval.h" */
696: /* #else */
697: /* #include <sys/time.h> */
698: /* #endif */
699:
1.126 brouard 700: #include <time.h>
701:
1.136 brouard 702: #ifdef GSL
703: #include <gsl/gsl_errno.h>
704: #include <gsl/gsl_multimin.h>
705: #endif
706:
1.167 brouard 707:
1.162 brouard 708: #ifdef NLOPT
709: #include <nlopt.h>
710: typedef struct {
711: double (* function)(double [] );
712: } myfunc_data ;
713: #endif
714:
1.126 brouard 715: /* #include <libintl.h> */
716: /* #define _(String) gettext (String) */
717:
1.141 brouard 718: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 719:
720: #define GNUPLOTPROGRAM "gnuplot"
721: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
722: #define FILENAMELENGTH 132
723:
724: #define GLOCK_ERROR_NOPATH -1 /* empty path */
725: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
726:
1.144 brouard 727: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
728: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 729:
730: #define NINTERVMAX 8
1.144 brouard 731: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
732: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
733: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197 brouard 734: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.126 brouard 735: #define MAXN 20000
1.144 brouard 736: #define YEARM 12. /**< Number of months per year */
1.126 brouard 737: #define AGESUP 130
738: #define AGEBASE 40
1.194 brouard 739: #define AGEOVERFLOW 1.e20
1.164 brouard 740: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 741: #ifdef _WIN32
742: #define DIRSEPARATOR '\\'
743: #define CHARSEPARATOR "\\"
744: #define ODIRSEPARATOR '/'
745: #else
1.126 brouard 746: #define DIRSEPARATOR '/'
747: #define CHARSEPARATOR "/"
748: #define ODIRSEPARATOR '\\'
749: #endif
750:
1.205 ! brouard 751: /* $Id: imach.c,v 1.204 2015/10/01 16:20:26 brouard Exp $ */
1.126 brouard 752: /* $State: Exp $ */
1.196 brouard 753: #include "version.h"
754: char version[]=__IMACH_VERSION__;
1.204 brouard 755: 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";
1.205 ! brouard 756: char fullversion[]="$Revision: 1.204 $ $Date: 2015/10/01 16:20:26 $";
1.126 brouard 757: char strstart[80];
758: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 759: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 760: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 761: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
762: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
763: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
764: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
765: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
766: int cptcovprodnoage=0; /**< Number of covariate products without age */
767: int cptcoveff=0; /* Total number of covariates to vary for printing results */
768: int cptcov=0; /* Working variable */
1.126 brouard 769: int npar=NPARMAX;
770: int nlstate=2; /* Number of live states */
771: int ndeath=1; /* Number of dead states */
1.130 brouard 772: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 773: int popbased=0;
774:
775: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 776: int maxwav=0; /* Maxim number of waves */
777: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
778: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
779: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 780: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 781: int mle=1, weightopt=0;
1.126 brouard 782: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
783: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
784: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
785: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 786: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 787: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 788: double **matprod2(); /* test */
1.126 brouard 789: double **oldm, **newm, **savm; /* Working pointers to matrices */
790: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 791: /*FILE *fic ; */ /* Used in readdata only */
792: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 793: FILE *ficlog, *ficrespow;
1.130 brouard 794: int globpr=0; /* Global variable for printing or not */
1.126 brouard 795: double fretone; /* Only one call to likelihood */
1.130 brouard 796: long ipmx=0; /* Number of contributions */
1.126 brouard 797: double sw; /* Sum of weights */
798: char filerespow[FILENAMELENGTH];
799: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
800: FILE *ficresilk;
801: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
802: FILE *ficresprobmorprev;
803: FILE *fichtm, *fichtmcov; /* Html File */
804: FILE *ficreseij;
805: char filerese[FILENAMELENGTH];
806: FILE *ficresstdeij;
807: char fileresstde[FILENAMELENGTH];
808: FILE *ficrescveij;
809: char filerescve[FILENAMELENGTH];
810: FILE *ficresvij;
811: char fileresv[FILENAMELENGTH];
812: FILE *ficresvpl;
813: char fileresvpl[FILENAMELENGTH];
814: char title[MAXLINE];
815: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
816: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
817: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
818: char command[FILENAMELENGTH];
819: int outcmd=0;
820:
821: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202 brouard 822: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126 brouard 823: char filelog[FILENAMELENGTH]; /* Log file */
824: char filerest[FILENAMELENGTH];
825: char fileregp[FILENAMELENGTH];
826: char popfile[FILENAMELENGTH];
827:
828: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
829:
1.157 brouard 830: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
831: /* struct timezone tzp; */
832: /* extern int gettimeofday(); */
833: struct tm tml, *gmtime(), *localtime();
834:
835: extern time_t time();
836:
837: struct tm start_time, end_time, curr_time, last_time, forecast_time;
838: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
839: struct tm tm;
840:
1.126 brouard 841: char strcurr[80], strfor[80];
842:
843: char *endptr;
844: long lval;
845: double dval;
846:
847: #define NR_END 1
848: #define FREE_ARG char*
849: #define FTOL 1.0e-10
850:
851: #define NRANSI
852: #define ITMAX 200
853:
854: #define TOL 2.0e-4
855:
856: #define CGOLD 0.3819660
857: #define ZEPS 1.0e-10
858: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
859:
860: #define GOLD 1.618034
861: #define GLIMIT 100.0
862: #define TINY 1.0e-20
863:
864: static double maxarg1,maxarg2;
865: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
866: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
867:
868: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
869: #define rint(a) floor(a+0.5)
1.166 brouard 870: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 871: #define mytinydouble 1.0e-16
1.166 brouard 872: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
873: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
874: /* static double dsqrarg; */
875: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 876: static double sqrarg;
877: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
878: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
879: int agegomp= AGEGOMP;
880:
881: int imx;
882: int stepm=1;
883: /* Stepm, step in month: minimum step interpolation*/
884:
885: int estepm;
886: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
887:
888: int m,nb;
889: long *num;
1.197 brouard 890: int firstpass=0, lastpass=4,*cod, *cens;
1.192 brouard 891: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
892: covariate for which somebody answered excluding
893: undefined. Usually 2: 0 and 1. */
894: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
895: covariate for which somebody answered including
896: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 897: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
898: double **pmmij, ***probs;
899: double *ageexmed,*agecens;
900: double dateintmean=0;
901:
902: double *weight;
903: int **s; /* Status */
1.141 brouard 904: double *agedc;
1.145 brouard 905: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 906: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 907: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 908: double idx;
909: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197 brouard 910: int *Tage;
1.145 brouard 911: int *Ndum; /** Freq of modality (tricode */
1.200 brouard 912: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141 brouard 913: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 914: double *lsurv, *lpop, *tpop;
915:
1.143 brouard 916: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
917: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 918:
919: /**************** split *************************/
920: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
921: {
922: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
923: the name of the file (name), its extension only (ext) and its first part of the name (finame)
924: */
925: char *ss; /* pointer */
1.186 brouard 926: int l1=0, l2=0; /* length counters */
1.126 brouard 927:
928: l1 = strlen(path ); /* length of path */
929: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
930: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
931: if ( ss == NULL ) { /* no directory, so determine current directory */
932: strcpy( name, path ); /* we got the fullname name because no directory */
933: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
934: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
935: /* get current working directory */
936: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 937: #ifdef WIN32
938: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
939: #else
940: if (getcwd(dirc, FILENAME_MAX) == NULL) {
941: #endif
1.126 brouard 942: return( GLOCK_ERROR_GETCWD );
943: }
944: /* got dirc from getcwd*/
945: printf(" DIRC = %s \n",dirc);
1.205 ! brouard 946: } else { /* strip directory from path */
1.126 brouard 947: ss++; /* after this, the filename */
948: l2 = strlen( ss ); /* length of filename */
949: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
950: strcpy( name, ss ); /* save file name */
951: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 952: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 953: printf(" DIRC2 = %s \n",dirc);
954: }
955: /* We add a separator at the end of dirc if not exists */
956: l1 = strlen( dirc ); /* length of directory */
957: if( dirc[l1-1] != DIRSEPARATOR ){
958: dirc[l1] = DIRSEPARATOR;
959: dirc[l1+1] = 0;
960: printf(" DIRC3 = %s \n",dirc);
961: }
962: ss = strrchr( name, '.' ); /* find last / */
963: if (ss >0){
964: ss++;
965: strcpy(ext,ss); /* save extension */
966: l1= strlen( name);
967: l2= strlen(ss)+1;
968: strncpy( finame, name, l1-l2);
969: finame[l1-l2]= 0;
970: }
971:
972: return( 0 ); /* we're done */
973: }
974:
975:
976: /******************************************/
977:
978: void replace_back_to_slash(char *s, char*t)
979: {
980: int i;
981: int lg=0;
982: i=0;
983: lg=strlen(t);
984: for(i=0; i<= lg; i++) {
985: (s[i] = t[i]);
986: if (t[i]== '\\') s[i]='/';
987: }
988: }
989:
1.132 brouard 990: char *trimbb(char *out, char *in)
1.137 brouard 991: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 992: char *s;
993: s=out;
994: while (*in != '\0'){
1.137 brouard 995: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 996: in++;
997: }
998: *out++ = *in++;
999: }
1000: *out='\0';
1001: return s;
1002: }
1003:
1.187 brouard 1004: /* char *substrchaine(char *out, char *in, char *chain) */
1005: /* { */
1006: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1007: /* char *s, *t; */
1008: /* t=in;s=out; */
1009: /* while ((*in != *chain) && (*in != '\0')){ */
1010: /* *out++ = *in++; */
1011: /* } */
1012:
1013: /* /\* *in matches *chain *\/ */
1014: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1015: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1016: /* } */
1017: /* in--; chain--; */
1018: /* while ( (*in != '\0')){ */
1019: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1020: /* *out++ = *in++; */
1021: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1022: /* } */
1023: /* *out='\0'; */
1024: /* out=s; */
1025: /* return out; */
1026: /* } */
1027: char *substrchaine(char *out, char *in, char *chain)
1028: {
1029: /* Substract chain 'chain' from 'in', return and output 'out' */
1030: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1031:
1032: char *strloc;
1033:
1034: strcpy (out, in);
1035: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1036: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1037: if(strloc != NULL){
1038: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1039: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1040: /* strcpy (strloc, strloc +strlen(chain));*/
1041: }
1042: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1043: return out;
1044: }
1045:
1046:
1.145 brouard 1047: char *cutl(char *blocc, char *alocc, char *in, char occ)
1048: {
1.187 brouard 1049: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 1050: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 1051: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 1052: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1053: */
1.160 brouard 1054: char *s, *t;
1.145 brouard 1055: t=in;s=in;
1056: while ((*in != occ) && (*in != '\0')){
1057: *alocc++ = *in++;
1058: }
1059: if( *in == occ){
1060: *(alocc)='\0';
1061: s=++in;
1062: }
1063:
1064: if (s == t) {/* occ not found */
1065: *(alocc-(in-s))='\0';
1066: in=s;
1067: }
1068: while ( *in != '\0'){
1069: *blocc++ = *in++;
1070: }
1071:
1072: *blocc='\0';
1073: return t;
1074: }
1.137 brouard 1075: char *cutv(char *blocc, char *alocc, char *in, char occ)
1076: {
1.187 brouard 1077: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1078: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1079: gives blocc="abcdef2ghi" and alocc="j".
1080: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1081: */
1082: char *s, *t;
1083: t=in;s=in;
1084: while (*in != '\0'){
1085: while( *in == occ){
1086: *blocc++ = *in++;
1087: s=in;
1088: }
1089: *blocc++ = *in++;
1090: }
1091: if (s == t) /* occ not found */
1092: *(blocc-(in-s))='\0';
1093: else
1094: *(blocc-(in-s)-1)='\0';
1095: in=s;
1096: while ( *in != '\0'){
1097: *alocc++ = *in++;
1098: }
1099:
1100: *alocc='\0';
1101: return s;
1102: }
1103:
1.126 brouard 1104: int nbocc(char *s, char occ)
1105: {
1106: int i,j=0;
1107: int lg=20;
1108: i=0;
1109: lg=strlen(s);
1110: for(i=0; i<= lg; i++) {
1111: if (s[i] == occ ) j++;
1112: }
1113: return j;
1114: }
1115:
1.137 brouard 1116: /* void cutv(char *u,char *v, char*t, char occ) */
1117: /* { */
1118: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1119: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1120: /* gives u="abcdef2ghi" and v="j" *\/ */
1121: /* int i,lg,j,p=0; */
1122: /* i=0; */
1123: /* lg=strlen(t); */
1124: /* for(j=0; j<=lg-1; j++) { */
1125: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1126: /* } */
1.126 brouard 1127:
1.137 brouard 1128: /* for(j=0; j<p; j++) { */
1129: /* (u[j] = t[j]); */
1130: /* } */
1131: /* u[p]='\0'; */
1.126 brouard 1132:
1.137 brouard 1133: /* for(j=0; j<= lg; j++) { */
1134: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1135: /* } */
1136: /* } */
1.126 brouard 1137:
1.160 brouard 1138: #ifdef _WIN32
1139: char * strsep(char **pp, const char *delim)
1140: {
1141: char *p, *q;
1142:
1143: if ((p = *pp) == NULL)
1144: return 0;
1145: if ((q = strpbrk (p, delim)) != NULL)
1146: {
1147: *pp = q + 1;
1148: *q = '\0';
1149: }
1150: else
1151: *pp = 0;
1152: return p;
1153: }
1154: #endif
1155:
1.126 brouard 1156: /********************** nrerror ********************/
1157:
1158: void nrerror(char error_text[])
1159: {
1160: fprintf(stderr,"ERREUR ...\n");
1161: fprintf(stderr,"%s\n",error_text);
1162: exit(EXIT_FAILURE);
1163: }
1164: /*********************** vector *******************/
1165: double *vector(int nl, int nh)
1166: {
1167: double *v;
1168: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1169: if (!v) nrerror("allocation failure in vector");
1170: return v-nl+NR_END;
1171: }
1172:
1173: /************************ free vector ******************/
1174: void free_vector(double*v, int nl, int nh)
1175: {
1176: free((FREE_ARG)(v+nl-NR_END));
1177: }
1178:
1179: /************************ivector *******************************/
1180: int *ivector(long nl,long nh)
1181: {
1182: int *v;
1183: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1184: if (!v) nrerror("allocation failure in ivector");
1185: return v-nl+NR_END;
1186: }
1187:
1188: /******************free ivector **************************/
1189: void free_ivector(int *v, long nl, long nh)
1190: {
1191: free((FREE_ARG)(v+nl-NR_END));
1192: }
1193:
1194: /************************lvector *******************************/
1195: long *lvector(long nl,long nh)
1196: {
1197: long *v;
1198: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1199: if (!v) nrerror("allocation failure in ivector");
1200: return v-nl+NR_END;
1201: }
1202:
1203: /******************free lvector **************************/
1204: void free_lvector(long *v, long nl, long nh)
1205: {
1206: free((FREE_ARG)(v+nl-NR_END));
1207: }
1208:
1209: /******************* imatrix *******************************/
1210: int **imatrix(long nrl, long nrh, long ncl, long nch)
1211: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1212: {
1213: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1214: int **m;
1215:
1216: /* allocate pointers to rows */
1217: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1218: if (!m) nrerror("allocation failure 1 in matrix()");
1219: m += NR_END;
1220: m -= nrl;
1221:
1222:
1223: /* allocate rows and set pointers to them */
1224: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1225: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1226: m[nrl] += NR_END;
1227: m[nrl] -= ncl;
1228:
1229: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1230:
1231: /* return pointer to array of pointers to rows */
1232: return m;
1233: }
1234:
1235: /****************** free_imatrix *************************/
1236: void free_imatrix(m,nrl,nrh,ncl,nch)
1237: int **m;
1238: long nch,ncl,nrh,nrl;
1239: /* free an int matrix allocated by imatrix() */
1240: {
1241: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1242: free((FREE_ARG) (m+nrl-NR_END));
1243: }
1244:
1245: /******************* matrix *******************************/
1246: double **matrix(long nrl, long nrh, long ncl, long nch)
1247: {
1248: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1249: double **m;
1250:
1251: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1252: if (!m) nrerror("allocation failure 1 in matrix()");
1253: m += NR_END;
1254: m -= nrl;
1255:
1256: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1257: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1258: m[nrl] += NR_END;
1259: m[nrl] -= ncl;
1260:
1261: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1262: return m;
1.145 brouard 1263: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1264: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1265: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1266: */
1267: }
1268:
1269: /*************************free matrix ************************/
1270: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1271: {
1272: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1273: free((FREE_ARG)(m+nrl-NR_END));
1274: }
1275:
1276: /******************* ma3x *******************************/
1277: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1278: {
1279: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1280: double ***m;
1281:
1282: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1283: if (!m) nrerror("allocation failure 1 in matrix()");
1284: m += NR_END;
1285: m -= nrl;
1286:
1287: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1288: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1289: m[nrl] += NR_END;
1290: m[nrl] -= ncl;
1291:
1292: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1293:
1294: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1295: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1296: m[nrl][ncl] += NR_END;
1297: m[nrl][ncl] -= nll;
1298: for (j=ncl+1; j<=nch; j++)
1299: m[nrl][j]=m[nrl][j-1]+nlay;
1300:
1301: for (i=nrl+1; i<=nrh; i++) {
1302: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1303: for (j=ncl+1; j<=nch; j++)
1304: m[i][j]=m[i][j-1]+nlay;
1305: }
1306: return m;
1307: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1308: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1309: */
1310: }
1311:
1312: /*************************free ma3x ************************/
1313: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1314: {
1315: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1316: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1317: free((FREE_ARG)(m+nrl-NR_END));
1318: }
1319:
1320: /*************** function subdirf ***********/
1321: char *subdirf(char fileres[])
1322: {
1323: /* Caution optionfilefiname is hidden */
1324: strcpy(tmpout,optionfilefiname);
1325: strcat(tmpout,"/"); /* Add to the right */
1326: strcat(tmpout,fileres);
1327: return tmpout;
1328: }
1329:
1330: /*************** function subdirf2 ***********/
1331: char *subdirf2(char fileres[], char *preop)
1332: {
1333:
1334: /* Caution optionfilefiname is hidden */
1335: strcpy(tmpout,optionfilefiname);
1336: strcat(tmpout,"/");
1337: strcat(tmpout,preop);
1338: strcat(tmpout,fileres);
1339: return tmpout;
1340: }
1341:
1342: /*************** function subdirf3 ***********/
1343: char *subdirf3(char fileres[], char *preop, char *preop2)
1344: {
1345:
1346: /* Caution optionfilefiname is hidden */
1347: strcpy(tmpout,optionfilefiname);
1348: strcat(tmpout,"/");
1349: strcat(tmpout,preop);
1350: strcat(tmpout,preop2);
1351: strcat(tmpout,fileres);
1352: return tmpout;
1353: }
1354:
1.162 brouard 1355: char *asc_diff_time(long time_sec, char ascdiff[])
1356: {
1357: long sec_left, days, hours, minutes;
1358: days = (time_sec) / (60*60*24);
1359: sec_left = (time_sec) % (60*60*24);
1360: hours = (sec_left) / (60*60) ;
1361: sec_left = (sec_left) %(60*60);
1362: minutes = (sec_left) /60;
1363: sec_left = (sec_left) % (60);
1364: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1365: return ascdiff;
1366: }
1367:
1.126 brouard 1368: /***************** f1dim *************************/
1369: extern int ncom;
1370: extern double *pcom,*xicom;
1371: extern double (*nrfunc)(double []);
1372:
1373: double f1dim(double x)
1374: {
1375: int j;
1376: double f;
1377: double *xt;
1378:
1379: xt=vector(1,ncom);
1380: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1381: f=(*nrfunc)(xt);
1382: free_vector(xt,1,ncom);
1383: return f;
1384: }
1385:
1386: /*****************brent *************************/
1387: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1388: {
1389: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1390: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1391: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1392: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1393: * returned function value.
1394: */
1.126 brouard 1395: int iter;
1396: double a,b,d,etemp;
1.159 brouard 1397: double fu=0,fv,fw,fx;
1.164 brouard 1398: double ftemp=0.;
1.126 brouard 1399: double p,q,r,tol1,tol2,u,v,w,x,xm;
1400: double e=0.0;
1401:
1402: a=(ax < cx ? ax : cx);
1403: b=(ax > cx ? ax : cx);
1404: x=w=v=bx;
1405: fw=fv=fx=(*f)(x);
1406: for (iter=1;iter<=ITMAX;iter++) {
1407: xm=0.5*(a+b);
1408: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1409: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1410: printf(".");fflush(stdout);
1411: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1412: #ifdef DEBUGBRENT
1.126 brouard 1413: 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);
1414: 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);
1415: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1416: #endif
1417: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1418: *xmin=x;
1419: return fx;
1420: }
1421: ftemp=fu;
1422: if (fabs(e) > tol1) {
1423: r=(x-w)*(fx-fv);
1424: q=(x-v)*(fx-fw);
1425: p=(x-v)*q-(x-w)*r;
1426: q=2.0*(q-r);
1427: if (q > 0.0) p = -p;
1428: q=fabs(q);
1429: etemp=e;
1430: e=d;
1431: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1432: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1433: else {
1434: d=p/q;
1435: u=x+d;
1436: if (u-a < tol2 || b-u < tol2)
1437: d=SIGN(tol1,xm-x);
1438: }
1439: } else {
1440: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1441: }
1442: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1443: fu=(*f)(u);
1444: if (fu <= fx) {
1445: if (u >= x) a=x; else b=x;
1446: SHFT(v,w,x,u)
1.183 brouard 1447: SHFT(fv,fw,fx,fu)
1448: } else {
1449: if (u < x) a=u; else b=u;
1450: if (fu <= fw || w == x) {
1451: v=w;
1452: w=u;
1453: fv=fw;
1454: fw=fu;
1455: } else if (fu <= fv || v == x || v == w) {
1456: v=u;
1457: fv=fu;
1458: }
1459: }
1.126 brouard 1460: }
1461: nrerror("Too many iterations in brent");
1462: *xmin=x;
1463: return fx;
1464: }
1465:
1466: /****************** mnbrak ***********************/
1467:
1468: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1469: double (*func)(double))
1.183 brouard 1470: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1471: the downhill direction (defined by the function as evaluated at the initial points) and returns
1472: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1473: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1474: */
1.126 brouard 1475: double ulim,u,r,q, dum;
1476: double fu;
1.187 brouard 1477:
1478: double scale=10.;
1479: int iterscale=0;
1480:
1481: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1482: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1483:
1484:
1485: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1486: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1487: /* *bx = *ax - (*ax - *bx)/scale; */
1488: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1489: /* } */
1490:
1.126 brouard 1491: if (*fb > *fa) {
1492: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1493: SHFT(dum,*fb,*fa,dum)
1494: }
1.126 brouard 1495: *cx=(*bx)+GOLD*(*bx-*ax);
1496: *fc=(*func)(*cx);
1.183 brouard 1497: #ifdef DEBUG
1498: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1499: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1500: #endif
1501: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1502: r=(*bx-*ax)*(*fb-*fc);
1503: q=(*bx-*cx)*(*fb-*fa);
1504: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1505: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1506: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1507: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1508: fu=(*func)(u);
1.163 brouard 1509: #ifdef DEBUG
1510: /* f(x)=A(x-u)**2+f(u) */
1511: double A, fparabu;
1512: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1513: fparabu= *fa - A*(*ax-u)*(*ax-u);
1514: 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);
1515: 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);
1.183 brouard 1516: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1517: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1518: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1519: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1520: #endif
1.184 brouard 1521: #ifdef MNBRAKORIGINAL
1.183 brouard 1522: #else
1.191 brouard 1523: /* if (fu > *fc) { */
1524: /* #ifdef DEBUG */
1525: /* printf("mnbrak4 fu > fc \n"); */
1526: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1527: /* #endif */
1528: /* /\* 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 *\\/ *\/ */
1529: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1530: /* dum=u; /\* Shifting c and u *\/ */
1531: /* u = *cx; */
1532: /* *cx = dum; */
1533: /* dum = fu; */
1534: /* fu = *fc; */
1535: /* *fc =dum; */
1536: /* } else { /\* end *\/ */
1537: /* #ifdef DEBUG */
1538: /* printf("mnbrak3 fu < fc \n"); */
1539: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1540: /* #endif */
1541: /* dum=u; /\* Shifting c and u *\/ */
1542: /* u = *cx; */
1543: /* *cx = dum; */
1544: /* dum = fu; */
1545: /* fu = *fc; */
1546: /* *fc =dum; */
1547: /* } */
1.183 brouard 1548: #ifdef DEBUG
1.191 brouard 1549: printf("mnbrak34 fu < or >= fc \n");
1550: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1551: #endif
1.191 brouard 1552: dum=u; /* Shifting c and u */
1553: u = *cx;
1554: *cx = dum;
1555: dum = fu;
1556: fu = *fc;
1557: *fc =dum;
1.183 brouard 1558: #endif
1.162 brouard 1559: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1560: #ifdef DEBUG
1561: printf("mnbrak2 u after c but before ulim\n");
1562: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1563: #endif
1.126 brouard 1564: fu=(*func)(u);
1565: if (fu < *fc) {
1.183 brouard 1566: #ifdef DEBUG
1567: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1568: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1569: #endif
1.126 brouard 1570: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1571: SHFT(*fb,*fc,fu,(*func)(u))
1572: }
1.162 brouard 1573: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1574: #ifdef DEBUG
1575: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1576: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1577: #endif
1.126 brouard 1578: u=ulim;
1579: fu=(*func)(u);
1.183 brouard 1580: } else { /* u could be left to b (if r > q parabola has a maximum) */
1581: #ifdef DEBUG
1582: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1583: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1584: #endif
1.126 brouard 1585: u=(*cx)+GOLD*(*cx-*bx);
1586: fu=(*func)(u);
1.183 brouard 1587: } /* end tests */
1.126 brouard 1588: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1589: SHFT(*fa,*fb,*fc,fu)
1590: #ifdef DEBUG
1591: 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);
1592: 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);
1593: #endif
1594: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126 brouard 1595: }
1596:
1597: /*************** linmin ************************/
1.162 brouard 1598: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1599: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1600: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1601: the value of func at the returned location p . This is actually all accomplished by calling the
1602: routines mnbrak and brent .*/
1.126 brouard 1603: int ncom;
1604: double *pcom,*xicom;
1605: double (*nrfunc)(double []);
1606:
1607: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1608: {
1609: double brent(double ax, double bx, double cx,
1610: double (*f)(double), double tol, double *xmin);
1611: double f1dim(double x);
1612: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1613: double *fc, double (*func)(double));
1614: int j;
1615: double xx,xmin,bx,ax;
1616: double fx,fb,fa;
1.187 brouard 1617:
1.203 brouard 1618: #ifdef LINMINORIGINAL
1619: #else
1620: double scale=10., axs, xxs; /* Scale added for infinity */
1621: #endif
1622:
1.126 brouard 1623: ncom=n;
1624: pcom=vector(1,n);
1625: xicom=vector(1,n);
1626: nrfunc=func;
1627: for (j=1;j<=n;j++) {
1628: pcom[j]=p[j];
1.202 brouard 1629: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126 brouard 1630: }
1.187 brouard 1631:
1.203 brouard 1632: #ifdef LINMINORIGINAL
1633: xx=1.;
1634: #else
1635: axs=0.0;
1636: xxs=1.;
1637: do{
1638: xx= xxs;
1639: #endif
1.187 brouard 1640: ax=0.;
1641: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1642: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1643: /* 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)) */
1644: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1645: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1646: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1647: /* 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]]*/
1.203 brouard 1648: #ifdef LINMINORIGINAL
1649: #else
1650: if (fx != fx){
1651: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1652: printf("|");
1653: fprintf(ficlog,"|");
1654: #ifdef DEBUGLINMIN
1655: 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);
1656: #endif
1657: }
1658: }while(fx != fx);
1659: #endif
1660:
1.191 brouard 1661: #ifdef DEBUGLINMIN
1662: 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);
1.202 brouard 1663: 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);
1.191 brouard 1664: #endif
1.187 brouard 1665: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1666: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1667: /* fmin = f(p[j] + xmin * xi[j]) */
1668: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1669: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1670: #ifdef DEBUG
1671: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1672: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1673: #endif
1.191 brouard 1674: #ifdef DEBUGLINMIN
1675: printf("linmin end ");
1.202 brouard 1676: fprintf(ficlog,"linmin end ");
1.191 brouard 1677: #endif
1.126 brouard 1678: for (j=1;j<=n;j++) {
1.203 brouard 1679: #ifdef LINMINORIGINAL
1680: xi[j] *= xmin;
1681: #else
1682: #ifdef DEBUGLINMIN
1683: if(xxs <1.0)
1684: printf(" before xi[%d]=%12.8f", j,xi[j]);
1685: #endif
1686: 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) */
1687: #ifdef DEBUGLINMIN
1688: if(xxs <1.0)
1689: 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 );
1690: #endif
1691: #endif
1.187 brouard 1692: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1693: }
1.191 brouard 1694: #ifdef DEBUGLINMIN
1.203 brouard 1695: printf("\n");
1.191 brouard 1696: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202 brouard 1697: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191 brouard 1698: for (j=1;j<=n;j++) {
1.202 brouard 1699: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1700: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1701: if(j % ncovmodel == 0){
1.191 brouard 1702: printf("\n");
1.202 brouard 1703: fprintf(ficlog,"\n");
1704: }
1.191 brouard 1705: }
1.203 brouard 1706: #else
1.191 brouard 1707: #endif
1.126 brouard 1708: free_vector(xicom,1,n);
1709: free_vector(pcom,1,n);
1710: }
1711:
1712:
1713: /*************** powell ************************/
1.162 brouard 1714: /*
1715: Minimization of a function func of n variables. Input consists of an initial starting point
1716: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1717: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1718: such that failure to decrease by more than this amount on one iteration signals doneness. On
1719: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1720: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1721: */
1.126 brouard 1722: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1723: double (*func)(double []))
1724: {
1725: void linmin(double p[], double xi[], int n, double *fret,
1726: double (*func)(double []));
1727: int i,ibig,j;
1728: double del,t,*pt,*ptt,*xit;
1.181 brouard 1729: double directest;
1.126 brouard 1730: double fp,fptt;
1731: double *xits;
1732: int niterf, itmp;
1733:
1734: pt=vector(1,n);
1735: ptt=vector(1,n);
1736: xit=vector(1,n);
1737: xits=vector(1,n);
1738: *fret=(*func)(p);
1739: for (j=1;j<=n;j++) pt[j]=p[j];
1.202 brouard 1740: rcurr_time = time(NULL);
1.126 brouard 1741: for (*iter=1;;++(*iter)) {
1.187 brouard 1742: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1743: ibig=0;
1744: del=0.0;
1.157 brouard 1745: rlast_time=rcurr_time;
1746: /* (void) gettimeofday(&curr_time,&tzp); */
1747: rcurr_time = time(NULL);
1748: curr_time = *localtime(&rcurr_time);
1749: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1750: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1751: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1752: for (i=1;i<=n;i++) {
1.126 brouard 1753: printf(" %d %.12f",i, p[i]);
1754: fprintf(ficlog," %d %.12lf",i, p[i]);
1755: fprintf(ficrespow," %.12lf", p[i]);
1756: }
1757: printf("\n");
1758: fprintf(ficlog,"\n");
1759: fprintf(ficrespow,"\n");fflush(ficrespow);
1760: if(*iter <=3){
1.157 brouard 1761: tml = *localtime(&rcurr_time);
1762: strcpy(strcurr,asctime(&tml));
1763: rforecast_time=rcurr_time;
1.126 brouard 1764: itmp = strlen(strcurr);
1765: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1766: strcurr[itmp-1]='\0';
1.162 brouard 1767: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1768: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1769: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1770: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1771: forecast_time = *localtime(&rforecast_time);
1772: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1773: itmp = strlen(strfor);
1774: if(strfor[itmp-1]=='\n')
1775: strfor[itmp-1]='\0';
1.157 brouard 1776: 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);
1777: 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);
1.126 brouard 1778: }
1779: }
1.187 brouard 1780: for (i=1;i<=n;i++) { /* For each direction i */
1781: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1782: fptt=(*fret);
1783: #ifdef DEBUG
1.203 brouard 1784: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1785: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1786: #endif
1.203 brouard 1787: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1788: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1789: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1790: /* Outputs are fret(new point p) p is updated and xit rescaled */
1791: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1792: /* because that direction will be replaced unless the gain del is small */
1793: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1794: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1795: /* with the new direction. */
1.126 brouard 1796: del=fabs(fptt-(*fret));
1797: ibig=i;
1798: }
1799: #ifdef DEBUG
1800: printf("%d %.12e",i,(*fret));
1801: fprintf(ficlog,"%d %.12e",i,(*fret));
1802: for (j=1;j<=n;j++) {
1803: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1804: printf(" x(%d)=%.12e",j,xit[j]);
1805: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1806: }
1807: for(j=1;j<=n;j++) {
1.162 brouard 1808: printf(" p(%d)=%.12e",j,p[j]);
1809: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1810: }
1811: printf("\n");
1812: fprintf(ficlog,"\n");
1813: #endif
1.187 brouard 1814: } /* end loop on each direction i */
1815: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1816: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1817: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1818: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1819: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1820: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1821: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1822: /* decreased of more than 3.84 */
1823: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1824: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1825: /* By adding 10 parameters more the gain should be 18.31 */
1826:
1827: /* Starting the program with initial values given by a former maximization will simply change */
1828: /* the scales of the directions and the directions, because the are reset to canonical directions */
1829: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1830: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1831: #ifdef DEBUG
1832: int k[2],l;
1833: k[0]=1;
1834: k[1]=-1;
1835: printf("Max: %.12e",(*func)(p));
1836: fprintf(ficlog,"Max: %.12e",(*func)(p));
1837: for (j=1;j<=n;j++) {
1838: printf(" %.12e",p[j]);
1839: fprintf(ficlog," %.12e",p[j]);
1840: }
1841: printf("\n");
1842: fprintf(ficlog,"\n");
1843: for(l=0;l<=1;l++) {
1844: for (j=1;j<=n;j++) {
1845: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1846: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1847: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1848: }
1849: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1850: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1851: }
1852: #endif
1853:
1854:
1855: free_vector(xit,1,n);
1856: free_vector(xits,1,n);
1857: free_vector(ptt,1,n);
1858: free_vector(pt,1,n);
1859: return;
1.192 brouard 1860: } /* enough precision */
1.126 brouard 1861: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1862: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1863: ptt[j]=2.0*p[j]-pt[j];
1864: xit[j]=p[j]-pt[j];
1865: pt[j]=p[j];
1866: }
1.181 brouard 1867: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1868: #ifdef POWELLF1F3
1869: #else
1.161 brouard 1870: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1871: #endif
1.162 brouard 1872: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1873: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1874: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1875: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1876: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1877: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1878: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1879: #ifdef NRCORIGINAL
1880: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1881: #else
1882: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161 brouard 1883: t= t- del*SQR(fp-fptt);
1.183 brouard 1884: #endif
1.202 brouard 1885: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161 brouard 1886: #ifdef DEBUG
1.181 brouard 1887: 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);
1888: 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);
1.161 brouard 1889: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1890: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1891: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1892: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1893: 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);
1894: 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);
1895: #endif
1.183 brouard 1896: #ifdef POWELLORIGINAL
1897: if (t < 0.0) { /* Then we use it for new direction */
1898: #else
1.182 brouard 1899: if (directest*t < 0.0) { /* Contradiction between both tests */
1.202 brouard 1900: 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);
1.192 brouard 1901: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202 brouard 1902: 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);
1.192 brouard 1903: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1904: }
1.181 brouard 1905: if (directest < 0.0) { /* Then we use it for new direction */
1906: #endif
1.191 brouard 1907: #ifdef DEBUGLINMIN
1908: printf("Before linmin in direction P%d-P0\n",n);
1909: for (j=1;j<=n;j++) {
1.202 brouard 1910: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1911: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1912: if(j % ncovmodel == 0){
1.191 brouard 1913: printf("\n");
1.202 brouard 1914: fprintf(ficlog,"\n");
1915: }
1.191 brouard 1916: }
1917: #endif
1.187 brouard 1918: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1919: #ifdef DEBUGLINMIN
1920: for (j=1;j<=n;j++) {
1921: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202 brouard 1922: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1923: if(j % ncovmodel == 0){
1.191 brouard 1924: printf("\n");
1.202 brouard 1925: fprintf(ficlog,"\n");
1926: }
1.191 brouard 1927: }
1928: #endif
1.126 brouard 1929: for (j=1;j<=n;j++) {
1.181 brouard 1930: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1931: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1932: }
1.181 brouard 1933: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1934: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1935:
1.126 brouard 1936: #ifdef DEBUG
1.164 brouard 1937: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1938: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1939: for(j=1;j<=n;j++){
1940: printf(" %.12e",xit[j]);
1941: fprintf(ficlog," %.12e",xit[j]);
1942: }
1943: printf("\n");
1944: fprintf(ficlog,"\n");
1945: #endif
1.192 brouard 1946: } /* end of t or directest negative */
1947: #ifdef POWELLF1F3
1948: #else
1.162 brouard 1949: } /* end if (fptt < fp) */
1.192 brouard 1950: #endif
1951: } /* loop iteration */
1.126 brouard 1952: }
1953:
1954: /**** Prevalence limit (stable or period prevalence) ****************/
1955:
1.203 brouard 1956: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126 brouard 1957: {
1958: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203 brouard 1959: matrix by transitions matrix until convergence is reached with precision ftolpl */
1.169 brouard 1960:
1.126 brouard 1961: int i, ii,j,k;
1962: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1963: /* double **matprod2(); */ /* test */
1.131 brouard 1964: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1965: double **newm;
1.202 brouard 1966: double agefin, delaymax=100 ; /* Max number of years to converge */
1.203 brouard 1967: int ncvloop=0;
1.169 brouard 1968:
1.126 brouard 1969: for (ii=1;ii<=nlstate+ndeath;ii++)
1970: for (j=1;j<=nlstate+ndeath;j++){
1971: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1972: }
1.169 brouard 1973:
1974: cov[1]=1.;
1975:
1976: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202 brouard 1977: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126 brouard 1978: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202 brouard 1979: ncvloop++;
1.126 brouard 1980: newm=savm;
1981: /* Covariates have to be included here again */
1.138 brouard 1982: cov[2]=agefin;
1.187 brouard 1983: if(nagesqr==1)
1984: cov[3]= agefin*agefin;;
1.138 brouard 1985: for (k=1; k<=cptcovn;k++) {
1.200 brouard 1986: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1987: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198 brouard 1988: /* 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])]); */
1.138 brouard 1989: }
1.186 brouard 1990: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 1991: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
1992: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186 brouard 1993: for (k=1; k<=cptcovprod;k++) /* Useless */
1.200 brouard 1994: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1995: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138 brouard 1996:
1997: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1998: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1999: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 2000: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2001: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 2002: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 2003:
1.126 brouard 2004: savm=oldm;
2005: oldm=newm;
2006: maxmax=0.;
2007: for(j=1;j<=nlstate;j++){
2008: min=1.;
2009: max=0.;
2010: for(i=1; i<=nlstate; i++) {
2011: sumnew=0;
2012: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2013: prlim[i][j]= newm[i][j]/(1-sumnew);
2014: max=FMAX(max,prlim[i][j]);
2015: min=FMIN(min,prlim[i][j]);
1.202 brouard 2016: /* printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min); */
1.126 brouard 2017: }
1.203 brouard 2018: maxmin=(max-min)/(max+min)*2;
1.126 brouard 2019: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 2020: } /* j loop */
1.203 brouard 2021: *ncvyear= (int)age- (int)agefin;
2022: /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126 brouard 2023: if(maxmax < ftolpl){
1.203 brouard 2024: /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126 brouard 2025: return prlim;
2026: }
1.169 brouard 2027: } /* age loop */
1.203 brouard 2028: printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g. \n\
2029: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
2030: /* 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); */
1.169 brouard 2031: return prlim; /* should not reach here */
1.126 brouard 2032: }
2033:
2034: /*************** transition probabilities ***************/
2035:
2036: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2037: {
1.138 brouard 2038: /* According to parameters values stored in x and the covariate's values stored in cov,
2039: computes the probability to be observed in state j being in state i by appying the
2040: model to the ncovmodel covariates (including constant and age).
2041: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2042: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2043: ncth covariate in the global vector x is given by the formula:
2044: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2045: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2046: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2047: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2048: Outputs ps[i][j] the probability to be observed in j being in j according to
2049: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2050: */
2051: double s1, lnpijopii;
1.126 brouard 2052: /*double t34;*/
1.164 brouard 2053: int i,j, nc, ii, jj;
1.126 brouard 2054:
2055: for(i=1; i<= nlstate; i++){
2056: for(j=1; j<i;j++){
1.138 brouard 2057: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2058: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2059: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2060: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2061: }
1.138 brouard 2062: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2063: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2064: }
2065: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 2066: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2067: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2068: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2069: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 2070: }
1.138 brouard 2071: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 2072: }
2073: }
2074:
2075: for(i=1; i<= nlstate; i++){
2076: s1=0;
1.131 brouard 2077: for(j=1; j<i; j++){
1.138 brouard 2078: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2079: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2080: }
2081: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 2082: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2083: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2084: }
1.138 brouard 2085: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 2086: ps[i][i]=1./(s1+1.);
1.138 brouard 2087: /* Computing other pijs */
1.126 brouard 2088: for(j=1; j<i; j++)
2089: ps[i][j]= exp(ps[i][j])*ps[i][i];
2090: for(j=i+1; j<=nlstate+ndeath; j++)
2091: ps[i][j]= exp(ps[i][j])*ps[i][i];
2092: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2093: } /* end i */
2094:
2095: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2096: for(jj=1; jj<= nlstate+ndeath; jj++){
2097: ps[ii][jj]=0;
2098: ps[ii][ii]=1;
2099: }
2100: }
2101:
1.145 brouard 2102:
2103: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2104: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2105: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2106: /* } */
2107: /* printf("\n "); */
2108: /* } */
2109: /* printf("\n ");printf("%lf ",cov[2]);*/
2110: /*
1.126 brouard 2111: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2112: goto end;*/
2113: return ps;
2114: }
2115:
2116: /**************** Product of 2 matrices ******************/
2117:
1.145 brouard 2118: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2119: {
2120: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2121: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2122: /* in, b, out are matrice of pointers which should have been initialized
2123: before: only the contents of out is modified. The function returns
2124: a pointer to pointers identical to out */
1.145 brouard 2125: int i, j, k;
1.126 brouard 2126: for(i=nrl; i<= nrh; i++)
1.145 brouard 2127: for(k=ncolol; k<=ncoloh; k++){
2128: out[i][k]=0.;
2129: for(j=ncl; j<=nch; j++)
2130: out[i][k] +=in[i][j]*b[j][k];
2131: }
1.126 brouard 2132: return out;
2133: }
2134:
2135:
2136: /************* Higher Matrix Product ***************/
2137:
2138: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2139: {
2140: /* Computes the transition matrix starting at age 'age' over
2141: 'nhstepm*hstepm*stepm' months (i.e. until
2142: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2143: nhstepm*hstepm matrices.
2144: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2145: (typically every 2 years instead of every month which is too big
2146: for the memory).
2147: Model is determined by parameters x and covariates have to be
2148: included manually here.
2149:
2150: */
2151:
2152: int i, j, d, h, k;
1.131 brouard 2153: double **out, cov[NCOVMAX+1];
1.126 brouard 2154: double **newm;
1.187 brouard 2155: double agexact;
1.126 brouard 2156:
2157: /* Hstepm could be zero and should return the unit matrix */
2158: for (i=1;i<=nlstate+ndeath;i++)
2159: for (j=1;j<=nlstate+ndeath;j++){
2160: oldm[i][j]=(i==j ? 1.0 : 0.0);
2161: po[i][j][0]=(i==j ? 1.0 : 0.0);
2162: }
2163: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2164: for(h=1; h <=nhstepm; h++){
2165: for(d=1; d <=hstepm; d++){
2166: newm=savm;
2167: /* Covariates have to be included here again */
2168: cov[1]=1.;
1.187 brouard 2169: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2170: cov[2]=agexact;
2171: if(nagesqr==1)
2172: cov[3]= agexact*agexact;
1.131 brouard 2173: for (k=1; k<=cptcovn;k++)
1.200 brouard 2174: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2175: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186 brouard 2176: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2177: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 2178: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2179: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145 brouard 2180: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200 brouard 2181: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2182: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126 brouard 2183:
2184:
2185: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2186: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2187: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2188: pmij(pmmij,cov,ncovmodel,x,nlstate));
2189: savm=oldm;
2190: oldm=newm;
2191: }
2192: for(i=1; i<=nlstate+ndeath; i++)
2193: for(j=1;j<=nlstate+ndeath;j++) {
2194: po[i][j][h]=newm[i][j];
1.128 brouard 2195: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2196: }
1.128 brouard 2197: /*printf("h=%d ",h);*/
1.126 brouard 2198: } /* end h */
1.128 brouard 2199: /* printf("\n H=%d \n",h); */
1.126 brouard 2200: return po;
2201: }
2202:
1.162 brouard 2203: #ifdef NLOPT
2204: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2205: double fret;
2206: double *xt;
2207: int j;
2208: myfunc_data *d2 = (myfunc_data *) pd;
2209: /* xt = (p1-1); */
2210: xt=vector(1,n);
2211: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2212:
2213: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2214: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2215: printf("Function = %.12lf ",fret);
2216: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2217: printf("\n");
2218: free_vector(xt,1,n);
2219: return fret;
2220: }
2221: #endif
1.126 brouard 2222:
2223: /*************** log-likelihood *************/
2224: double func( double *x)
2225: {
2226: int i, ii, j, k, mi, d, kk;
1.131 brouard 2227: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2228: double **out;
2229: double sw; /* Sum of weights */
2230: double lli; /* Individual log likelihood */
2231: int s1, s2;
2232: double bbh, survp;
2233: long ipmx;
1.187 brouard 2234: double agexact;
1.126 brouard 2235: /*extern weight */
2236: /* We are differentiating ll according to initial status */
2237: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2238: /*for(i=1;i<imx;i++)
2239: printf(" %d\n",s[4][i]);
2240: */
1.162 brouard 2241:
2242: ++countcallfunc;
2243:
1.126 brouard 2244: cov[1]=1.;
2245:
2246: for(k=1; k<=nlstate; k++) ll[k]=0.;
2247:
2248: if(mle==1){
2249: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2250: /* Computes the values of the ncovmodel covariates of the model
2251: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2252: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2253: to be observed in j being in i according to the model.
2254: */
1.145 brouard 2255: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2256: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2257: }
1.137 brouard 2258: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2259: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2260: has been calculated etc */
1.126 brouard 2261: for(mi=1; mi<= wav[i]-1; mi++){
2262: for (ii=1;ii<=nlstate+ndeath;ii++)
2263: for (j=1;j<=nlstate+ndeath;j++){
2264: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2265: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2266: }
2267: for(d=0; d<dh[mi][i]; d++){
2268: newm=savm;
1.187 brouard 2269: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2270: cov[2]=agexact;
2271: if(nagesqr==1)
2272: cov[3]= agexact*agexact;
1.126 brouard 2273: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2274: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2275: }
2276: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2277: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2278: savm=oldm;
2279: oldm=newm;
2280: } /* end mult */
2281:
2282: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2283: /* But now since version 0.9 we anticipate for bias at large stepm.
2284: * If stepm is larger than one month (smallest stepm) and if the exact delay
2285: * (in months) between two waves is not a multiple of stepm, we rounded to
2286: * the nearest (and in case of equal distance, to the lowest) interval but now
2287: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2288: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2289: * probability in order to take into account the bias as a fraction of the way
2290: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2291: * -stepm/2 to stepm/2 .
2292: * For stepm=1 the results are the same as for previous versions of Imach.
2293: * For stepm > 1 the results are less biased than in previous versions.
2294: */
2295: s1=s[mw[mi][i]][i];
2296: s2=s[mw[mi+1][i]][i];
2297: bbh=(double)bh[mi][i]/(double)stepm;
2298: /* bias bh is positive if real duration
2299: * is higher than the multiple of stepm and negative otherwise.
2300: */
2301: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2302: if( s2 > nlstate){
2303: /* i.e. if s2 is a death state and if the date of death is known
2304: then the contribution to the likelihood is the probability to
2305: die between last step unit time and current step unit time,
2306: which is also equal to probability to die before dh
2307: minus probability to die before dh-stepm .
2308: In version up to 0.92 likelihood was computed
2309: as if date of death was unknown. Death was treated as any other
2310: health state: the date of the interview describes the actual state
2311: and not the date of a change in health state. The former idea was
2312: to consider that at each interview the state was recorded
2313: (healthy, disable or death) and IMaCh was corrected; but when we
2314: introduced the exact date of death then we should have modified
2315: the contribution of an exact death to the likelihood. This new
2316: contribution is smaller and very dependent of the step unit
2317: stepm. It is no more the probability to die between last interview
2318: and month of death but the probability to survive from last
2319: interview up to one month before death multiplied by the
2320: probability to die within a month. Thanks to Chris
2321: Jackson for correcting this bug. Former versions increased
2322: mortality artificially. The bad side is that we add another loop
2323: which slows down the processing. The difference can be up to 10%
2324: lower mortality.
2325: */
1.183 brouard 2326: /* If, at the beginning of the maximization mostly, the
2327: cumulative probability or probability to be dead is
2328: constant (ie = 1) over time d, the difference is equal to
2329: 0. out[s1][3] = savm[s1][3]: probability, being at state
2330: s1 at precedent wave, to be dead a month before current
2331: wave is equal to probability, being at state s1 at
2332: precedent wave, to be dead at mont of the current
2333: wave. Then the observed probability (that this person died)
2334: is null according to current estimated parameter. In fact,
2335: it should be very low but not zero otherwise the log go to
2336: infinity.
2337: */
2338: /* #ifdef INFINITYORIGINAL */
2339: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2340: /* #else */
2341: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2342: /* lli=log(mytinydouble); */
2343: /* else */
2344: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2345: /* #endif */
2346: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2347:
2348: } else if (s2==-2) {
2349: for (j=1,survp=0. ; j<=nlstate; j++)
2350: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2351: /*survp += out[s1][j]; */
2352: lli= log(survp);
2353: }
2354:
2355: else if (s2==-4) {
2356: for (j=3,survp=0. ; j<=nlstate; j++)
2357: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2358: lli= log(survp);
2359: }
2360:
2361: else if (s2==-5) {
2362: for (j=1,survp=0. ; j<=2; j++)
2363: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2364: lli= log(survp);
2365: }
2366:
2367: else{
2368: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2369: /* 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 */
2370: }
2371: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2372: /*if(lli ==000.0)*/
2373: /*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); */
2374: ipmx +=1;
2375: sw += weight[i];
2376: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2377: /* if (lli < log(mytinydouble)){ */
2378: /* 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); */
2379: /* 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]); */
2380: /* } */
1.126 brouard 2381: } /* end of wave */
2382: } /* end of individual */
2383: } else if(mle==2){
2384: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2385: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2386: for(mi=1; mi<= wav[i]-1; mi++){
2387: for (ii=1;ii<=nlstate+ndeath;ii++)
2388: for (j=1;j<=nlstate+ndeath;j++){
2389: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2390: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2391: }
2392: for(d=0; d<=dh[mi][i]; d++){
2393: newm=savm;
1.187 brouard 2394: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2395: cov[2]=agexact;
2396: if(nagesqr==1)
2397: cov[3]= agexact*agexact;
1.126 brouard 2398: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2399: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2400: }
2401: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2402: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2403: savm=oldm;
2404: oldm=newm;
2405: } /* end mult */
2406:
2407: s1=s[mw[mi][i]][i];
2408: s2=s[mw[mi+1][i]][i];
2409: bbh=(double)bh[mi][i]/(double)stepm;
2410: 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 */
2411: ipmx +=1;
2412: sw += weight[i];
2413: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2414: } /* end of wave */
2415: } /* end of individual */
2416: } else if(mle==3){ /* exponential inter-extrapolation */
2417: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2418: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2419: for(mi=1; mi<= wav[i]-1; mi++){
2420: for (ii=1;ii<=nlstate+ndeath;ii++)
2421: for (j=1;j<=nlstate+ndeath;j++){
2422: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2423: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2424: }
2425: for(d=0; d<dh[mi][i]; d++){
2426: newm=savm;
1.187 brouard 2427: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2428: cov[2]=agexact;
2429: if(nagesqr==1)
2430: cov[3]= agexact*agexact;
1.126 brouard 2431: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2432: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2433: }
2434: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2435: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2436: savm=oldm;
2437: oldm=newm;
2438: } /* end mult */
2439:
2440: s1=s[mw[mi][i]][i];
2441: s2=s[mw[mi+1][i]][i];
2442: bbh=(double)bh[mi][i]/(double)stepm;
2443: 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 */
2444: ipmx +=1;
2445: sw += weight[i];
2446: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2447: } /* end of wave */
2448: } /* end of individual */
2449: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2450: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2451: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2452: for(mi=1; mi<= wav[i]-1; mi++){
2453: for (ii=1;ii<=nlstate+ndeath;ii++)
2454: for (j=1;j<=nlstate+ndeath;j++){
2455: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2456: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2457: }
2458: for(d=0; d<dh[mi][i]; d++){
2459: newm=savm;
1.187 brouard 2460: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2461: cov[2]=agexact;
2462: if(nagesqr==1)
2463: cov[3]= agexact*agexact;
1.126 brouard 2464: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2465: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2466: }
2467:
2468: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2469: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2470: savm=oldm;
2471: oldm=newm;
2472: } /* end mult */
2473:
2474: s1=s[mw[mi][i]][i];
2475: s2=s[mw[mi+1][i]][i];
2476: if( s2 > nlstate){
2477: lli=log(out[s1][s2] - savm[s1][s2]);
2478: }else{
2479: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2480: }
2481: ipmx +=1;
2482: sw += weight[i];
2483: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2484: /* 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]); */
2485: } /* end of wave */
2486: } /* end of individual */
2487: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2488: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2489: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2490: for(mi=1; mi<= wav[i]-1; mi++){
2491: for (ii=1;ii<=nlstate+ndeath;ii++)
2492: for (j=1;j<=nlstate+ndeath;j++){
2493: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2494: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2495: }
2496: for(d=0; d<dh[mi][i]; d++){
2497: newm=savm;
1.187 brouard 2498: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2499: cov[2]=agexact;
2500: if(nagesqr==1)
2501: cov[3]= agexact*agexact;
1.126 brouard 2502: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2503: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2504: }
2505:
2506: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2507: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2508: savm=oldm;
2509: oldm=newm;
2510: } /* end mult */
2511:
2512: s1=s[mw[mi][i]][i];
2513: s2=s[mw[mi+1][i]][i];
2514: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2515: ipmx +=1;
2516: sw += weight[i];
2517: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2518: /*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]);*/
2519: } /* end of wave */
2520: } /* end of individual */
2521: } /* End of if */
2522: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2523: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2524: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2525: return -l;
2526: }
2527:
2528: /*************** log-likelihood *************/
2529: double funcone( double *x)
2530: {
2531: /* Same as likeli but slower because of a lot of printf and if */
2532: int i, ii, j, k, mi, d, kk;
1.131 brouard 2533: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2534: double **out;
2535: double lli; /* Individual log likelihood */
2536: double llt;
2537: int s1, s2;
2538: double bbh, survp;
1.187 brouard 2539: double agexact;
1.126 brouard 2540: /*extern weight */
2541: /* We are differentiating ll according to initial status */
2542: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2543: /*for(i=1;i<imx;i++)
2544: printf(" %d\n",s[4][i]);
2545: */
2546: cov[1]=1.;
2547:
2548: for(k=1; k<=nlstate; k++) ll[k]=0.;
2549:
2550: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2551: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2552: for(mi=1; mi<= wav[i]-1; mi++){
2553: for (ii=1;ii<=nlstate+ndeath;ii++)
2554: for (j=1;j<=nlstate+ndeath;j++){
2555: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2556: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2557: }
2558: for(d=0; d<dh[mi][i]; d++){
2559: newm=savm;
1.187 brouard 2560: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2561: cov[2]=agexact;
2562: if(nagesqr==1)
2563: cov[3]= agexact*agexact;
1.126 brouard 2564: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2565: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2566: }
1.187 brouard 2567:
1.145 brouard 2568: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2569: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2570: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2571: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2572: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2573: savm=oldm;
2574: oldm=newm;
2575: } /* end mult */
2576:
2577: s1=s[mw[mi][i]][i];
2578: s2=s[mw[mi+1][i]][i];
2579: bbh=(double)bh[mi][i]/(double)stepm;
2580: /* bias is positive if real duration
2581: * is higher than the multiple of stepm and negative otherwise.
2582: */
2583: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2584: lli=log(out[s1][s2] - savm[s1][s2]);
2585: } else if (s2==-2) {
2586: for (j=1,survp=0. ; j<=nlstate; j++)
2587: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2588: lli= log(survp);
2589: }else if (mle==1){
2590: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2591: } else if(mle==2){
2592: 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 */
2593: } else if(mle==3){ /* exponential inter-extrapolation */
2594: 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 */
2595: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2596: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2597: } else{ /* mle=0 back to 1 */
2598: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2599: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2600: } /* End of if */
2601: ipmx +=1;
2602: sw += weight[i];
2603: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2604: /*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]); */
1.126 brouard 2605: if(globpr){
1.205 ! brouard 2606: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126 brouard 2607: %11.6f %11.6f %11.6f ", \
1.205 ! brouard 2608: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126 brouard 2609: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2610: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2611: llt +=ll[k]*gipmx/gsw;
2612: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2613: }
2614: fprintf(ficresilk," %10.6f\n", -llt);
2615: }
2616: } /* end of wave */
2617: } /* end of individual */
2618: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2619: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2620: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2621: if(globpr==0){ /* First time we count the contributions and weights */
2622: gipmx=ipmx;
2623: gsw=sw;
2624: }
2625: return -l;
2626: }
2627:
2628:
2629: /*************** function likelione ***********/
2630: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2631: {
2632: /* This routine should help understanding what is done with
2633: the selection of individuals/waves and
2634: to check the exact contribution to the likelihood.
2635: Plotting could be done.
2636: */
2637: int k;
2638:
2639: if(*globpri !=0){ /* Just counts and sums, no printings */
1.201 brouard 2640: strcpy(fileresilk,"ILK_");
1.202 brouard 2641: strcat(fileresilk,fileresu);
1.126 brouard 2642: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2643: printf("Problem with resultfile: %s\n", fileresilk);
2644: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2645: }
1.205 ! brouard 2646: fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
! 2647: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %weight 2wlli out sav ");
1.126 brouard 2648: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2649: for(k=1; k<=nlstate; k++)
2650: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2651: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2652: }
2653:
2654: *fretone=(*funcone)(p);
2655: if(*globpri !=0){
2656: fclose(ficresilk);
1.205 ! brouard 2657: if (mle ==0)
! 2658: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
! 2659: else if(mle >=1)
! 2660: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
! 2661: 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));
! 2662:
! 2663: 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> \
1.204 brouard 2664: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.205 ! brouard 2665: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204 brouard 2666: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.205 ! brouard 2667: fflush(fichtm);
! 2668:
! 2669: for (k=1; k<= nlstate ; k++) {
! 2670: fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.204 brouard 2671: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
1.205 ! brouard 2672: }
! 2673: }
1.126 brouard 2674: return;
2675: }
2676:
2677:
2678: /*********** Maximum Likelihood Estimation ***************/
2679:
2680: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2681: {
1.165 brouard 2682: int i,j, iter=0;
1.126 brouard 2683: double **xi;
2684: double fret;
2685: double fretone; /* Only one call to likelihood */
2686: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2687:
2688: #ifdef NLOPT
2689: int creturn;
2690: nlopt_opt opt;
2691: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2692: double *lb;
2693: double minf; /* the minimum objective value, upon return */
2694: double * p1; /* Shifted parameters from 0 instead of 1 */
2695: myfunc_data dinst, *d = &dinst;
2696: #endif
2697:
2698:
1.126 brouard 2699: xi=matrix(1,npar,1,npar);
2700: for (i=1;i<=npar;i++)
2701: for (j=1;j<=npar;j++)
2702: xi[i][j]=(i==j ? 1.0 : 0.0);
2703: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.201 brouard 2704: strcpy(filerespow,"POW_");
1.126 brouard 2705: strcat(filerespow,fileres);
2706: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2707: printf("Problem with resultfile: %s\n", filerespow);
2708: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2709: }
2710: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2711: for (i=1;i<=nlstate;i++)
2712: for(j=1;j<=nlstate+ndeath;j++)
2713: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2714: fprintf(ficrespow,"\n");
1.162 brouard 2715: #ifdef POWELL
1.126 brouard 2716: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2717: #endif
1.126 brouard 2718:
1.162 brouard 2719: #ifdef NLOPT
2720: #ifdef NEWUOA
2721: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2722: #else
2723: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2724: #endif
2725: lb=vector(0,npar-1);
2726: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2727: nlopt_set_lower_bounds(opt, lb);
2728: nlopt_set_initial_step1(opt, 0.1);
2729:
2730: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2731: d->function = func;
2732: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2733: nlopt_set_min_objective(opt, myfunc, d);
2734: nlopt_set_xtol_rel(opt, ftol);
2735: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2736: printf("nlopt failed! %d\n",creturn);
2737: }
2738: else {
2739: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2740: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2741: iter=1; /* not equal */
2742: }
2743: nlopt_destroy(opt);
2744: #endif
1.126 brouard 2745: free_matrix(xi,1,npar,1,npar);
2746: fclose(ficrespow);
1.203 brouard 2747: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2748: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180 brouard 2749: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2750:
2751: }
2752:
2753: /**** Computes Hessian and covariance matrix ***/
1.203 brouard 2754: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126 brouard 2755: {
2756: double **a,**y,*x,pd;
1.203 brouard 2757: /* double **hess; */
1.164 brouard 2758: int i, j;
1.126 brouard 2759: int *indx;
2760:
2761: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203 brouard 2762: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126 brouard 2763: void lubksb(double **a, int npar, int *indx, double b[]) ;
2764: void ludcmp(double **a, int npar, int *indx, double *d) ;
2765: double gompertz(double p[]);
1.203 brouard 2766: /* hess=matrix(1,npar,1,npar); */
1.126 brouard 2767:
2768: printf("\nCalculation of the hessian matrix. Wait...\n");
2769: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2770: for (i=1;i<=npar;i++){
1.203 brouard 2771: printf("%d-",i);fflush(stdout);
2772: fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126 brouard 2773:
2774: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2775:
2776: /* printf(" %f ",p[i]);
2777: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2778: }
2779:
2780: for (i=1;i<=npar;i++) {
2781: for (j=1;j<=npar;j++) {
2782: if (j>i) {
1.203 brouard 2783: printf(".%d-%d",i,j);fflush(stdout);
2784: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2785: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126 brouard 2786:
2787: hess[j][i]=hess[i][j];
2788: /*printf(" %lf ",hess[i][j]);*/
2789: }
2790: }
2791: }
2792: printf("\n");
2793: fprintf(ficlog,"\n");
2794:
2795: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2796: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2797:
2798: a=matrix(1,npar,1,npar);
2799: y=matrix(1,npar,1,npar);
2800: x=vector(1,npar);
2801: indx=ivector(1,npar);
2802: for (i=1;i<=npar;i++)
2803: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2804: ludcmp(a,npar,indx,&pd);
2805:
2806: for (j=1;j<=npar;j++) {
2807: for (i=1;i<=npar;i++) x[i]=0;
2808: x[j]=1;
2809: lubksb(a,npar,indx,x);
2810: for (i=1;i<=npar;i++){
2811: matcov[i][j]=x[i];
2812: }
2813: }
2814:
2815: printf("\n#Hessian matrix#\n");
2816: fprintf(ficlog,"\n#Hessian matrix#\n");
2817: for (i=1;i<=npar;i++) {
2818: for (j=1;j<=npar;j++) {
1.203 brouard 2819: printf("%.6e ",hess[i][j]);
2820: fprintf(ficlog,"%.6e ",hess[i][j]);
1.126 brouard 2821: }
2822: printf("\n");
2823: fprintf(ficlog,"\n");
2824: }
2825:
1.203 brouard 2826: /* printf("\n#Covariance matrix#\n"); */
2827: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2828: /* for (i=1;i<=npar;i++) { */
2829: /* for (j=1;j<=npar;j++) { */
2830: /* printf("%.6e ",matcov[i][j]); */
2831: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2832: /* } */
2833: /* printf("\n"); */
2834: /* fprintf(ficlog,"\n"); */
2835: /* } */
2836:
1.126 brouard 2837: /* Recompute Inverse */
1.203 brouard 2838: /* for (i=1;i<=npar;i++) */
2839: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2840: /* ludcmp(a,npar,indx,&pd); */
2841:
2842: /* printf("\n#Hessian matrix recomputed#\n"); */
2843:
2844: /* for (j=1;j<=npar;j++) { */
2845: /* for (i=1;i<=npar;i++) x[i]=0; */
2846: /* x[j]=1; */
2847: /* lubksb(a,npar,indx,x); */
2848: /* for (i=1;i<=npar;i++){ */
2849: /* y[i][j]=x[i]; */
2850: /* printf("%.3e ",y[i][j]); */
2851: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2852: /* } */
2853: /* printf("\n"); */
2854: /* fprintf(ficlog,"\n"); */
2855: /* } */
2856:
2857: /* Verifying the inverse matrix */
2858: #ifdef DEBUGHESS
2859: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126 brouard 2860:
1.203 brouard 2861: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2862: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126 brouard 2863:
2864: for (j=1;j<=npar;j++) {
2865: for (i=1;i<=npar;i++){
1.203 brouard 2866: printf("%.2f ",y[i][j]);
2867: fprintf(ficlog,"%.2f ",y[i][j]);
1.126 brouard 2868: }
2869: printf("\n");
2870: fprintf(ficlog,"\n");
2871: }
1.203 brouard 2872: #endif
1.126 brouard 2873:
2874: free_matrix(a,1,npar,1,npar);
2875: free_matrix(y,1,npar,1,npar);
2876: free_vector(x,1,npar);
2877: free_ivector(indx,1,npar);
1.203 brouard 2878: /* free_matrix(hess,1,npar,1,npar); */
1.126 brouard 2879:
2880:
2881: }
2882:
2883: /*************** hessian matrix ****************/
2884: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203 brouard 2885: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126 brouard 2886: int i;
2887: int l=1, lmax=20;
1.203 brouard 2888: double k1,k2, res, fx;
1.132 brouard 2889: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2890: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2891: int k=0,kmax=10;
2892: double l1;
2893:
2894: fx=func(x);
2895: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2896: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2897: l1=pow(10,l);
2898: delts=delt;
2899: for(k=1 ; k <kmax; k=k+1){
2900: delt = delta*(l1*k);
2901: p2[theta]=x[theta] +delt;
1.145 brouard 2902: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2903: p2[theta]=x[theta]-delt;
2904: k2=func(p2)-fx;
2905: /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203 brouard 2906: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126 brouard 2907:
1.203 brouard 2908: #ifdef DEBUGHESSII
1.126 brouard 2909: 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);
2910: 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);
2911: #endif
2912: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2913: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2914: k=kmax;
2915: }
2916: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2917: k=kmax; l=lmax*10;
1.126 brouard 2918: }
2919: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2920: delts=delt;
2921: }
1.203 brouard 2922: } /* End loop k */
1.126 brouard 2923: }
2924: delti[theta]=delts;
2925: return res;
2926:
2927: }
2928:
1.203 brouard 2929: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126 brouard 2930: {
2931: int i;
1.164 brouard 2932: int l=1, lmax=20;
1.126 brouard 2933: double k1,k2,k3,k4,res,fx;
1.132 brouard 2934: double p2[MAXPARM+1];
1.203 brouard 2935: int k, kmax=1;
2936: double v1, v2, cv12, lc1, lc2;
2937:
1.126 brouard 2938: fx=func(x);
1.203 brouard 2939: for (k=1; k<=kmax; k=k+10) {
1.126 brouard 2940: for (i=1;i<=npar;i++) p2[i]=x[i];
1.203 brouard 2941: p2[thetai]=x[thetai]+delti[thetai]*k;
2942: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 2943: k1=func(p2)-fx;
2944:
1.203 brouard 2945: p2[thetai]=x[thetai]+delti[thetai]*k;
2946: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 2947: k2=func(p2)-fx;
2948:
1.203 brouard 2949: p2[thetai]=x[thetai]-delti[thetai]*k;
2950: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 2951: k3=func(p2)-fx;
2952:
1.203 brouard 2953: p2[thetai]=x[thetai]-delti[thetai]*k;
2954: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 2955: k4=func(p2)-fx;
1.203 brouard 2956: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
2957: if(k1*k2*k3*k4 <0.){
2958: kmax=kmax+10;
2959: if(kmax >=10){
2960: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
2961: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
2962: 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);
2963: 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);
2964: }
2965: }
2966: #ifdef DEBUGHESSIJ
2967: v1=hess[thetai][thetai];
2968: v2=hess[thetaj][thetaj];
2969: cv12=res;
2970: /* Computing eigen value of Hessian matrix */
2971: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
2972: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
2973: if ((lc2 <0) || (lc1 <0) ){
2974: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
2975: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
2976: 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);
2977: 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);
2978: }
1.126 brouard 2979: #endif
2980: }
2981: return res;
2982: }
2983:
1.203 brouard 2984: /* Not done yet: Was supposed to fix if not exactly at the maximum */
2985: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
2986: /* { */
2987: /* int i; */
2988: /* int l=1, lmax=20; */
2989: /* double k1,k2,k3,k4,res,fx; */
2990: /* double p2[MAXPARM+1]; */
2991: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
2992: /* int k=0,kmax=10; */
2993: /* double l1; */
2994:
2995: /* fx=func(x); */
2996: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
2997: /* l1=pow(10,l); */
2998: /* delts=delt; */
2999: /* for(k=1 ; k <kmax; k=k+1){ */
3000: /* delt = delti*(l1*k); */
3001: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3002: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3003: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3004: /* k1=func(p2)-fx; */
3005:
3006: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3007: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3008: /* k2=func(p2)-fx; */
3009:
3010: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3011: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3012: /* k3=func(p2)-fx; */
3013:
3014: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3015: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3016: /* k4=func(p2)-fx; */
3017: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3018: /* #ifdef DEBUGHESSIJ */
3019: /* 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); */
3020: /* 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); */
3021: /* #endif */
3022: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3023: /* k=kmax; */
3024: /* } */
3025: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3026: /* k=kmax; l=lmax*10; */
3027: /* } */
3028: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3029: /* delts=delt; */
3030: /* } */
3031: /* } /\* End loop k *\/ */
3032: /* } */
3033: /* delti[theta]=delts; */
3034: /* return res; */
3035: /* } */
3036:
3037:
1.126 brouard 3038: /************** Inverse of matrix **************/
3039: void ludcmp(double **a, int n, int *indx, double *d)
3040: {
3041: int i,imax,j,k;
3042: double big,dum,sum,temp;
3043: double *vv;
3044:
3045: vv=vector(1,n);
3046: *d=1.0;
3047: for (i=1;i<=n;i++) {
3048: big=0.0;
3049: for (j=1;j<=n;j++)
3050: if ((temp=fabs(a[i][j])) > big) big=temp;
3051: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3052: vv[i]=1.0/big;
3053: }
3054: for (j=1;j<=n;j++) {
3055: for (i=1;i<j;i++) {
3056: sum=a[i][j];
3057: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3058: a[i][j]=sum;
3059: }
3060: big=0.0;
3061: for (i=j;i<=n;i++) {
3062: sum=a[i][j];
3063: for (k=1;k<j;k++)
3064: sum -= a[i][k]*a[k][j];
3065: a[i][j]=sum;
3066: if ( (dum=vv[i]*fabs(sum)) >= big) {
3067: big=dum;
3068: imax=i;
3069: }
3070: }
3071: if (j != imax) {
3072: for (k=1;k<=n;k++) {
3073: dum=a[imax][k];
3074: a[imax][k]=a[j][k];
3075: a[j][k]=dum;
3076: }
3077: *d = -(*d);
3078: vv[imax]=vv[j];
3079: }
3080: indx[j]=imax;
3081: if (a[j][j] == 0.0) a[j][j]=TINY;
3082: if (j != n) {
3083: dum=1.0/(a[j][j]);
3084: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3085: }
3086: }
3087: free_vector(vv,1,n); /* Doesn't work */
3088: ;
3089: }
3090:
3091: void lubksb(double **a, int n, int *indx, double b[])
3092: {
3093: int i,ii=0,ip,j;
3094: double sum;
3095:
3096: for (i=1;i<=n;i++) {
3097: ip=indx[i];
3098: sum=b[ip];
3099: b[ip]=b[i];
3100: if (ii)
3101: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3102: else if (sum) ii=i;
3103: b[i]=sum;
3104: }
3105: for (i=n;i>=1;i--) {
3106: sum=b[i];
3107: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3108: b[i]=sum/a[i][i];
3109: }
3110: }
3111:
3112: void pstamp(FILE *fichier)
3113: {
1.196 brouard 3114: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126 brouard 3115: }
3116:
3117: /************ Frequencies ********************/
3118: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
3119: { /* Some frequencies */
3120:
1.164 brouard 3121: int i, m, jk, j1, bool, z1,j;
1.126 brouard 3122: int first;
3123: double ***freq; /* Frequencies */
3124: double *pp, **prop;
3125: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3126: char fileresp[FILENAMELENGTH];
3127:
3128: pp=vector(1,nlstate);
3129: prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201 brouard 3130: strcpy(fileresp,"P_");
3131: strcat(fileresp,fileresu);
1.126 brouard 3132: if((ficresp=fopen(fileresp,"w"))==NULL) {
3133: printf("Problem with prevalence resultfile: %s\n", fileresp);
3134: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3135: exit(0);
3136: }
3137: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3138: j1=0;
3139:
3140: j=cptcoveff;
3141: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3142:
3143: first=1;
3144:
1.169 brouard 3145: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3146: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3147: /* j1++; */
1.145 brouard 3148: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 3149: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3150: scanf("%d", i);*/
3151: for (i=-5; i<=nlstate+ndeath; i++)
3152: for (jk=-5; jk<=nlstate+ndeath; jk++)
3153: for(m=iagemin; m <= iagemax+3; m++)
3154: freq[i][jk][m]=0;
1.143 brouard 3155:
3156: for (i=1; i<=nlstate; i++)
3157: for(m=iagemin; m <= iagemax+3; m++)
3158: prop[i][m]=0;
1.126 brouard 3159:
3160: dateintsum=0;
3161: k2cpt=0;
3162: for (i=1; i<=imx; i++) {
3163: bool=1;
1.144 brouard 3164: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3165: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3166: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145 brouard 3167: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 3168: bool=0;
1.198 brouard 3169: /* 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",
3170: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3171: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3172: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144 brouard 3173: }
1.126 brouard 3174: }
1.144 brouard 3175:
1.126 brouard 3176: if (bool==1){
3177: for(m=firstpass; m<=lastpass; m++){
3178: k2=anint[m][i]+(mint[m][i]/12.);
3179: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3180: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3181: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3182: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
3183: if (m<lastpass) {
3184: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3185: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3186: }
3187:
3188: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
3189: dateintsum=dateintsum+k2;
3190: k2cpt++;
3191: }
3192: /*}*/
3193: }
3194: }
1.145 brouard 3195: } /* end i */
1.126 brouard 3196:
3197: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3198: pstamp(ficresp);
3199: if (cptcovn>0) {
3200: fprintf(ficresp, "\n#********** Variable ");
1.198 brouard 3201: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 3202: fprintf(ficresp, "**********\n#");
1.143 brouard 3203: fprintf(ficlog, "\n#********** Variable ");
1.198 brouard 3204: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143 brouard 3205: fprintf(ficlog, "**********\n#");
1.126 brouard 3206: }
3207: for(i=1; i<=nlstate;i++)
3208: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3209: fprintf(ficresp, "\n");
3210:
3211: for(i=iagemin; i <= iagemax+3; i++){
3212: if(i==iagemax+3){
3213: fprintf(ficlog,"Total");
3214: }else{
3215: if(first==1){
3216: first=0;
3217: printf("See log file for details...\n");
3218: }
3219: fprintf(ficlog,"Age %d", i);
3220: }
3221: for(jk=1; jk <=nlstate ; jk++){
3222: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3223: pp[jk] += freq[jk][m][i];
3224: }
3225: for(jk=1; jk <=nlstate ; jk++){
3226: for(m=-1, pos=0; m <=0 ; m++)
3227: pos += freq[jk][m][i];
3228: if(pp[jk]>=1.e-10){
3229: if(first==1){
1.132 brouard 3230: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3231: }
3232: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3233: }else{
3234: if(first==1)
3235: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3236: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3237: }
3238: }
3239:
3240: for(jk=1; jk <=nlstate ; jk++){
3241: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3242: pp[jk] += freq[jk][m][i];
3243: }
3244: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3245: pos += pp[jk];
3246: posprop += prop[jk][i];
3247: }
3248: for(jk=1; jk <=nlstate ; jk++){
3249: if(pos>=1.e-5){
3250: if(first==1)
3251: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3252: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3253: }else{
3254: if(first==1)
3255: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3256: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3257: }
3258: if( i <= iagemax){
3259: if(pos>=1.e-5){
3260: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3261: /*probs[i][jk][j1]= pp[jk]/pos;*/
3262: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3263: }
3264: else
3265: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3266: }
3267: }
3268:
3269: for(jk=-1; jk <=nlstate+ndeath; jk++)
3270: for(m=-1; m <=nlstate+ndeath; m++)
3271: if(freq[jk][m][i] !=0 ) {
3272: if(first==1)
3273: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3274: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3275: }
3276: if(i <= iagemax)
3277: fprintf(ficresp,"\n");
3278: if(first==1)
3279: printf("Others in log...\n");
3280: fprintf(ficlog,"\n");
3281: }
1.145 brouard 3282: /*}*/
1.126 brouard 3283: }
3284: dateintmean=dateintsum/k2cpt;
3285:
3286: fclose(ficresp);
3287: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3288: free_vector(pp,1,nlstate);
3289: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3290: /* End of Freq */
3291: }
3292:
3293: /************ Prevalence ********************/
3294: 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)
3295: {
3296: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3297: in each health status at the date of interview (if between dateprev1 and dateprev2).
3298: We still use firstpass and lastpass as another selection.
3299: */
3300:
1.164 brouard 3301: int i, m, jk, j1, bool, z1,j;
3302:
3303: double **prop;
3304: double posprop;
1.126 brouard 3305: double y2; /* in fractional years */
3306: int iagemin, iagemax;
1.145 brouard 3307: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3308:
3309: iagemin= (int) agemin;
3310: iagemax= (int) agemax;
3311: /*pp=vector(1,nlstate);*/
3312: prop=matrix(1,nlstate,iagemin,iagemax+3);
3313: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3314: j1=0;
3315:
1.145 brouard 3316: /*j=cptcoveff;*/
1.126 brouard 3317: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3318:
1.145 brouard 3319: first=1;
3320: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3321: /*for(i1=1; i1<=ncodemax[k1];i1++){
3322: j1++;*/
1.126 brouard 3323:
3324: for (i=1; i<=nlstate; i++)
3325: for(m=iagemin; m <= iagemax+3; m++)
3326: prop[i][m]=0.0;
3327:
3328: for (i=1; i<=imx; i++) { /* Each individual */
3329: bool=1;
3330: if (cptcovn>0) {
3331: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3332: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
1.126 brouard 3333: bool=0;
3334: }
3335: if (bool==1) {
3336: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3337: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3338: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3339: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3340: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3341: if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);
3342: if (s[m][i]>0 && s[m][i]<=nlstate) {
3343: /*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]]);*/
3344: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3345: prop[s[m][i]][iagemax+3] += weight[i];
3346: }
3347: }
3348: } /* end selection of waves */
3349: }
3350: }
3351: for(i=iagemin; i <= iagemax+3; i++){
3352: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3353: posprop += prop[jk][i];
3354: }
1.145 brouard 3355:
1.126 brouard 3356: for(jk=1; jk <=nlstate ; jk++){
3357: if( i <= iagemax){
3358: if(posprop>=1.e-5){
3359: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3360: } else{
3361: if(first==1){
3362: first=0;
3363: 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]);
3364: }
3365: }
1.126 brouard 3366: }
3367: }/* end jk */
3368: }/* end i */
1.145 brouard 3369: /*} *//* end i1 */
3370: } /* end j1 */
1.126 brouard 3371:
3372: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3373: /*free_vector(pp,1,nlstate);*/
3374: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3375: } /* End of prevalence */
3376:
3377: /************* Waves Concatenation ***************/
3378:
3379: 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)
3380: {
3381: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3382: Death is a valid wave (if date is known).
3383: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3384: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3385: and mw[mi+1][i]. dh depends on stepm.
3386: */
3387:
3388: int i, mi, m;
3389: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3390: double sum=0., jmean=0.;*/
3391: int first;
3392: int j, k=0,jk, ju, jl;
3393: double sum=0.;
3394: first=0;
1.164 brouard 3395: jmin=100000;
1.126 brouard 3396: jmax=-1;
3397: jmean=0.;
3398: for(i=1; i<=imx; i++){
3399: mi=0;
3400: m=firstpass;
3401: while(s[m][i] <= nlstate){
3402: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3403: mw[++mi][i]=m;
3404: if(m >=lastpass)
3405: break;
3406: else
3407: m++;
3408: }/* end while */
3409: if (s[m][i] > nlstate){
3410: mi++; /* Death is another wave */
3411: /* if(mi==0) never been interviewed correctly before death */
3412: /* Only death is a correct wave */
3413: mw[mi][i]=m;
3414: }
3415:
3416: wav[i]=mi;
3417: if(mi==0){
3418: nbwarn++;
3419: if(first==0){
3420: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3421: first=1;
3422: }
3423: if(first==1){
3424: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3425: }
3426: } /* end mi==0 */
3427: } /* End individuals */
3428:
3429: for(i=1; i<=imx; i++){
3430: for(mi=1; mi<wav[i];mi++){
3431: if (stepm <=0)
3432: dh[mi][i]=1;
3433: else{
3434: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3435: if (agedc[i] < 2*AGESUP) {
3436: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3437: if(j==0) j=1; /* Survives at least one month after exam */
3438: else if(j<0){
3439: nberr++;
3440: 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]);
3441: j=1; /* Temporary Dangerous patch */
3442: 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);
3443: 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]);
3444: 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);
3445: }
3446: k=k+1;
3447: if (j >= jmax){
3448: jmax=j;
3449: ijmax=i;
3450: }
3451: if (j <= jmin){
3452: jmin=j;
3453: ijmin=i;
3454: }
3455: sum=sum+j;
3456: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3457: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3458: }
3459: }
3460: else{
3461: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3462: /* 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]); */
3463:
3464: k=k+1;
3465: if (j >= jmax) {
3466: jmax=j;
3467: ijmax=i;
3468: }
3469: else if (j <= jmin){
3470: jmin=j;
3471: ijmin=i;
3472: }
3473: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3474: /*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]);*/
3475: if(j<0){
3476: nberr++;
3477: 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]);
3478: 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]);
3479: }
3480: sum=sum+j;
3481: }
3482: jk= j/stepm;
3483: jl= j -jk*stepm;
3484: ju= j -(jk+1)*stepm;
3485: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3486: if(jl==0){
3487: dh[mi][i]=jk;
3488: bh[mi][i]=0;
3489: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3490: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3491: dh[mi][i]=jk+1;
3492: bh[mi][i]=ju;
3493: }
3494: }else{
3495: if(jl <= -ju){
3496: dh[mi][i]=jk;
3497: bh[mi][i]=jl; /* bias is positive if real duration
3498: * is higher than the multiple of stepm and negative otherwise.
3499: */
3500: }
3501: else{
3502: dh[mi][i]=jk+1;
3503: bh[mi][i]=ju;
3504: }
3505: if(dh[mi][i]==0){
3506: dh[mi][i]=1; /* At least one step */
3507: bh[mi][i]=ju; /* At least one step */
3508: /* 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);*/
3509: }
3510: } /* end if mle */
3511: }
3512: } /* end wave */
3513: }
3514: jmean=sum/k;
3515: 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);
1.141 brouard 3516: 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);
1.126 brouard 3517: }
3518:
3519: /*********** Tricode ****************************/
1.145 brouard 3520: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3521: {
1.144 brouard 3522: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3523: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
1.169 brouard 3524: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3525: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3526: * nbcode[Tvar[j]][1]=
1.144 brouard 3527: */
1.130 brouard 3528:
1.145 brouard 3529: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3530: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3531: int cptcode=0; /* Modality max of covariates j */
3532: int modmincovj=0; /* Modality min of covariates j */
3533:
3534:
1.126 brouard 3535: cptcoveff=0;
3536:
1.144 brouard 3537: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3538:
1.145 brouard 3539: /* Loop on covariates without age and products */
1.186 brouard 3540: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3541: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3542: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3543: modality of this covariate Vj*/
1.145 brouard 3544: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3545: * If product of Vn*Vm, still boolean *:
3546: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3547: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3548: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3549: modality of the nth covariate of individual i. */
1.145 brouard 3550: if (ij > modmaxcovj)
3551: modmaxcovj=ij;
3552: else if (ij < modmincovj)
3553: modmincovj=ij;
3554: if ((ij < -1) && (ij > NCOVMAX)){
3555: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3556: exit(1);
3557: }else
1.136 brouard 3558: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3559: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3560: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3561: /* getting the maximum value of the modality of the covariate
3562: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3563: female is 1, then modmaxcovj=1.*/
1.192 brouard 3564: } /* end for loop on individuals i */
1.145 brouard 3565: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3566: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145 brouard 3567: cptcode=modmaxcovj;
1.137 brouard 3568: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3569: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3570: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3571: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3572: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3573: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3574: if( k != -1){
3575: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3576: covariate for which somebody answered excluding
3577: undefined. Usually 2: 0 and 1. */
3578: }
3579: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3580: covariate for which somebody answered including
3581: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3582: }
3583: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3584: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3585: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3586:
1.136 brouard 3587: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3588: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3589: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145 brouard 3590: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3591: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3592: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3593: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3594: nbcode[Tvar[j]][ij]=k;
3595: nbcode[Tvar[j]][1]=0;
3596: nbcode[Tvar[j]][2]=1;
3597: nbcode[Tvar[j]][3]=2;
1.197 brouard 3598: To be continued (not working yet).
1.145 brouard 3599: */
1.197 brouard 3600: ij=0; /* ij is similar to i but can jump over null modalities */
3601: 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*/
3602: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192 brouard 3603: break;
3604: }
3605: ij++;
1.197 brouard 3606: 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.*/
1.192 brouard 3607: cptcode = ij; /* New max modality for covar j */
3608: } /* end of loop on modality i=-1 to 1 or more */
3609:
3610: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3611: /* /\*recode from 0 *\/ */
3612: /* k is a modality. If we have model=V1+V1*sex */
3613: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3614: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3615: /* } */
3616: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3617: /* if (ij > ncodemax[j]) { */
3618: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3619: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3620: /* break; */
3621: /* } */
3622: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3623: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3624:
1.145 brouard 3625: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3626:
1.187 brouard 3627: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3628: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3629: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3630: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3631: }
1.126 brouard 3632:
1.192 brouard 3633: ij=0;
1.145 brouard 3634: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3635: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3636: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3637: ij++;
1.145 brouard 3638: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3639: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3640: }else{
3641: /* Tvaraff[ij]=0; */
3642: }
1.126 brouard 3643: }
1.192 brouard 3644: /* ij--; */
1.144 brouard 3645: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3646:
1.126 brouard 3647: }
3648:
1.145 brouard 3649:
1.126 brouard 3650: /*********** Health Expectancies ****************/
3651:
1.127 brouard 3652: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126 brouard 3653:
3654: {
3655: /* Health expectancies, no variances */
1.164 brouard 3656: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3657: int nhstepma, nstepma; /* Decreasing with age */
3658: double age, agelim, hf;
3659: double ***p3mat;
3660: double eip;
3661:
3662: pstamp(ficreseij);
3663: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3664: fprintf(ficreseij,"# Age");
3665: for(i=1; i<=nlstate;i++){
3666: for(j=1; j<=nlstate;j++){
3667: fprintf(ficreseij," e%1d%1d ",i,j);
3668: }
3669: fprintf(ficreseij," e%1d. ",i);
3670: }
3671: fprintf(ficreseij,"\n");
3672:
3673:
3674: if(estepm < stepm){
3675: printf ("Problem %d lower than %d\n",estepm, stepm);
3676: }
3677: else hstepm=estepm;
3678: /* We compute the life expectancy from trapezoids spaced every estepm months
3679: * This is mainly to measure the difference between two models: for example
3680: * if stepm=24 months pijx are given only every 2 years and by summing them
3681: * we are calculating an estimate of the Life Expectancy assuming a linear
3682: * progression in between and thus overestimating or underestimating according
3683: * to the curvature of the survival function. If, for the same date, we
3684: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3685: * to compare the new estimate of Life expectancy with the same linear
3686: * hypothesis. A more precise result, taking into account a more precise
3687: * curvature will be obtained if estepm is as small as stepm. */
3688:
3689: /* For example we decided to compute the life expectancy with the smallest unit */
3690: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3691: nhstepm is the number of hstepm from age to agelim
3692: nstepm is the number of stepm from age to agelin.
3693: Look at hpijx to understand the reason of that which relies in memory size
3694: and note for a fixed period like estepm months */
3695: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3696: survival function given by stepm (the optimization length). Unfortunately it
3697: means that if the survival funtion is printed only each two years of age and if
3698: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3699: results. So we changed our mind and took the option of the best precision.
3700: */
3701: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3702:
3703: agelim=AGESUP;
3704: /* If stepm=6 months */
3705: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3706: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3707:
3708: /* nhstepm age range expressed in number of stepm */
3709: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3710: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3711: /* if (stepm >= YEARM) hstepm=1;*/
3712: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3713: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3714:
3715: for (age=bage; age<=fage; age ++){
3716: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3717: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3718: /* if (stepm >= YEARM) hstepm=1;*/
3719: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3720:
3721: /* If stepm=6 months */
3722: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3723: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3724:
3725: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3726:
3727: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3728:
3729: printf("%d|",(int)age);fflush(stdout);
3730: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3731:
3732: /* Computing expectancies */
3733: for(i=1; i<=nlstate;i++)
3734: for(j=1; j<=nlstate;j++)
3735: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3736: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3737:
3738: /* 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]);*/
3739:
3740: }
3741:
3742: fprintf(ficreseij,"%3.0f",age );
3743: for(i=1; i<=nlstate;i++){
3744: eip=0;
3745: for(j=1; j<=nlstate;j++){
3746: eip +=eij[i][j][(int)age];
3747: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3748: }
3749: fprintf(ficreseij,"%9.4f", eip );
3750: }
3751: fprintf(ficreseij,"\n");
3752:
3753: }
3754: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3755: printf("\n");
3756: fprintf(ficlog,"\n");
3757:
3758: }
3759:
1.127 brouard 3760: 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[] )
1.126 brouard 3761:
3762: {
3763: /* Covariances of health expectancies eij and of total life expectancies according
3764: to initial status i, ei. .
3765: */
3766: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3767: int nhstepma, nstepma; /* Decreasing with age */
3768: double age, agelim, hf;
3769: double ***p3matp, ***p3matm, ***varhe;
3770: double **dnewm,**doldm;
3771: double *xp, *xm;
3772: double **gp, **gm;
3773: double ***gradg, ***trgradg;
3774: int theta;
3775:
3776: double eip, vip;
3777:
3778: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3779: xp=vector(1,npar);
3780: xm=vector(1,npar);
3781: dnewm=matrix(1,nlstate*nlstate,1,npar);
3782: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3783:
3784: pstamp(ficresstdeij);
3785: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3786: fprintf(ficresstdeij,"# Age");
3787: for(i=1; i<=nlstate;i++){
3788: for(j=1; j<=nlstate;j++)
3789: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3790: fprintf(ficresstdeij," e%1d. ",i);
3791: }
3792: fprintf(ficresstdeij,"\n");
3793:
3794: pstamp(ficrescveij);
3795: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3796: fprintf(ficrescveij,"# Age");
3797: for(i=1; i<=nlstate;i++)
3798: for(j=1; j<=nlstate;j++){
3799: cptj= (j-1)*nlstate+i;
3800: for(i2=1; i2<=nlstate;i2++)
3801: for(j2=1; j2<=nlstate;j2++){
3802: cptj2= (j2-1)*nlstate+i2;
3803: if(cptj2 <= cptj)
3804: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3805: }
3806: }
3807: fprintf(ficrescveij,"\n");
3808:
3809: if(estepm < stepm){
3810: printf ("Problem %d lower than %d\n",estepm, stepm);
3811: }
3812: else hstepm=estepm;
3813: /* We compute the life expectancy from trapezoids spaced every estepm months
3814: * This is mainly to measure the difference between two models: for example
3815: * if stepm=24 months pijx are given only every 2 years and by summing them
3816: * we are calculating an estimate of the Life Expectancy assuming a linear
3817: * progression in between and thus overestimating or underestimating according
3818: * to the curvature of the survival function. If, for the same date, we
3819: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3820: * to compare the new estimate of Life expectancy with the same linear
3821: * hypothesis. A more precise result, taking into account a more precise
3822: * curvature will be obtained if estepm is as small as stepm. */
3823:
3824: /* For example we decided to compute the life expectancy with the smallest unit */
3825: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3826: nhstepm is the number of hstepm from age to agelim
3827: nstepm is the number of stepm from age to agelin.
3828: Look at hpijx to understand the reason of that which relies in memory size
3829: and note for a fixed period like estepm months */
3830: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3831: survival function given by stepm (the optimization length). Unfortunately it
3832: means that if the survival funtion is printed only each two years of age and if
3833: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3834: results. So we changed our mind and took the option of the best precision.
3835: */
3836: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3837:
3838: /* If stepm=6 months */
3839: /* nhstepm age range expressed in number of stepm */
3840: agelim=AGESUP;
3841: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3842: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3843: /* if (stepm >= YEARM) hstepm=1;*/
3844: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3845:
3846: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3847: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3848: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3849: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3850: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3851: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3852:
3853: for (age=bage; age<=fage; age ++){
3854: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3855: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3856: /* if (stepm >= YEARM) hstepm=1;*/
3857: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3858:
3859: /* If stepm=6 months */
3860: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3861: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3862:
3863: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3864:
3865: /* Computing Variances of health expectancies */
3866: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3867: decrease memory allocation */
3868: for(theta=1; theta <=npar; theta++){
3869: for(i=1; i<=npar; i++){
3870: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3871: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3872: }
3873: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3874: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3875:
3876: for(j=1; j<= nlstate; j++){
3877: for(i=1; i<=nlstate; i++){
3878: for(h=0; h<=nhstepm-1; h++){
3879: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3880: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3881: }
3882: }
3883: }
3884:
3885: for(ij=1; ij<= nlstate*nlstate; ij++)
3886: for(h=0; h<=nhstepm-1; h++){
3887: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3888: }
3889: }/* End theta */
3890:
3891:
3892: for(h=0; h<=nhstepm-1; h++)
3893: for(j=1; j<=nlstate*nlstate;j++)
3894: for(theta=1; theta <=npar; theta++)
3895: trgradg[h][j][theta]=gradg[h][theta][j];
3896:
3897:
3898: for(ij=1;ij<=nlstate*nlstate;ij++)
3899: for(ji=1;ji<=nlstate*nlstate;ji++)
3900: varhe[ij][ji][(int)age] =0.;
3901:
3902: printf("%d|",(int)age);fflush(stdout);
3903: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3904: for(h=0;h<=nhstepm-1;h++){
3905: for(k=0;k<=nhstepm-1;k++){
3906: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3907: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3908: for(ij=1;ij<=nlstate*nlstate;ij++)
3909: for(ji=1;ji<=nlstate*nlstate;ji++)
3910: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3911: }
3912: }
3913:
3914: /* Computing expectancies */
3915: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3916: for(i=1; i<=nlstate;i++)
3917: for(j=1; j<=nlstate;j++)
3918: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3919: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3920:
3921: /* 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]);*/
3922:
3923: }
3924:
3925: fprintf(ficresstdeij,"%3.0f",age );
3926: for(i=1; i<=nlstate;i++){
3927: eip=0.;
3928: vip=0.;
3929: for(j=1; j<=nlstate;j++){
3930: eip += eij[i][j][(int)age];
3931: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3932: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3933: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3934: }
3935: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3936: }
3937: fprintf(ficresstdeij,"\n");
3938:
3939: fprintf(ficrescveij,"%3.0f",age );
3940: for(i=1; i<=nlstate;i++)
3941: for(j=1; j<=nlstate;j++){
3942: cptj= (j-1)*nlstate+i;
3943: for(i2=1; i2<=nlstate;i2++)
3944: for(j2=1; j2<=nlstate;j2++){
3945: cptj2= (j2-1)*nlstate+i2;
3946: if(cptj2 <= cptj)
3947: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3948: }
3949: }
3950: fprintf(ficrescveij,"\n");
3951:
3952: }
3953: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3954: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3955: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3956: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3957: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3958: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3959: printf("\n");
3960: fprintf(ficlog,"\n");
3961:
3962: free_vector(xm,1,npar);
3963: free_vector(xp,1,npar);
3964: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3965: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3966: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3967: }
3968:
3969: /************ Variance ******************/
1.203 brouard 3970: 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 *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126 brouard 3971: {
3972: /* Variance of health expectancies */
3973: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3974: /* double **newm;*/
1.169 brouard 3975: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3976:
3977: int movingaverage();
1.126 brouard 3978: double **dnewm,**doldm;
3979: double **dnewmp,**doldmp;
3980: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3981: int k;
1.126 brouard 3982: double *xp;
3983: double **gp, **gm; /* for var eij */
3984: double ***gradg, ***trgradg; /*for var eij */
3985: double **gradgp, **trgradgp; /* for var p point j */
3986: double *gpp, *gmp; /* for var p point j */
3987: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3988: double ***p3mat;
3989: double age,agelim, hf;
3990: double ***mobaverage;
3991: int theta;
3992: char digit[4];
3993: char digitp[25];
3994:
3995: char fileresprobmorprev[FILENAMELENGTH];
3996:
3997: if(popbased==1){
3998: if(mobilav!=0)
1.201 brouard 3999: strcpy(digitp,"-POPULBASED-MOBILAV_");
4000: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126 brouard 4001: }
4002: else
1.201 brouard 4003: strcpy(digitp,"-STABLBASED_");
1.126 brouard 4004:
4005: if (mobilav!=0) {
4006: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4007: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4008: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4009: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4010: }
4011: }
4012:
1.201 brouard 4013: strcpy(fileresprobmorprev,"PRMORPREV-");
1.126 brouard 4014: sprintf(digit,"%-d",ij);
4015: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4016: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4017: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202 brouard 4018: strcat(fileresprobmorprev,fileresu);
1.126 brouard 4019: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4020: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4021: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4022: }
4023: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4024:
4025: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4026: pstamp(ficresprobmorprev);
4027: 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);
4028: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4029: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4030: fprintf(ficresprobmorprev," p.%-d SE",j);
4031: for(i=1; i<=nlstate;i++)
4032: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4033: }
4034: fprintf(ficresprobmorprev,"\n");
4035: fprintf(ficgp,"\n# Routine varevsij");
1.200 brouard 4036: fprintf(ficgp,"\nunset title \n");
4037: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126 brouard 4038: 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");
4039: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4040: /* } */
4041: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4042: pstamp(ficresvij);
4043: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4044: if(popbased==1)
1.128 brouard 4045: 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);
1.126 brouard 4046: else
4047: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4048: fprintf(ficresvij,"# Age");
4049: for(i=1; i<=nlstate;i++)
4050: for(j=1; j<=nlstate;j++)
4051: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4052: fprintf(ficresvij,"\n");
4053:
4054: xp=vector(1,npar);
4055: dnewm=matrix(1,nlstate,1,npar);
4056: doldm=matrix(1,nlstate,1,nlstate);
4057: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4058: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4059:
4060: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4061: gpp=vector(nlstate+1,nlstate+ndeath);
4062: gmp=vector(nlstate+1,nlstate+ndeath);
4063: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4064:
4065: if(estepm < stepm){
4066: printf ("Problem %d lower than %d\n",estepm, stepm);
4067: }
4068: else hstepm=estepm;
4069: /* For example we decided to compute the life expectancy with the smallest unit */
4070: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4071: nhstepm is the number of hstepm from age to agelim
4072: nstepm is the number of stepm from age to agelin.
1.128 brouard 4073: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 4074: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4075: survival function given by stepm (the optimization length). Unfortunately it
4076: means that if the survival funtion is printed every two years of age and if
4077: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4078: results. So we changed our mind and took the option of the best precision.
4079: */
4080: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4081: agelim = AGESUP;
4082: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4083: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4084: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4085: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4086: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4087: gp=matrix(0,nhstepm,1,nlstate);
4088: gm=matrix(0,nhstepm,1,nlstate);
4089:
4090:
4091: for(theta=1; theta <=npar; theta++){
4092: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4093: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4094: }
4095: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
1.203 brouard 4096: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126 brouard 4097:
4098: if (popbased==1) {
4099: if(mobilav ==0){
4100: for(i=1; i<=nlstate;i++)
4101: prlim[i][i]=probs[(int)age][i][ij];
4102: }else{ /* mobilav */
4103: for(i=1; i<=nlstate;i++)
4104: prlim[i][i]=mobaverage[(int)age][i][ij];
4105: }
4106: }
4107:
4108: for(j=1; j<= nlstate; j++){
4109: for(h=0; h<=nhstepm; h++){
4110: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4111: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4112: }
4113: }
4114: /* This for computing probability of death (h=1 means
4115: computed over hstepm matrices product = hstepm*stepm months)
4116: as a weighted average of prlim.
4117: */
4118: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4119: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4120: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4121: }
4122: /* end probability of death */
4123:
4124: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4125: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4126: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
1.203 brouard 4127: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
1.126 brouard 4128:
4129: if (popbased==1) {
4130: if(mobilav ==0){
4131: for(i=1; i<=nlstate;i++)
4132: prlim[i][i]=probs[(int)age][i][ij];
4133: }else{ /* mobilav */
4134: for(i=1; i<=nlstate;i++)
4135: prlim[i][i]=mobaverage[(int)age][i][ij];
4136: }
4137: }
4138:
1.128 brouard 4139: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 4140: for(h=0; h<=nhstepm; h++){
4141: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4142: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4143: }
4144: }
4145: /* This for computing probability of death (h=1 means
4146: computed over hstepm matrices product = hstepm*stepm months)
4147: as a weighted average of prlim.
4148: */
4149: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4150: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4151: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4152: }
4153: /* end probability of death */
4154:
4155: for(j=1; j<= nlstate; j++) /* vareij */
4156: for(h=0; h<=nhstepm; h++){
4157: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4158: }
4159:
4160: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4161: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4162: }
4163:
4164: } /* End theta */
4165:
4166: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4167:
4168: for(h=0; h<=nhstepm; h++) /* veij */
4169: for(j=1; j<=nlstate;j++)
4170: for(theta=1; theta <=npar; theta++)
4171: trgradg[h][j][theta]=gradg[h][theta][j];
4172:
4173: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4174: for(theta=1; theta <=npar; theta++)
4175: trgradgp[j][theta]=gradgp[theta][j];
4176:
4177:
4178: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4179: for(i=1;i<=nlstate;i++)
4180: for(j=1;j<=nlstate;j++)
4181: vareij[i][j][(int)age] =0.;
4182:
4183: for(h=0;h<=nhstepm;h++){
4184: for(k=0;k<=nhstepm;k++){
4185: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4186: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4187: for(i=1;i<=nlstate;i++)
4188: for(j=1;j<=nlstate;j++)
4189: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4190: }
4191: }
4192:
4193: /* pptj */
4194: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4195: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4196: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4197: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4198: varppt[j][i]=doldmp[j][i];
4199: /* end ppptj */
4200: /* x centered again */
4201: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
1.203 brouard 4202: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
1.126 brouard 4203:
4204: if (popbased==1) {
4205: if(mobilav ==0){
4206: for(i=1; i<=nlstate;i++)
4207: prlim[i][i]=probs[(int)age][i][ij];
4208: }else{ /* mobilav */
4209: for(i=1; i<=nlstate;i++)
4210: prlim[i][i]=mobaverage[(int)age][i][ij];
4211: }
4212: }
4213:
4214: /* This for computing probability of death (h=1 means
4215: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4216: as a weighted average of prlim.
4217: */
4218: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4219: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4220: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4221: }
4222: /* end probability of death */
4223:
4224: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4225: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4226: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4227: for(i=1; i<=nlstate;i++){
4228: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4229: }
4230: }
4231: fprintf(ficresprobmorprev,"\n");
4232:
4233: fprintf(ficresvij,"%.0f ",age );
4234: for(i=1; i<=nlstate;i++)
4235: for(j=1; j<=nlstate;j++){
4236: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4237: }
4238: fprintf(ficresvij,"\n");
4239: free_matrix(gp,0,nhstepm,1,nlstate);
4240: free_matrix(gm,0,nhstepm,1,nlstate);
4241: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4242: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4243: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4244: } /* End age */
4245: free_vector(gpp,nlstate+1,nlstate+ndeath);
4246: free_vector(gmp,nlstate+1,nlstate+ndeath);
4247: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4248: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199 brouard 4249: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4250: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126 brouard 4251: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4252: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201 brouard 4253: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4254: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4255: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4256: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4257: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4258: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4259: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4260: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201 brouard 4261: 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);
1.199 brouard 4262: /* 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);
1.126 brouard 4263: */
1.199 brouard 4264: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201 brouard 4265: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4266:
4267: free_vector(xp,1,npar);
4268: free_matrix(doldm,1,nlstate,1,nlstate);
4269: free_matrix(dnewm,1,nlstate,1,npar);
4270: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4271: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4272: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4273: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4274: fclose(ficresprobmorprev);
4275: fflush(ficgp);
4276: fflush(fichtm);
4277: } /* end varevsij */
4278:
4279: /************ Variance of prevlim ******************/
1.203 brouard 4280: 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 *ncvyear, int ij, char strstart[])
1.126 brouard 4281: {
1.205 ! brouard 4282: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126 brouard 4283: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4284:
1.126 brouard 4285: double **dnewm,**doldm;
4286: int i, j, nhstepm, hstepm;
4287: double *xp;
4288: double *gp, *gm;
4289: double **gradg, **trgradg;
4290: double age,agelim;
4291: int theta;
4292:
4293: pstamp(ficresvpl);
4294: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4295: fprintf(ficresvpl,"# Age");
4296: for(i=1; i<=nlstate;i++)
4297: fprintf(ficresvpl," %1d-%1d",i,i);
4298: fprintf(ficresvpl,"\n");
4299:
4300: xp=vector(1,npar);
4301: dnewm=matrix(1,nlstate,1,npar);
4302: doldm=matrix(1,nlstate,1,nlstate);
4303:
4304: hstepm=1*YEARM; /* Every year of age */
4305: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4306: agelim = AGESUP;
4307: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4308: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4309: if (stepm >= YEARM) hstepm=1;
4310: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4311: gradg=matrix(1,npar,1,nlstate);
4312: gp=vector(1,nlstate);
4313: gm=vector(1,nlstate);
4314:
4315: for(theta=1; theta <=npar; theta++){
4316: for(i=1; i<=npar; i++){ /* Computes gradient */
4317: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4318: }
1.203 brouard 4319: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126 brouard 4320: for(i=1;i<=nlstate;i++)
4321: gp[i] = prlim[i][i];
4322:
4323: for(i=1; i<=npar; i++) /* Computes gradient */
4324: xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.203 brouard 4325: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126 brouard 4326: for(i=1;i<=nlstate;i++)
4327: gm[i] = prlim[i][i];
4328:
4329: for(i=1;i<=nlstate;i++)
4330: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4331: } /* End theta */
4332:
4333: trgradg =matrix(1,nlstate,1,npar);
4334:
4335: for(j=1; j<=nlstate;j++)
4336: for(theta=1; theta <=npar; theta++)
4337: trgradg[j][theta]=gradg[theta][j];
4338:
4339: for(i=1;i<=nlstate;i++)
4340: varpl[i][(int)age] =0.;
1.205 ! brouard 4341: if((int)age==67 ||(int)age== 66 ){
! 4342: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
! 4343: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
! 4344: }else{
1.126 brouard 4345: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4346: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205 ! brouard 4347: }
1.126 brouard 4348: for(i=1;i<=nlstate;i++)
4349: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4350:
4351: fprintf(ficresvpl,"%.0f ",age );
4352: for(i=1; i<=nlstate;i++)
4353: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4354: fprintf(ficresvpl,"\n");
4355: free_vector(gp,1,nlstate);
4356: free_vector(gm,1,nlstate);
4357: free_matrix(gradg,1,npar,1,nlstate);
4358: free_matrix(trgradg,1,nlstate,1,npar);
4359: } /* End age */
4360:
4361: free_vector(xp,1,npar);
4362: free_matrix(doldm,1,nlstate,1,npar);
4363: free_matrix(dnewm,1,nlstate,1,nlstate);
4364:
4365: }
4366:
4367: /************ Variance of one-step probabilities ******************/
4368: 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[])
4369: {
1.164 brouard 4370: int i, j=0, k1, l1, tj;
1.126 brouard 4371: int k2, l2, j1, z1;
1.164 brouard 4372: int k=0, l;
1.145 brouard 4373: int first=1, first1, first2;
1.126 brouard 4374: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4375: double **dnewm,**doldm;
4376: double *xp;
4377: double *gp, *gm;
4378: double **gradg, **trgradg;
4379: double **mu;
1.164 brouard 4380: double age, cov[NCOVMAX+1];
1.126 brouard 4381: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4382: int theta;
4383: char fileresprob[FILENAMELENGTH];
4384: char fileresprobcov[FILENAMELENGTH];
4385: char fileresprobcor[FILENAMELENGTH];
4386: double ***varpij;
4387:
1.201 brouard 4388: strcpy(fileresprob,"PROB_");
1.126 brouard 4389: strcat(fileresprob,fileres);
4390: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4391: printf("Problem with resultfile: %s\n", fileresprob);
4392: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4393: }
1.201 brouard 4394: strcpy(fileresprobcov,"PROBCOV_");
1.202 brouard 4395: strcat(fileresprobcov,fileresu);
1.126 brouard 4396: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4397: printf("Problem with resultfile: %s\n", fileresprobcov);
4398: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4399: }
1.201 brouard 4400: strcpy(fileresprobcor,"PROBCOR_");
1.202 brouard 4401: strcat(fileresprobcor,fileresu);
1.126 brouard 4402: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4403: printf("Problem with resultfile: %s\n", fileresprobcor);
4404: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4405: }
4406: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4407: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4408: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4409: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4410: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4411: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4412: pstamp(ficresprob);
4413: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4414: fprintf(ficresprob,"# Age");
4415: pstamp(ficresprobcov);
4416: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4417: fprintf(ficresprobcov,"# Age");
4418: pstamp(ficresprobcor);
4419: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4420: fprintf(ficresprobcor,"# Age");
4421:
4422:
4423: for(i=1; i<=nlstate;i++)
4424: for(j=1; j<=(nlstate+ndeath);j++){
4425: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4426: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4427: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4428: }
4429: /* fprintf(ficresprob,"\n");
4430: fprintf(ficresprobcov,"\n");
4431: fprintf(ficresprobcor,"\n");
4432: */
1.131 brouard 4433: xp=vector(1,npar);
1.126 brouard 4434: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4435: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4436: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4437: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4438: first=1;
4439: fprintf(ficgp,"\n# Routine varprob");
4440: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4441: fprintf(fichtm,"\n");
4442:
1.200 brouard 4443: 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);
1.197 brouard 4444: 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);
4445: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126 brouard 4446: and drawn. It helps understanding how is the covariance between two incidences.\
4447: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4448: 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. \
4449: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4450: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4451: standard deviations wide on each axis. <br>\
4452: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4453: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4454: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4455:
4456: cov[1]=1;
1.145 brouard 4457: /* tj=cptcoveff; */
4458: tj = (int) pow(2,cptcoveff);
1.126 brouard 4459: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4460: j1=0;
1.145 brouard 4461: for(j1=1; j1<=tj;j1++){
4462: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4463: /*j1++;*/
1.126 brouard 4464: if (cptcovn>0) {
4465: fprintf(ficresprob, "\n#********** Variable ");
1.198 brouard 4466: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4467: fprintf(ficresprob, "**********\n#\n");
4468: fprintf(ficresprobcov, "\n#********** Variable ");
1.198 brouard 4469: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4470: fprintf(ficresprobcov, "**********\n#\n");
4471:
4472: fprintf(ficgp, "\n#********** Variable ");
1.198 brouard 4473: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4474: fprintf(ficgp, "**********\n#\n");
4475:
4476:
4477: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
1.198 brouard 4478: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4479: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4480:
4481: fprintf(ficresprobcor, "\n#********** Variable ");
1.198 brouard 4482: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4483: fprintf(ficresprobcor, "**********\n#");
4484: }
4485:
1.145 brouard 4486: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4487: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4488: gp=vector(1,(nlstate)*(nlstate+ndeath));
4489: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4490: for (age=bage; age<=fage; age ++){
4491: cov[2]=age;
1.187 brouard 4492: if(nagesqr==1)
4493: cov[3]= age*age;
1.126 brouard 4494: for (k=1; k<=cptcovn;k++) {
1.200 brouard 4495: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4496: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145 brouard 4497: * 1 1 1 1 1
4498: * 2 2 1 1 1
4499: * 3 1 2 1 1
4500: */
4501: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4502: }
1.186 brouard 4503: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 4504: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126 brouard 4505: for (k=1; k<=cptcovprod;k++)
1.200 brouard 4506: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126 brouard 4507:
4508:
4509: for(theta=1; theta <=npar; theta++){
4510: for(i=1; i<=npar; i++)
4511: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4512:
4513: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4514:
4515: k=0;
4516: for(i=1; i<= (nlstate); i++){
4517: for(j=1; j<=(nlstate+ndeath);j++){
4518: k=k+1;
4519: gp[k]=pmmij[i][j];
4520: }
4521: }
4522:
4523: for(i=1; i<=npar; i++)
4524: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4525:
4526: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4527: k=0;
4528: for(i=1; i<=(nlstate); i++){
4529: for(j=1; j<=(nlstate+ndeath);j++){
4530: k=k+1;
4531: gm[k]=pmmij[i][j];
4532: }
4533: }
4534:
4535: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4536: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4537: }
4538:
4539: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4540: for(theta=1; theta <=npar; theta++)
4541: trgradg[j][theta]=gradg[theta][j];
4542:
4543: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4544: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4545:
4546: pmij(pmmij,cov,ncovmodel,x,nlstate);
4547:
4548: k=0;
4549: for(i=1; i<=(nlstate); i++){
4550: for(j=1; j<=(nlstate+ndeath);j++){
4551: k=k+1;
4552: mu[k][(int) age]=pmmij[i][j];
4553: }
4554: }
4555: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4556: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4557: varpij[i][j][(int)age] = doldm[i][j];
4558:
4559: /*printf("\n%d ",(int)age);
4560: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4561: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4562: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4563: }*/
4564:
4565: fprintf(ficresprob,"\n%d ",(int)age);
4566: fprintf(ficresprobcov,"\n%d ",(int)age);
4567: fprintf(ficresprobcor,"\n%d ",(int)age);
4568:
4569: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4570: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4571: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4572: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4573: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4574: }
4575: i=0;
4576: for (k=1; k<=(nlstate);k++){
4577: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4578: i++;
1.126 brouard 4579: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4580: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4581: for (j=1; j<=i;j++){
1.145 brouard 4582: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4583: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4584: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4585: }
4586: }
4587: }/* end of loop for state */
4588: } /* end of loop for age */
1.145 brouard 4589: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4590: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4591: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4592: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4593:
1.126 brouard 4594: /* Confidence intervalle of pij */
4595: /*
1.131 brouard 4596: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4597: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4598: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4599: 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);
4600: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4601: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4602: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4603: */
4604:
4605: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4606: first1=1;first2=2;
1.126 brouard 4607: for (k2=1; k2<=(nlstate);k2++){
4608: for (l2=1; l2<=(nlstate+ndeath);l2++){
4609: if(l2==k2) continue;
4610: j=(k2-1)*(nlstate+ndeath)+l2;
4611: for (k1=1; k1<=(nlstate);k1++){
4612: for (l1=1; l1<=(nlstate+ndeath);l1++){
4613: if(l1==k1) continue;
4614: i=(k1-1)*(nlstate+ndeath)+l1;
4615: if(i<=j) continue;
4616: for (age=bage; age<=fage; age ++){
4617: if ((int)age %5==0){
4618: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4619: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4620: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4621: mu1=mu[i][(int) age]/stepm*YEARM ;
4622: mu2=mu[j][(int) age]/stepm*YEARM;
4623: c12=cv12/sqrt(v1*v2);
4624: /* Computing eigen value of matrix of covariance */
4625: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4626: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4627: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4628: if(first2==1){
4629: first1=0;
4630: 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);
4631: }
4632: 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);
4633: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4634: /* lc2=fabs(lc2); */
1.135 brouard 4635: }
4636:
1.126 brouard 4637: /* Eigen vectors */
4638: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4639: /*v21=sqrt(1.-v11*v11); *//* error */
4640: v21=(lc1-v1)/cv12*v11;
4641: v12=-v21;
4642: v22=v11;
4643: tnalp=v21/v11;
4644: if(first1==1){
4645: first1=0;
4646: 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);
4647: }
4648: 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);
4649: /*printf(fignu*/
4650: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4651: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4652: if(first==1){
4653: first=0;
1.200 brouard 4654: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126 brouard 4655: fprintf(ficgp,"\nset parametric;unset label");
4656: 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);
1.199 brouard 4657: fprintf(ficgp,"\nset ter svg size 640, 480");
1.126 brouard 4658: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201 brouard 4659: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4660: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4661: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4662: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4663: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4664: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201 brouard 4665: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4666: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4667: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4668: 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",\
4669: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4670: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4671: }else{
4672: first=0;
4673: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4674: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4675: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4676: 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",\
4677: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4678: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4679: }/* if first */
4680: } /* age mod 5 */
4681: } /* end loop age */
1.201 brouard 4682: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4683: first=1;
4684: } /*l12 */
4685: } /* k12 */
4686: } /*l1 */
4687: }/* k1 */
1.169 brouard 4688: /* } */ /* loop covariates */
1.126 brouard 4689: }
4690: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4691: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4692: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4693: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4694: free_vector(xp,1,npar);
4695: fclose(ficresprob);
4696: fclose(ficresprobcov);
4697: fclose(ficresprobcor);
4698: fflush(ficgp);
4699: fflush(fichtmcov);
4700: }
4701:
4702:
4703: /******************* Printing html file ***********/
1.201 brouard 4704: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 4705: int lastpass, int stepm, int weightopt, char model[],\
4706: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4707: int popforecast, int estepm ,\
4708: double jprev1, double mprev1,double anprev1, \
4709: double jprev2, double mprev2,double anprev2){
4710: int jj1, k1, i1, cpt;
4711:
4712: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4713: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4714: </ul>");
4715: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4716: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201 brouard 4717: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126 brouard 4718: fprintf(fichtm,"\
4719: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201 brouard 4720: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126 brouard 4721: fprintf(fichtm,"\
4722: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4723: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126 brouard 4724: fprintf(fichtm,"\
1.128 brouard 4725: - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126 brouard 4726: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4727: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126 brouard 4728: fprintf(fichtm,"\
4729: - Population projections by age and states: \
1.201 brouard 4730: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126 brouard 4731:
4732: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4733:
1.145 brouard 4734: m=pow(2,cptcoveff);
1.126 brouard 4735: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4736:
4737: jj1=0;
4738: for(k1=1; k1<=m;k1++){
1.192 brouard 4739: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4740: jj1++;
4741: if (cptcovn > 0) {
4742: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4743: for (cpt=1; cpt<=cptcoveff;cpt++){
1.198 brouard 4744: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4745: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192 brouard 4746: }
1.126 brouard 4747: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4748: }
1.201 brouard 4749: /* aij, bij */
4750: fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
4751: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4752: /* Pij */
1.202 brouard 4753: fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201 brouard 4754: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4755: /* Quasi-incidences */
1.201 brouard 4756: fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4757: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
4758: incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
4759: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
4760: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4761: /* Survival functions (period) in state j */
4762: for(cpt=1; cpt<=nlstate;cpt++){
4763: 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> \
4764: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4765: }
4766: /* State specific survival functions (period) */
4767: for(cpt=1; cpt<=nlstate;cpt++){
4768: fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
4769: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4770: <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);
4771: }
4772: /* Period (stable) prevalence in each health state */
4773: for(cpt=1; cpt<=nlstate;cpt++){
4774: 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> \
4775: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4776: }
1.126 brouard 4777: for(cpt=1; cpt<=nlstate;cpt++) {
1.205 ! brouard 4778: 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> \
1.201 brouard 4779: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.126 brouard 4780: }
1.192 brouard 4781: /* } /\* end i1 *\/ */
1.126 brouard 4782: }/* End k1 */
4783: fprintf(fichtm,"</ul>");
4784:
4785: fprintf(fichtm,"\
4786: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4787: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203 brouard 4788: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197 brouard 4789: But because parameters are usually highly correlated (a higher incidence of disability \
4790: and a higher incidence of recovery can give very close observed transition) it might \
4791: be very useful to look not only at linear confidence intervals estimated from the \
4792: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4793: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4794: covariance matrix of the one-step probabilities. \
4795: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126 brouard 4796:
1.193 brouard 4797: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4798: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126 brouard 4799: fprintf(fichtm,"\
4800: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4801: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126 brouard 4802:
4803: fprintf(fichtm,"\
4804: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4805: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126 brouard 4806: fprintf(fichtm,"\
4807: - 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): \
4808: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4809: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126 brouard 4810: fprintf(fichtm,"\
4811: - (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): \
4812: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4813: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126 brouard 4814: fprintf(fichtm,"\
1.128 brouard 4815: - 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",
1.201 brouard 4816: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126 brouard 4817: fprintf(fichtm,"\
1.128 brouard 4818: - 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",
1.201 brouard 4819: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126 brouard 4820: fprintf(fichtm,"\
4821: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201 brouard 4822: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126 brouard 4823:
4824: /* if(popforecast==1) fprintf(fichtm,"\n */
4825: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4826: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4827: /* <br>",fileres,fileres,fileres,fileres); */
4828: /* else */
4829: /* 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); */
4830: fflush(fichtm);
4831: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4832:
1.145 brouard 4833: m=pow(2,cptcoveff);
1.126 brouard 4834: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4835:
4836: jj1=0;
4837: for(k1=1; k1<=m;k1++){
1.192 brouard 4838: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4839: jj1++;
4840: if (cptcovn > 0) {
4841: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4842: for (cpt=1; cpt<=cptcoveff;cpt++)
1.198 brouard 4843: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126 brouard 4844: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4845: }
4846: for(cpt=1; cpt<=nlstate;cpt++) {
4847: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205 ! brouard 4848: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
! 4849: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
1.126 brouard 4850: }
4851: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4852: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4853: true period expectancies (those weighted with period prevalences are also\
4854: drawn in addition to the population based expectancies computed using\
1.205 ! brouard 4855: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
! 4856: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192 brouard 4857: /* } /\* end i1 *\/ */
1.126 brouard 4858: }/* End k1 */
4859: fprintf(fichtm,"</ul>");
4860: fflush(fichtm);
4861: }
4862:
4863: /******************* Gnuplot file **************/
1.201 brouard 4864: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126 brouard 4865:
4866: char dirfileres[132],optfileres[132];
1.164 brouard 4867: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4868: int ng=0;
1.201 brouard 4869: int vpopbased;
1.126 brouard 4870: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4871: /* printf("Problem with file %s",optionfilegnuplot); */
4872: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4873: /* } */
4874:
4875: /*#ifdef windows */
4876: fprintf(ficgp,"cd \"%s\" \n",pathc);
4877: /*#endif */
4878: m=pow(2,cptcoveff);
4879:
1.202 brouard 4880: /* Contribution to likelihood */
4881: /* Plot the probability implied in the likelihood */
4882: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
4883: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
4884: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205 ! brouard 4885: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204 brouard 4886: /* nice for mle=4 plot by number of matrix products.
1.202 brouard 4887: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
4888: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
4889: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204 brouard 4890: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 ! brouard 4891: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204 brouard 4892: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 ! brouard 4893: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204 brouard 4894: for (i=1; i<= nlstate ; i ++) {
4895: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205 ! brouard 4896: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
! 4897: fprintf(ficgp," u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204 brouard 4898: for (j=2; j<= nlstate+ndeath ; j ++) {
1.205 ! brouard 4899: fprintf(ficgp,",\\\n \"\" u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204 brouard 4900: }
4901: fprintf(ficgp,";\nset out; unset ylabel;\n");
4902: }
4903: /* 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 */
4904: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
4905: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
1.203 brouard 4906: fprintf(ficgp,"\nset out;unset log\n");
1.202 brouard 4907: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
4908:
1.126 brouard 4909: strcpy(dirfileres,optionfilefiname);
4910: strcpy(optfileres,"vpl");
4911: /* 1eme*/
1.201 brouard 4912: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126 brouard 4913: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4914: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201 brouard 4915: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
4916: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4917: fprintf(ficgp,"set xlabel \"Age\" \n\
4918: set ylabel \"Probability\" \n\
1.199 brouard 4919: set ter svg size 640, 480\n\
1.201 brouard 4920: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126 brouard 4921:
4922: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4923: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4924: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4925: }
1.201 brouard 4926: 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);
1.126 brouard 4927: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4928: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4929: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4930: }
1.201 brouard 4931: 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);
1.126 brouard 4932: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4933: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4934: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4935: }
1.201 brouard 4936: 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));
4937: fprintf(ficgp,"\nset out \n");
4938: } /* k1 */
4939: } /* cpt */
1.126 brouard 4940: /*2 eme*/
1.153 brouard 4941: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4942: for (k1=1; k1<= m ; k1 ++) {
1.201 brouard 4943: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
4944: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
4945: if(vpopbased==0)
4946: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
4947: else
4948: fprintf(ficgp,"\nreplot ");
4949: for (i=1; i<= nlstate+1 ; i ++) {
4950: k=2*i;
4951: 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);
4952: for (j=1; j<= nlstate+1 ; j ++) {
4953: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4954: else fprintf(ficgp," %%*lf (%%*lf)");
4955: }
4956: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
4957: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
4958: 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);
4959: for (j=1; j<= nlstate+1 ; j ++) {
4960: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4961: else fprintf(ficgp," %%*lf (%%*lf)");
4962: }
4963: fprintf(ficgp,"\" t\"\" w l lt 0,");
4964: 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);
4965: for (j=1; j<= nlstate+1 ; j ++) {
4966: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4967: else fprintf(ficgp," %%*lf (%%*lf)");
4968: }
4969: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4970: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
4971: } /* state */
4972: } /* vpopbased */
4973: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
4974: } /* k1 */
1.126 brouard 4975: /*3eme*/
4976:
4977: for (k1=1; k1<= m ; k1 ++) {
4978: for (cpt=1; cpt<= nlstate ; cpt ++) {
4979: /* k=2+nlstate*(2*cpt-2); */
4980: k=2+(nlstate+1)*(cpt-1);
1.201 brouard 4981: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199 brouard 4982: fprintf(ficgp,"set ter svg size 640, 480\n\
1.201 brouard 4983: 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);
1.126 brouard 4984: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4985: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4986: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4987: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4988: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4989: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4990:
4991: */
4992: for (i=1; i< nlstate ; i ++) {
1.201 brouard 4993: 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);
1.126 brouard 4994: /* 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);*/
4995:
4996: }
1.201 brouard 4997: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126 brouard 4998: }
4999: }
5000:
1.201 brouard 5001: /* Survival functions (period) from state i in state j by initial state i */
5002: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5003: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5004: k=3;
5005: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
5006: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5007: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5008: set ter svg size 640, 480\n\
5009: unset log y\n\
5010: plot [%.f:%.f] ", ageminpar, agemaxpar);
5011: for (i=1; i<= nlstate ; i ++){
5012: if(i==1)
5013: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5014: else
5015: fprintf(ficgp,", '' ");
5016: l=(nlstate+ndeath)*(i-1)+1;
5017: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5018: for (j=2; j<= nlstate+ndeath ; j ++)
5019: fprintf(ficgp,"+$%d",k+l+j-1);
5020: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5021: } /* nlstate */
5022: fprintf(ficgp,"\nset out\n");
5023: } /* end cpt state*/
5024: } /* end covariate */
5025:
5026: /* Survival functions (period) from state i in state j by final state j */
1.202 brouard 5027: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201 brouard 5028: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5029: k=3;
5030: 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);
5031: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5032: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5033: set ter svg size 640, 480\n\
5034: unset log y\n\
5035: plot [%.f:%.f] ", ageminpar, agemaxpar);
5036: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5037: if(j==1)
5038: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5039: else
5040: fprintf(ficgp,", '' ");
5041: l=(nlstate+ndeath)*(cpt-1) +j;
5042: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5043: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5044: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5045: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5046: } /* nlstate */
5047: fprintf(ficgp,", '' ");
5048: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5049: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5050: l=(nlstate+ndeath)*(cpt-1) +j;
5051: if(j < nlstate)
5052: fprintf(ficgp,"$%d +",k+l);
5053: else
5054: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5055: }
5056: fprintf(ficgp,"\nset out\n");
5057: } /* end cpt state*/
5058: } /* end covariate */
5059:
1.202 brouard 5060: /* CV preval stable (period) for each covariate */
5061: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153 brouard 5062: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 5063: k=3;
1.153 brouard 5064: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201 brouard 5065: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126 brouard 5066: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199 brouard 5067: set ter svg size 640, 480\n\
1.126 brouard 5068: unset log y\n\
1.153 brouard 5069: plot [%.f:%.f] ", ageminpar, agemaxpar);
5070: for (i=1; i<= nlstate ; i ++){
5071: if(i==1)
1.201 brouard 5072: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153 brouard 5073: else
5074: fprintf(ficgp,", '' ");
1.154 brouard 5075: l=(nlstate+ndeath)*(i-1)+1;
5076: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201 brouard 5077: for (j=2; j<= nlstate ; j ++)
5078: fprintf(ficgp,"+$%d",k+l+j-1);
1.153 brouard 5079: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5080: } /* nlstate */
1.201 brouard 5081: fprintf(ficgp,"\nset out\n");
1.153 brouard 5082: } /* end cpt state*/
5083: } /* end covariate */
1.201 brouard 5084:
1.126 brouard 5085: /* proba elementaires */
1.187 brouard 5086: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 5087: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 5088: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 5089: for(k=1; k <=(nlstate+ndeath); k++){
5090: if (k != i) {
1.187 brouard 5091: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 5092: for(j=1; j <=ncovmodel; j++){
1.187 brouard 5093: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 5094: jk++;
5095: }
1.187 brouard 5096: fprintf(ficgp,"\n");
1.126 brouard 5097: }
5098: }
5099: }
1.187 brouard 5100: fprintf(ficgp,"##############\n#\n");
5101:
1.145 brouard 5102: /*goto avoid;*/
1.200 brouard 5103: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187 brouard 5104: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5105: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5106: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5107: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5108: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5109: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5110: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5111: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5112: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5113: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5114: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5115: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5116: fprintf(ficgp,"#\n");
1.201 brouard 5117: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187 brouard 5118: fprintf(ficgp,"# ng=%d\n",ng);
5119: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 5120: for(jk=1; jk <=m; jk++) {
1.187 brouard 5121: fprintf(ficgp,"# jk=%d\n",jk);
1.201 brouard 5122: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5123: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5124: if (ng==1){
5125: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5126: fprintf(ficgp,"\nunset log y");
5127: }else if (ng==2){
5128: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5129: fprintf(ficgp,"\nset log y");
5130: }else if (ng==3){
1.126 brouard 5131: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201 brouard 5132: fprintf(ficgp,"\nset log y");
5133: }else
5134: fprintf(ficgp,"\nunset title ");
5135: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 5136: i=1;
5137: for(k2=1; k2<=nlstate; k2++) {
5138: k3=i;
5139: for(k=1; k<=(nlstate+ndeath); k++) {
5140: if (k != k2){
1.201 brouard 5141: switch( ng) {
5142: case 1:
1.187 brouard 5143: if(nagesqr==0)
1.201 brouard 5144: fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187 brouard 5145: else /* nagesqr =1 */
1.201 brouard 5146: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5147: break;
5148: case 2: /* ng=2 */
1.187 brouard 5149: if(nagesqr==0)
5150: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5151: else /* nagesqr =1 */
1.201 brouard 5152: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5153: break;
5154: case 3:
5155: if(nagesqr==0)
5156: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5157: else /* nagesqr =1 */
5158: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5159: break;
5160: }
1.141 brouard 5161: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 5162: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197 brouard 5163: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5164: if(ij <=cptcovage) { /* Bug valgrind */
5165: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200 brouard 5166: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5167: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197 brouard 5168: ij++;
5169: }
1.186 brouard 5170: }
5171: else
1.198 brouard 5172: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 5173: }
1.201 brouard 5174: if(ng != 1){
5175: fprintf(ficgp,")/(1");
1.126 brouard 5176:
1.201 brouard 5177: for(k1=1; k1 <=nlstate; k1++){
5178: if(nagesqr==0)
5179: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5180: else /* nagesqr =1 */
5181: 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);
5182:
5183: ij=1;
5184: for(j=3; j <=ncovmodel-nagesqr; j++){
5185: if(ij <=cptcovage) { /* Bug valgrind */
5186: if((j-2)==Tage[ij]) { /* Bug valgrind */
5187: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5188: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5189: ij++;
5190: }
1.197 brouard 5191: }
1.201 brouard 5192: else
5193: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186 brouard 5194: }
1.201 brouard 5195: fprintf(ficgp,")");
1.126 brouard 5196: }
5197: fprintf(ficgp,")");
1.201 brouard 5198: if(ng ==2)
5199: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5200: else /* ng= 3 */
5201: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5202: }else{ /* end ng <> 1 */
5203: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126 brouard 5204: }
5205: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5206: i=i+ncovmodel;
5207: }
5208: } /* end k */
5209: } /* end k2 */
1.201 brouard 5210: fprintf(ficgp,"\n set out\n");
1.126 brouard 5211: } /* end jk */
5212: } /* end ng */
1.164 brouard 5213: /* avoid: */
1.126 brouard 5214: fflush(ficgp);
5215: } /* end gnuplot */
5216:
5217:
5218: /*************** Moving average **************/
5219: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5220:
5221: int i, cpt, cptcod;
5222: int modcovmax =1;
5223: int mobilavrange, mob;
5224: double age;
5225:
5226: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5227: a covariate has 2 modalities */
5228: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5229:
5230: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5231: if(mobilav==1) mobilavrange=5; /* default */
5232: else mobilavrange=mobilav;
5233: for (age=bage; age<=fage; age++)
5234: for (i=1; i<=nlstate;i++)
5235: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5236: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5237: /* We keep the original values on the extreme ages bage, fage and for
5238: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5239: we use a 5 terms etc. until the borders are no more concerned.
5240: */
5241: for (mob=3;mob <=mobilavrange;mob=mob+2){
5242: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5243: for (i=1; i<=nlstate;i++){
5244: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5245: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5246: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5247: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5248: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5249: }
5250: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5251: }
5252: }
5253: }/* end age */
5254: }/* end mob */
5255: }else return -1;
5256: return 0;
5257: }/* End movingaverage */
5258:
5259:
5260: /************** Forecasting ******************/
1.169 brouard 5261: 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){
1.126 brouard 5262: /* proj1, year, month, day of starting projection
5263: agemin, agemax range of age
5264: dateprev1 dateprev2 range of dates during which prevalence is computed
5265: anproj2 year of en of projection (same day and month as proj1).
5266: */
1.164 brouard 5267: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 5268: double agec; /* generic age */
5269: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5270: double *popeffectif,*popcount;
5271: double ***p3mat;
5272: double ***mobaverage;
5273: char fileresf[FILENAMELENGTH];
5274:
5275: agelim=AGESUP;
5276: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5277:
1.201 brouard 5278: strcpy(fileresf,"F_");
5279: strcat(fileresf,fileresu);
1.126 brouard 5280: if((ficresf=fopen(fileresf,"w"))==NULL) {
5281: printf("Problem with forecast resultfile: %s\n", fileresf);
5282: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5283: }
5284: printf("Computing forecasting: result on file '%s' \n", fileresf);
5285: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5286:
5287: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5288:
5289: if (mobilav!=0) {
5290: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5291: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5292: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5293: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5294: }
5295: }
5296:
5297: stepsize=(int) (stepm+YEARM-1)/YEARM;
5298: if (stepm<=12) stepsize=1;
5299: if(estepm < stepm){
5300: printf ("Problem %d lower than %d\n",estepm, stepm);
5301: }
5302: else hstepm=estepm;
5303:
5304: hstepm=hstepm/stepm;
5305: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5306: fractional in yp1 */
5307: anprojmean=yp;
5308: yp2=modf((yp1*12),&yp);
5309: mprojmean=yp;
5310: yp1=modf((yp2*30.5),&yp);
5311: jprojmean=yp;
5312: if(jprojmean==0) jprojmean=1;
5313: if(mprojmean==0) jprojmean=1;
5314:
5315: i1=cptcoveff;
5316: if (cptcovn < 1){i1=1;}
5317:
5318: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5319:
5320: fprintf(ficresf,"#****** Routine prevforecast **\n");
5321:
5322: /* if (h==(int)(YEARM*yearp)){ */
5323: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5324: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5325: k=k+1;
5326: fprintf(ficresf,"\n#******");
5327: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5328: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5329: }
5330: fprintf(ficresf,"******\n");
5331: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
5332: for(j=1; j<=nlstate+ndeath;j++){
5333: for(i=1; i<=nlstate;i++)
5334: fprintf(ficresf," p%d%d",i,j);
5335: fprintf(ficresf," p.%d",j);
5336: }
5337: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5338: fprintf(ficresf,"\n");
5339: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5340:
5341: for (agec=fage; agec>=(ageminpar-1); agec--){
5342: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5343: nhstepm = nhstepm/hstepm;
5344: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5345: oldm=oldms;savm=savms;
5346: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5347:
5348: for (h=0; h<=nhstepm; h++){
5349: if (h*hstepm/YEARM*stepm ==yearp) {
5350: fprintf(ficresf,"\n");
5351: for(j=1;j<=cptcoveff;j++)
1.198 brouard 5352: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5353: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5354: }
5355: for(j=1; j<=nlstate+ndeath;j++) {
5356: ppij=0.;
5357: for(i=1; i<=nlstate;i++) {
5358: if (mobilav==1)
5359: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5360: else {
5361: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5362: }
5363: if (h*hstepm/YEARM*stepm== yearp) {
5364: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5365: }
5366: } /* end i */
5367: if (h*hstepm/YEARM*stepm==yearp) {
5368: fprintf(ficresf," %.3f", ppij);
5369: }
5370: }/* end j */
5371: } /* end h */
5372: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5373: } /* end agec */
5374: } /* end yearp */
5375: } /* end cptcod */
5376: } /* end cptcov */
5377:
5378: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5379:
5380: fclose(ficresf);
5381: }
5382:
5383: /************** Forecasting *****not tested NB*************/
1.169 brouard 5384: 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){
1.126 brouard 5385:
5386: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5387: int *popage;
5388: double calagedatem, agelim, kk1, kk2;
5389: double *popeffectif,*popcount;
5390: double ***p3mat,***tabpop,***tabpopprev;
5391: double ***mobaverage;
5392: char filerespop[FILENAMELENGTH];
5393:
5394: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5395: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5396: agelim=AGESUP;
5397: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5398:
5399: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5400:
5401:
1.201 brouard 5402: strcpy(filerespop,"POP_");
5403: strcat(filerespop,fileresu);
1.126 brouard 5404: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5405: printf("Problem with forecast resultfile: %s\n", filerespop);
5406: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5407: }
5408: printf("Computing forecasting: result on file '%s' \n", filerespop);
5409: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5410:
5411: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5412:
5413: if (mobilav!=0) {
5414: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5415: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5416: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5417: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5418: }
5419: }
5420:
5421: stepsize=(int) (stepm+YEARM-1)/YEARM;
5422: if (stepm<=12) stepsize=1;
5423:
5424: agelim=AGESUP;
5425:
5426: hstepm=1;
5427: hstepm=hstepm/stepm;
5428:
5429: if (popforecast==1) {
5430: if((ficpop=fopen(popfile,"r"))==NULL) {
5431: printf("Problem with population file : %s\n",popfile);exit(0);
5432: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5433: }
5434: popage=ivector(0,AGESUP);
5435: popeffectif=vector(0,AGESUP);
5436: popcount=vector(0,AGESUP);
5437:
5438: i=1;
5439: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5440:
5441: imx=i;
5442: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5443: }
5444:
5445: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5446: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5447: k=k+1;
5448: fprintf(ficrespop,"\n#******");
5449: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5450: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5451: }
5452: fprintf(ficrespop,"******\n");
5453: fprintf(ficrespop,"# Age");
5454: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5455: if (popforecast==1) fprintf(ficrespop," [Population]");
5456:
5457: for (cpt=0; cpt<=0;cpt++) {
5458: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5459:
5460: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5461: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5462: nhstepm = nhstepm/hstepm;
5463:
5464: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5465: oldm=oldms;savm=savms;
5466: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5467:
5468: for (h=0; h<=nhstepm; h++){
5469: if (h==(int) (calagedatem+YEARM*cpt)) {
5470: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5471: }
5472: for(j=1; j<=nlstate+ndeath;j++) {
5473: kk1=0.;kk2=0;
5474: for(i=1; i<=nlstate;i++) {
5475: if (mobilav==1)
5476: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5477: else {
5478: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5479: }
5480: }
5481: if (h==(int)(calagedatem+12*cpt)){
5482: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5483: /*fprintf(ficrespop," %.3f", kk1);
5484: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5485: }
5486: }
5487: for(i=1; i<=nlstate;i++){
5488: kk1=0.;
5489: for(j=1; j<=nlstate;j++){
5490: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5491: }
5492: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5493: }
5494:
5495: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5496: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5497: }
5498: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5499: }
5500: }
5501:
5502: /******/
5503:
5504: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5505: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5506: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5507: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5508: nhstepm = nhstepm/hstepm;
5509:
5510: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5511: oldm=oldms;savm=savms;
5512: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5513: for (h=0; h<=nhstepm; h++){
5514: if (h==(int) (calagedatem+YEARM*cpt)) {
5515: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5516: }
5517: for(j=1; j<=nlstate+ndeath;j++) {
5518: kk1=0.;kk2=0;
5519: for(i=1; i<=nlstate;i++) {
5520: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5521: }
5522: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5523: }
5524: }
5525: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5526: }
5527: }
5528: }
5529: }
5530:
5531: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5532:
5533: if (popforecast==1) {
5534: free_ivector(popage,0,AGESUP);
5535: free_vector(popeffectif,0,AGESUP);
5536: free_vector(popcount,0,AGESUP);
5537: }
5538: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5539: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5540: fclose(ficrespop);
5541: } /* End of popforecast */
5542:
5543: int fileappend(FILE *fichier, char *optionfich)
5544: {
5545: if((fichier=fopen(optionfich,"a"))==NULL) {
5546: printf("Problem with file: %s\n", optionfich);
5547: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5548: return (0);
5549: }
5550: fflush(fichier);
5551: return (1);
5552: }
5553:
5554:
5555: /**************** function prwizard **********************/
5556: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5557: {
5558:
5559: /* Wizard to print covariance matrix template */
5560:
1.164 brouard 5561: char ca[32], cb[32];
5562: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5563: int numlinepar;
5564:
5565: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5566: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5567: for(i=1; i <=nlstate; i++){
5568: jj=0;
5569: for(j=1; j <=nlstate+ndeath; j++){
5570: if(j==i) continue;
5571: jj++;
5572: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5573: printf("%1d%1d",i,j);
5574: fprintf(ficparo,"%1d%1d",i,j);
5575: for(k=1; k<=ncovmodel;k++){
5576: /* printf(" %lf",param[i][j][k]); */
5577: /* fprintf(ficparo," %lf",param[i][j][k]); */
5578: printf(" 0.");
5579: fprintf(ficparo," 0.");
5580: }
5581: printf("\n");
5582: fprintf(ficparo,"\n");
5583: }
5584: }
5585: printf("# Scales (for hessian or gradient estimation)\n");
5586: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5587: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5588: for(i=1; i <=nlstate; i++){
5589: jj=0;
5590: for(j=1; j <=nlstate+ndeath; j++){
5591: if(j==i) continue;
5592: jj++;
5593: fprintf(ficparo,"%1d%1d",i,j);
5594: printf("%1d%1d",i,j);
5595: fflush(stdout);
5596: for(k=1; k<=ncovmodel;k++){
5597: /* printf(" %le",delti3[i][j][k]); */
5598: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5599: printf(" 0.");
5600: fprintf(ficparo," 0.");
5601: }
5602: numlinepar++;
5603: printf("\n");
5604: fprintf(ficparo,"\n");
5605: }
5606: }
5607: printf("# Covariance matrix\n");
5608: /* # 121 Var(a12)\n\ */
5609: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5610: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5611: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5612: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5613: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5614: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5615: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5616: fflush(stdout);
5617: fprintf(ficparo,"# Covariance matrix\n");
5618: /* # 121 Var(a12)\n\ */
5619: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5620: /* # ...\n\ */
5621: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5622:
5623: for(itimes=1;itimes<=2;itimes++){
5624: jj=0;
5625: for(i=1; i <=nlstate; i++){
5626: for(j=1; j <=nlstate+ndeath; j++){
5627: if(j==i) continue;
5628: for(k=1; k<=ncovmodel;k++){
5629: jj++;
5630: ca[0]= k+'a'-1;ca[1]='\0';
5631: if(itimes==1){
5632: printf("#%1d%1d%d",i,j,k);
5633: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5634: }else{
5635: printf("%1d%1d%d",i,j,k);
5636: fprintf(ficparo,"%1d%1d%d",i,j,k);
5637: /* printf(" %.5le",matcov[i][j]); */
5638: }
5639: ll=0;
5640: for(li=1;li <=nlstate; li++){
5641: for(lj=1;lj <=nlstate+ndeath; lj++){
5642: if(lj==li) continue;
5643: for(lk=1;lk<=ncovmodel;lk++){
5644: ll++;
5645: if(ll<=jj){
5646: cb[0]= lk +'a'-1;cb[1]='\0';
5647: if(ll<jj){
5648: if(itimes==1){
5649: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5650: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5651: }else{
5652: printf(" 0.");
5653: fprintf(ficparo," 0.");
5654: }
5655: }else{
5656: if(itimes==1){
5657: printf(" Var(%s%1d%1d)",ca,i,j);
5658: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5659: }else{
5660: printf(" 0.");
5661: fprintf(ficparo," 0.");
5662: }
5663: }
5664: }
5665: } /* end lk */
5666: } /* end lj */
5667: } /* end li */
5668: printf("\n");
5669: fprintf(ficparo,"\n");
5670: numlinepar++;
5671: } /* end k*/
5672: } /*end j */
5673: } /* end i */
5674: } /* end itimes */
5675:
5676: } /* end of prwizard */
5677: /******************* Gompertz Likelihood ******************************/
5678: double gompertz(double x[])
5679: {
5680: double A,B,L=0.0,sump=0.,num=0.;
5681: int i,n=0; /* n is the size of the sample */
5682:
5683: for (i=0;i<=imx-1 ; i++) {
5684: sump=sump+weight[i];
5685: /* sump=sump+1;*/
5686: num=num+1;
5687: }
5688:
5689:
5690: /* for (i=0; i<=imx; i++)
5691: 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]);*/
5692:
5693: for (i=1;i<=imx ; i++)
5694: {
5695: if (cens[i] == 1 && wav[i]>1)
5696: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5697:
5698: if (cens[i] == 0 && wav[i]>1)
5699: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5700: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5701:
5702: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5703: if (wav[i] > 1 ) { /* ??? */
5704: L=L+A*weight[i];
5705: /* 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]);*/
5706: }
5707: }
5708:
5709: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5710:
5711: return -2*L*num/sump;
5712: }
5713:
1.136 brouard 5714: #ifdef GSL
5715: /******************* Gompertz_f Likelihood ******************************/
5716: double gompertz_f(const gsl_vector *v, void *params)
5717: {
5718: double A,B,LL=0.0,sump=0.,num=0.;
5719: double *x= (double *) v->data;
5720: int i,n=0; /* n is the size of the sample */
5721:
5722: for (i=0;i<=imx-1 ; i++) {
5723: sump=sump+weight[i];
5724: /* sump=sump+1;*/
5725: num=num+1;
5726: }
5727:
5728:
5729: /* for (i=0; i<=imx; i++)
5730: 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]);*/
5731: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5732: for (i=1;i<=imx ; i++)
5733: {
5734: if (cens[i] == 1 && wav[i]>1)
5735: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5736:
5737: if (cens[i] == 0 && wav[i]>1)
5738: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5739: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5740:
5741: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5742: if (wav[i] > 1 ) { /* ??? */
5743: LL=LL+A*weight[i];
5744: /* 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]);*/
5745: }
5746: }
5747:
5748: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5749: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5750:
5751: return -2*LL*num/sump;
5752: }
5753: #endif
5754:
1.126 brouard 5755: /******************* Printing html file ***********/
1.201 brouard 5756: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 5757: int lastpass, int stepm, int weightopt, char model[],\
5758: int imx, double p[],double **matcov,double agemortsup){
5759: int i,k;
5760:
5761: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5762: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5763: for (i=1;i<=2;i++)
5764: 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]));
1.199 brouard 5765: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126 brouard 5766: fprintf(fichtm,"</ul>");
5767:
5768: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5769:
5770: 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>");
5771:
5772: for (k=agegomp;k<(agemortsup-2);k++)
5773: 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]);
5774:
5775:
5776: fflush(fichtm);
5777: }
5778:
5779: /******************* Gnuplot file **************/
1.201 brouard 5780: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126 brouard 5781:
5782: char dirfileres[132],optfileres[132];
1.164 brouard 5783:
1.126 brouard 5784: int ng;
5785:
5786:
5787: /*#ifdef windows */
5788: fprintf(ficgp,"cd \"%s\" \n",pathc);
5789: /*#endif */
5790:
5791:
5792: strcpy(dirfileres,optionfilefiname);
5793: strcpy(optfileres,"vpl");
1.199 brouard 5794: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
1.126 brouard 5795: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.199 brouard 5796: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
1.145 brouard 5797: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5798: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5799:
5800: }
5801:
1.136 brouard 5802: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5803: {
1.126 brouard 5804:
1.136 brouard 5805: /*-------- data file ----------*/
5806: FILE *fic;
5807: char dummy[]=" ";
1.164 brouard 5808: int i=0, j=0, n=0;
1.136 brouard 5809: int linei, month, year,iout;
5810: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5811: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5812: char *stratrunc;
5813: int lstra;
1.126 brouard 5814:
5815:
1.136 brouard 5816: if((fic=fopen(datafile,"r"))==NULL) {
1.195 brouard 5817: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5818: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136 brouard 5819: }
1.126 brouard 5820:
1.136 brouard 5821: i=1;
5822: linei=0;
5823: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5824: linei=linei+1;
5825: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5826: if(line[j] == '\t')
5827: line[j] = ' ';
5828: }
5829: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5830: ;
5831: };
5832: line[j+1]=0; /* Trims blanks at end of line */
5833: if(line[0]=='#'){
5834: fprintf(ficlog,"Comment line\n%s\n",line);
5835: printf("Comment line\n%s\n",line);
5836: continue;
5837: }
5838: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5839: strcpy(line, linetmp);
1.136 brouard 5840:
1.126 brouard 5841:
1.136 brouard 5842: for (j=maxwav;j>=1;j--){
1.137 brouard 5843: cutv(stra, strb, line, ' ');
1.136 brouard 5844: if(strb[0]=='.') { /* Missing status */
5845: lval=-1;
5846: }else{
5847: errno=0;
5848: lval=strtol(strb,&endptr,10);
5849: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5850: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5851: 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);
5852: 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);
1.136 brouard 5853: return 1;
5854: }
5855: }
5856: s[j][i]=lval;
5857:
5858: strcpy(line,stra);
5859: cutv(stra, strb,line,' ');
1.169 brouard 5860: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5861: }
1.169 brouard 5862: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5863: month=99;
5864: year=9999;
5865: }else{
1.141 brouard 5866: 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);
5867: 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);
1.136 brouard 5868: return 1;
5869: }
5870: anint[j][i]= (double) year;
5871: mint[j][i]= (double)month;
5872: strcpy(line,stra);
5873: } /* ENd Waves */
5874:
5875: cutv(stra, strb,line,' ');
1.169 brouard 5876: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5877: }
1.169 brouard 5878: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5879: month=99;
5880: year=9999;
5881: }else{
1.141 brouard 5882: 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);
5883: 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);
1.136 brouard 5884: return 1;
5885: }
5886: andc[i]=(double) year;
5887: moisdc[i]=(double) month;
5888: strcpy(line,stra);
5889:
5890: cutv(stra, strb,line,' ');
1.169 brouard 5891: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5892: }
1.169 brouard 5893: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5894: month=99;
5895: year=9999;
5896: }else{
1.141 brouard 5897: 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);
5898: 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);
1.136 brouard 5899: return 1;
5900: }
5901: if (year==9999) {
1.141 brouard 5902: 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);
5903: 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);
1.136 brouard 5904: return 1;
1.126 brouard 5905:
1.136 brouard 5906: }
5907: annais[i]=(double)(year);
5908: moisnais[i]=(double)(month);
5909: strcpy(line,stra);
5910:
5911: cutv(stra, strb,line,' ');
5912: errno=0;
5913: dval=strtod(strb,&endptr);
5914: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5915: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5916: 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);
1.136 brouard 5917: fflush(ficlog);
5918: return 1;
5919: }
5920: weight[i]=dval;
5921: strcpy(line,stra);
5922:
5923: for (j=ncovcol;j>=1;j--){
5924: cutv(stra, strb,line,' ');
5925: if(strb[0]=='.') { /* Missing status */
5926: lval=-1;
5927: }else{
5928: errno=0;
5929: lval=strtol(strb,&endptr,10);
5930: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5931: 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);
5932: 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);
1.136 brouard 5933: return 1;
5934: }
5935: }
5936: if(lval <-1 || lval >1){
1.141 brouard 5937: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5938: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5939: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5940: For example, for multinomial values like 1, 2 and 3,\n \
5941: build V1=0 V2=0 for the reference value (1),\n \
5942: V1=1 V2=0 for (2) \n \
5943: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5944: output of IMaCh is often meaningless.\n \
5945: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5946: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5947: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5948: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5949: For example, for multinomial values like 1, 2 and 3,\n \
5950: build V1=0 V2=0 for the reference value (1),\n \
5951: V1=1 V2=0 for (2) \n \
5952: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5953: output of IMaCh is often meaningless.\n \
5954: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5955: return 1;
5956: }
5957: covar[j][i]=(double)(lval);
5958: strcpy(line,stra);
5959: }
5960: lstra=strlen(stra);
5961:
5962: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5963: stratrunc = &(stra[lstra-9]);
5964: num[i]=atol(stratrunc);
5965: }
5966: else
5967: num[i]=atol(stra);
5968: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5969: 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;}*/
5970:
5971: i=i+1;
5972: } /* End loop reading data */
1.126 brouard 5973:
1.136 brouard 5974: *imax=i-1; /* Number of individuals */
5975: fclose(fic);
5976:
5977: return (0);
1.164 brouard 5978: /* endread: */
1.136 brouard 5979: printf("Exiting readdata: ");
5980: fclose(fic);
5981: return (1);
1.126 brouard 5982:
5983:
5984:
1.136 brouard 5985: }
1.145 brouard 5986: void removespace(char *str) {
5987: char *p1 = str, *p2 = str;
5988: do
5989: while (*p2 == ' ')
5990: p2++;
1.169 brouard 5991: while (*p1++ == *p2++);
1.145 brouard 5992: }
5993:
5994: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5995: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5996: * - nagesqr = 1 if age*age in the model, otherwise 0.
5997: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5998: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5999: * - cptcovage number of covariates with age*products =2
6000: * - cptcovs number of simple covariates
6001: * - 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
6002: * which is a new column after the 9 (ncovcol) variables.
6003: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6004: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6005: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6006: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6007: */
1.136 brouard 6008: {
1.145 brouard 6009: int i, j, k, ks;
1.164 brouard 6010: int j1, k1, k2;
1.136 brouard 6011: char modelsav[80];
1.145 brouard 6012: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 6013: char *strpt;
1.136 brouard 6014:
1.145 brouard 6015: /*removespace(model);*/
1.136 brouard 6016: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 6017: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 6018: if (strstr(model,"AGE") !=0){
1.192 brouard 6019: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6020: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 6021: return 1;
6022: }
1.141 brouard 6023: if (strstr(model,"v") !=0){
6024: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6025: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6026: return 1;
6027: }
1.187 brouard 6028: strcpy(modelsav,model);
6029: if ((strpt=strstr(model,"age*age")) !=0){
6030: printf(" strpt=%s, model=%s\n",strpt, model);
6031: if(strpt != model){
6032: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6033: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6034: corresponding column of parameters.\n",model);
6035: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6036: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6037: corresponding column of parameters.\n",model); fflush(ficlog);
6038: return 1;
6039: }
6040:
6041: nagesqr=1;
6042: if (strstr(model,"+age*age") !=0)
6043: substrchaine(modelsav, model, "+age*age");
6044: else if (strstr(model,"age*age+") !=0)
6045: substrchaine(modelsav, model, "age*age+");
6046: else
6047: substrchaine(modelsav, model, "age*age");
6048: }else
6049: nagesqr=0;
6050: if (strlen(modelsav) >1){
6051: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6052: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6053: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6054: cptcovt= j+1; /* Number of total covariates in the model, not including
6055: * cst, age and age*age
6056: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6057: /* including age products which are counted in cptcovage.
6058: * but the covariates which are products must be treated
6059: * separately: ncovn=4- 2=2 (V1+V3). */
6060: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6061: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6062:
6063:
6064: /* Design
6065: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6066: * < ncovcol=8 >
6067: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6068: * k= 1 2 3 4 5 6 7 8
6069: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6070: * covar[k,i], value of kth covariate if not including age for individual i:
6071: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6072: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6073: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6074: * Tage[++cptcovage]=k
6075: * if products, new covar are created after ncovcol with k1
6076: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6077: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6078: * 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
6079: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6080: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6081: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6082: * < ncovcol=8 >
6083: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6084: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6085: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6086: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6087: * p Tprod[1]@2={ 6, 5}
6088: *p Tvard[1][1]@4= {7, 8, 5, 6}
6089: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6090: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6091: *How to reorganize?
6092: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6093: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6094: * {2, 1, 4, 8, 5, 6, 3, 7}
6095: * Struct []
6096: */
1.145 brouard 6097:
1.187 brouard 6098: /* This loop fills the array Tvar from the string 'model'.*/
6099: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6100: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6101: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6102: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6103: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6104: /* k=1 Tvar[1]=2 (from V2) */
6105: /* k=5 Tvar[5] */
6106: /* for (k=1; k<=cptcovn;k++) { */
1.198 brouard 6107: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187 brouard 6108: /* } */
1.198 brouard 6109: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187 brouard 6110: /*
6111: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6112: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 6113: Tvar[k]=0;
1.187 brouard 6114: cptcovage=0;
6115: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6116: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6117: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6118: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6119: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6120: /*scanf("%d",i);*/
6121: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6122: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6123: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6124: /* covar is not filled and then is empty */
6125: cptcovprod--;
6126: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6127: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6128: cptcovage++; /* Sums the number of covariates which include age as a product */
6129: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6130: /*printf("stre=%s ", stre);*/
6131: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6132: cptcovprod--;
6133: cutl(stre,strb,strc,'V');
6134: Tvar[k]=atoi(stre);
6135: cptcovage++;
6136: Tage[cptcovage]=k;
6137: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6138: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6139: cptcovn++;
6140: cptcovprodnoage++;k1++;
6141: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6142: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6143: because this model-covariate is a construction we invent a new column
6144: ncovcol + k1
6145: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6146: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6147: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6148: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6149: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6150: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6151: k2=k2+2;
6152: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6153: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6154: for (i=1; i<=lastobs;i++){
6155: /* Computes the new covariate which is a product of
6156: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6157: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6158: }
6159: } /* End age is not in the model */
6160: } /* End if model includes a product */
6161: else { /* no more sum */
6162: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6163: /* scanf("%d",i);*/
6164: cutl(strd,strc,strb,'V');
6165: ks++; /**< Number of simple covariates */
1.145 brouard 6166: cptcovn++;
1.187 brouard 6167: Tvar[k]=atoi(strd);
6168: }
6169: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6170: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6171: scanf("%d",i);*/
6172: } /* end of loop + on total covariates */
6173: } /* end if strlen(modelsave == 0) age*age might exist */
6174: } /* end if strlen(model == 0) */
1.136 brouard 6175:
6176: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6177: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6178:
6179: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6180: printf("cptcovprod=%d ", cptcovprod);
6181: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6182:
6183: scanf("%d ",i);*/
6184:
6185:
1.137 brouard 6186: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 6187: /*endread:*/
1.136 brouard 6188: printf("Exiting decodemodel: ");
6189: return (1);
6190: }
6191:
1.169 brouard 6192: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 6193: {
6194: int i, m;
6195:
6196: for (i=1; i<=imx; i++) {
6197: for(m=2; (m<= maxwav); m++) {
6198: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6199: anint[m][i]=9999;
6200: s[m][i]=-1;
6201: }
6202: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 6203: *nberr = *nberr + 1;
6204: printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
6205: fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136 brouard 6206: s[m][i]=-1;
6207: }
6208: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 6209: (*nberr)++;
1.136 brouard 6210: 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]);
6211: 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]);
6212: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6213: }
6214: }
6215: }
6216:
6217: for (i=1; i<=imx; i++) {
6218: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6219: for(m=firstpass; (m<= lastpass); m++){
6220: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6221: if (s[m][i] >= nlstate+1) {
1.169 brouard 6222: if(agedc[i]>0){
6223: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 6224: agev[m][i]=agedc[i];
6225: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 6226: }else {
1.136 brouard 6227: if ((int)andc[i]!=9999){
6228: nbwarn++;
6229: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6230: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6231: agev[m][i]=-1;
6232: }
6233: }
1.169 brouard 6234: } /* agedc > 0 */
1.136 brouard 6235: }
6236: else if(s[m][i] !=9){ /* Standard case, age in fractional
6237: years but with the precision of a month */
6238: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6239: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6240: agev[m][i]=1;
6241: else if(agev[m][i] < *agemin){
6242: *agemin=agev[m][i];
6243: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6244: }
6245: else if(agev[m][i] >*agemax){
6246: *agemax=agev[m][i];
1.156 brouard 6247: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 6248: }
6249: /*agev[m][i]=anint[m][i]-annais[i];*/
6250: /* agev[m][i] = age[i]+2*m;*/
6251: }
6252: else { /* =9 */
6253: agev[m][i]=1;
6254: s[m][i]=-1;
6255: }
6256: }
6257: else /*= 0 Unknown */
6258: agev[m][i]=1;
6259: }
6260:
6261: }
6262: for (i=1; i<=imx; i++) {
6263: for(m=firstpass; (m<=lastpass); m++){
6264: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 6265: (*nberr)++;
1.136 brouard 6266: 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);
6267: 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);
6268: return 1;
6269: }
6270: }
6271: }
6272:
6273: /*for (i=1; i<=imx; i++){
6274: for (m=firstpass; (m<lastpass); m++){
6275: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6276: }
6277:
6278: }*/
6279:
6280:
1.139 brouard 6281: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6282: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 6283:
6284: return (0);
1.164 brouard 6285: /* endread:*/
1.136 brouard 6286: printf("Exiting calandcheckages: ");
6287: return (1);
6288: }
6289:
1.172 brouard 6290: #if defined(_MSC_VER)
6291: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6292: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6293: //#include "stdafx.h"
6294: //#include <stdio.h>
6295: //#include <tchar.h>
6296: //#include <windows.h>
6297: //#include <iostream>
6298: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6299:
6300: LPFN_ISWOW64PROCESS fnIsWow64Process;
6301:
6302: BOOL IsWow64()
6303: {
6304: BOOL bIsWow64 = FALSE;
6305:
6306: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6307: // (HANDLE, PBOOL);
6308:
6309: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6310:
6311: HMODULE module = GetModuleHandle(_T("kernel32"));
6312: const char funcName[] = "IsWow64Process";
6313: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6314: GetProcAddress(module, funcName);
6315:
6316: if (NULL != fnIsWow64Process)
6317: {
6318: if (!fnIsWow64Process(GetCurrentProcess(),
6319: &bIsWow64))
6320: //throw std::exception("Unknown error");
6321: printf("Unknown error\n");
6322: }
6323: return bIsWow64 != FALSE;
6324: }
6325: #endif
1.177 brouard 6326:
1.191 brouard 6327: void syscompilerinfo(int logged)
1.167 brouard 6328: {
6329: /* #include "syscompilerinfo.h"*/
1.185 brouard 6330: /* command line Intel compiler 32bit windows, XP compatible:*/
6331: /* /GS /W3 /Gy
6332: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6333: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6334: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 6335: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6336: */
6337: /* 64 bits */
1.185 brouard 6338: /*
6339: /GS /W3 /Gy
6340: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6341: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6342: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6343: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6344: /* Optimization are useless and O3 is slower than O2 */
6345: /*
6346: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6347: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6348: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6349: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6350: */
1.186 brouard 6351: /* Link is */ /* /OUT:"visual studio
1.185 brouard 6352: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6353: /PDB:"visual studio
6354: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6355: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6356: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6357: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6358: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6359: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6360: uiAccess='false'"
6361: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6362: /NOLOGO /TLBID:1
6363: */
1.177 brouard 6364: #if defined __INTEL_COMPILER
1.178 brouard 6365: #if defined(__GNUC__)
6366: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6367: #endif
1.177 brouard 6368: #elif defined(__GNUC__)
1.179 brouard 6369: #ifndef __APPLE__
1.174 brouard 6370: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 6371: #endif
1.177 brouard 6372: struct utsname sysInfo;
1.178 brouard 6373: int cross = CROSS;
6374: if (cross){
6375: printf("Cross-");
1.191 brouard 6376: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6377: }
1.174 brouard 6378: #endif
6379:
1.171 brouard 6380: #include <stdint.h>
1.178 brouard 6381:
1.191 brouard 6382: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6383: #if defined(__clang__)
1.191 brouard 6384: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6385: #endif
6386: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6387: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6388: #endif
6389: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6390: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6391: #endif
6392: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6393: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6394: #endif
6395: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6396: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6397: #endif
6398: #if defined(_MSC_VER)
1.191 brouard 6399: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6400: #endif
6401: #if defined(__PGI)
1.191 brouard 6402: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6403: #endif
6404: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6405: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6406: #endif
1.191 brouard 6407: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6408:
1.167 brouard 6409: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6410: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6411: // Windows (x64 and x86)
1.191 brouard 6412: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6413: #elif __unix__ // all unices, not all compilers
6414: // Unix
1.191 brouard 6415: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6416: #elif __linux__
6417: // linux
1.191 brouard 6418: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6419: #elif __APPLE__
1.174 brouard 6420: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6421: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6422: #endif
6423:
6424: /* __MINGW32__ */
6425: /* __CYGWIN__ */
6426: /* __MINGW64__ */
6427: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6428: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6429: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6430: /* _WIN64 // Defined for applications for Win64. */
6431: /* _M_X64 // Defined for compilations that target x64 processors. */
6432: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6433:
1.167 brouard 6434: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6435: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6436: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6437: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6438: #else
1.191 brouard 6439: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6440: #endif
6441:
1.169 brouard 6442: #if defined(__GNUC__)
6443: # if defined(__GNUC_PATCHLEVEL__)
6444: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6445: + __GNUC_MINOR__ * 100 \
6446: + __GNUC_PATCHLEVEL__)
6447: # else
6448: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6449: + __GNUC_MINOR__ * 100)
6450: # endif
1.174 brouard 6451: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6452: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6453:
6454: if (uname(&sysInfo) != -1) {
6455: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6456: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176 brouard 6457: }
6458: else
6459: perror("uname() error");
1.179 brouard 6460: //#ifndef __INTEL_COMPILER
6461: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6462: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6463: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6464: #endif
1.169 brouard 6465: #endif
1.172 brouard 6466:
6467: // void main()
6468: // {
1.169 brouard 6469: #if defined(_MSC_VER)
1.174 brouard 6470: if (IsWow64()){
1.191 brouard 6471: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6472: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6473: }
6474: else{
1.191 brouard 6475: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6476: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6477: }
1.172 brouard 6478: // printf("\nPress Enter to continue...");
6479: // getchar();
6480: // }
6481:
1.169 brouard 6482: #endif
6483:
1.167 brouard 6484:
6485: }
1.136 brouard 6486:
1.203 brouard 6487: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
1.180 brouard 6488: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6489: int i, j, k, i1 ;
1.202 brouard 6490: /* double ftolpl = 1.e-10; */
1.180 brouard 6491: double age, agebase, agelim;
1.203 brouard 6492: double tot;
1.180 brouard 6493:
1.202 brouard 6494: strcpy(filerespl,"PL_");
6495: strcat(filerespl,fileresu);
6496: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6497: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6498: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6499: }
6500: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6501: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6502: pstamp(ficrespl);
1.203 brouard 6503: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202 brouard 6504: fprintf(ficrespl,"#Age ");
6505: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6506: fprintf(ficrespl,"\n");
1.180 brouard 6507:
6508: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6509:
6510: agebase=ageminpar;
6511: agelim=agemaxpar;
6512:
6513: i1=pow(2,cptcoveff);
6514: if (cptcovn < 1){i1=1;}
6515:
6516: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6517: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6518: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6519: k=k+1;
6520: /* to clean */
1.198 brouard 6521: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200 brouard 6522: fprintf(ficrespl,"#******");
6523: printf("#******");
6524: fprintf(ficlog,"#******");
1.180 brouard 6525: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 6526: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6527: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6528: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6529: }
6530: fprintf(ficrespl,"******\n");
6531: printf("******\n");
6532: fprintf(ficlog,"******\n");
6533:
6534: fprintf(ficrespl,"#Age ");
6535: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 6536: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6537: }
1.203 brouard 6538: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6539: fprintf(ficrespl,"Total Years_to_converge\n");
1.180 brouard 6540:
6541: for (age=agebase; age<=agelim; age++){
6542: /* for (age=agebase; age<=agebase; age++){ */
1.203 brouard 6543: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
1.180 brouard 6544: fprintf(ficrespl,"%.0f ",age );
6545: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6546: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203 brouard 6547: tot=0.;
6548: for(i=1; i<=nlstate;i++){
6549: tot += prlim[i][i];
1.180 brouard 6550: fprintf(ficrespl," %.5f", prlim[i][i]);
1.203 brouard 6551: }
6552: fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
1.180 brouard 6553: } /* Age */
6554: /* was end of cptcod */
6555: } /* cptcov */
1.184 brouard 6556: return 0;
1.180 brouard 6557: }
6558:
6559: int hPijx(double *p, int bage, int fage){
6560: /*------------- h Pij x at various ages ------------*/
6561:
6562: int stepsize;
6563: int agelim;
6564: int hstepm;
6565: int nhstepm;
6566: int h, i, i1, j, k;
6567:
6568: double agedeb;
6569: double ***p3mat;
6570:
1.201 brouard 6571: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
1.180 brouard 6572: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6573: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6574: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6575: }
6576: printf("Computing pij: result on file '%s' \n", filerespij);
6577: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6578:
6579: stepsize=(int) (stepm+YEARM-1)/YEARM;
6580: /*if (stepm<=24) stepsize=2;*/
6581:
6582: agelim=AGESUP;
6583: hstepm=stepsize*YEARM; /* Every year of age */
6584: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6585:
6586: /* hstepm=1; aff par mois*/
6587: pstamp(ficrespij);
6588: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6589: i1= pow(2,cptcoveff);
1.183 brouard 6590: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6591: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6592: /* k=k+1; */
6593: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6594: fprintf(ficrespij,"\n#****** ");
6595: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6596: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183 brouard 6597: fprintf(ficrespij,"******\n");
6598:
6599: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6600: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6601: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6602:
6603: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6604:
1.183 brouard 6605: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6606: oldm=oldms;savm=savms;
6607: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6608: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6609: for(i=1; i<=nlstate;i++)
6610: for(j=1; j<=nlstate+ndeath;j++)
6611: fprintf(ficrespij," %1d-%1d",i,j);
6612: fprintf(ficrespij,"\n");
6613: for (h=0; h<=nhstepm; h++){
6614: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6615: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6616: for(i=1; i<=nlstate;i++)
6617: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6618: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6619: fprintf(ficrespij,"\n");
6620: }
1.183 brouard 6621: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6622: fprintf(ficrespij,"\n");
6623: }
1.180 brouard 6624: /*}*/
6625: }
1.184 brouard 6626: return 0;
1.180 brouard 6627: }
6628:
6629:
1.136 brouard 6630: /***********************************************/
6631: /**************** Main Program *****************/
6632: /***********************************************/
6633:
6634: int main(int argc, char *argv[])
6635: {
6636: #ifdef GSL
6637: const gsl_multimin_fminimizer_type *T;
6638: size_t iteri = 0, it;
6639: int rval = GSL_CONTINUE;
6640: int status = GSL_SUCCESS;
6641: double ssval;
6642: #endif
6643: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6644: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.203 brouard 6645: int ncvyearnp=0;
6646: int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
1.164 brouard 6647: int jj, ll, li, lj, lk;
1.136 brouard 6648: int numlinepar=0; /* Current linenumber of parameter file */
1.197 brouard 6649: int num_filled;
1.136 brouard 6650: int itimes;
6651: int NDIM=2;
6652: int vpopbased=0;
6653:
1.164 brouard 6654: char ca[32], cb[32];
1.136 brouard 6655: /* FILE *fichtm; *//* Html File */
6656: /* FILE *ficgp;*/ /*Gnuplot File */
6657: struct stat info;
1.191 brouard 6658: double agedeb=0.;
1.194 brouard 6659:
6660: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6661:
1.165 brouard 6662: double fret;
1.191 brouard 6663: double dum=0.; /* Dummy variable */
1.136 brouard 6664: double ***p3mat;
6665: double ***mobaverage;
1.164 brouard 6666:
6667: char line[MAXLINE];
1.197 brouard 6668: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6669:
6670: char model[MAXLINE], modeltemp[MAXLINE];
1.136 brouard 6671: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6672: char *tok, *val; /* pathtot */
1.136 brouard 6673: int firstobs=1, lastobs=10;
1.195 brouard 6674: int c, h , cpt, c2;
1.191 brouard 6675: int jl=0;
6676: int i1, j1, jk, stepsize=0;
1.194 brouard 6677: int count=0;
6678:
1.164 brouard 6679: int *tab;
1.136 brouard 6680: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6681: int mobilav=0,popforecast=0;
1.191 brouard 6682: int hstepm=0, nhstepm=0;
1.136 brouard 6683: int agemortsup;
6684: float sumlpop=0.;
6685: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6686: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6687:
1.191 brouard 6688: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6689: double ftolpl=FTOL;
6690: double **prlim;
6691: double ***param; /* Matrix of parameters */
6692: double *p;
6693: double **matcov; /* Matrix of covariance */
1.203 brouard 6694: double **hess; /* Hessian matrix */
1.136 brouard 6695: double ***delti3; /* Scale */
6696: double *delti; /* Scale */
6697: double ***eij, ***vareij;
6698: double **varpl; /* Variances of prevalence limits by age */
6699: double *epj, vepp;
1.164 brouard 6700:
1.136 brouard 6701: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6702: double **ximort;
1.145 brouard 6703: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6704: int *dcwave;
6705:
1.164 brouard 6706: char z[1]="c";
1.136 brouard 6707:
6708: /*char *strt;*/
6709: char strtend[80];
1.126 brouard 6710:
1.164 brouard 6711:
1.126 brouard 6712: /* setlocale (LC_ALL, ""); */
6713: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6714: /* textdomain (PACKAGE); */
6715: /* setlocale (LC_CTYPE, ""); */
6716: /* setlocale (LC_MESSAGES, ""); */
6717:
6718: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6719: rstart_time = time(NULL);
6720: /* (void) gettimeofday(&start_time,&tzp);*/
6721: start_time = *localtime(&rstart_time);
1.126 brouard 6722: curr_time=start_time;
1.157 brouard 6723: /*tml = *localtime(&start_time.tm_sec);*/
6724: /* strcpy(strstart,asctime(&tml)); */
6725: strcpy(strstart,asctime(&start_time));
1.126 brouard 6726:
6727: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6728: /* tp.tm_sec = tp.tm_sec +86400; */
6729: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6730: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6731: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6732: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6733: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6734: /* strt=asctime(&tmg); */
6735: /* printf("Time(after) =%s",strstart); */
6736: /* (void) time (&time_value);
6737: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6738: * tm = *localtime(&time_value);
6739: * strstart=asctime(&tm);
6740: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6741: */
6742:
6743: nberr=0; /* Number of errors and warnings */
6744: nbwarn=0;
1.184 brouard 6745: #ifdef WIN32
6746: _getcwd(pathcd, size);
6747: #else
1.126 brouard 6748: getcwd(pathcd, size);
1.184 brouard 6749: #endif
1.191 brouard 6750: syscompilerinfo(0);
1.196 brouard 6751: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126 brouard 6752: if(argc <=1){
6753: printf("\nEnter the parameter file name: ");
1.205 ! brouard 6754: if(!fgets(pathr,FILENAMELENGTH,stdin)){
! 6755: printf("ERROR Empty parameter file name\n");
! 6756: goto end;
! 6757: }
1.126 brouard 6758: i=strlen(pathr);
6759: if(pathr[i-1]=='\n')
6760: pathr[i-1]='\0';
1.156 brouard 6761: i=strlen(pathr);
1.205 ! brouard 6762: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156 brouard 6763: pathr[i-1]='\0';
1.205 ! brouard 6764: }
! 6765: i=strlen(pathr);
! 6766: if( i==0 ){
! 6767: printf("ERROR Empty parameter file name\n");
! 6768: goto end;
! 6769: }
! 6770: for (tok = pathr; tok != NULL; ){
1.126 brouard 6771: printf("Pathr |%s|\n",pathr);
6772: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6773: printf("val= |%s| pathr=%s\n",val,pathr);
6774: strcpy (pathtot, val);
6775: if(pathr[0] == '\0') break; /* Dirty */
6776: }
6777: }
6778: else{
6779: strcpy(pathtot,argv[1]);
6780: }
6781: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6782: /*cygwin_split_path(pathtot,path,optionfile);
6783: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6784: /* cutv(path,optionfile,pathtot,'\\');*/
6785:
6786: /* Split argv[0], imach program to get pathimach */
6787: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6788: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6789: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6790: /* strcpy(pathimach,argv[0]); */
6791: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6792: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6793: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6794: #ifdef WIN32
6795: _chdir(path); /* Can be a relative path */
6796: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6797: #else
1.126 brouard 6798: chdir(path); /* Can be a relative path */
1.184 brouard 6799: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6800: #endif
6801: printf("Current directory %s!\n",pathcd);
1.126 brouard 6802: strcpy(command,"mkdir ");
6803: strcat(command,optionfilefiname);
6804: if((outcmd=system(command)) != 0){
1.169 brouard 6805: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6806: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6807: /* fclose(ficlog); */
6808: /* exit(1); */
6809: }
6810: /* if((imk=mkdir(optionfilefiname))<0){ */
6811: /* perror("mkdir"); */
6812: /* } */
6813:
6814: /*-------- arguments in the command line --------*/
6815:
1.186 brouard 6816: /* Main Log file */
1.126 brouard 6817: strcat(filelog, optionfilefiname);
6818: strcat(filelog,".log"); /* */
6819: if((ficlog=fopen(filelog,"w"))==NULL) {
6820: printf("Problem with logfile %s\n",filelog);
6821: goto end;
6822: }
6823: fprintf(ficlog,"Log filename:%s\n",filelog);
1.197 brouard 6824: fprintf(ficlog,"Version %s %s",version,fullversion);
1.126 brouard 6825: fprintf(ficlog,"\nEnter the parameter file name: \n");
6826: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6827: path=%s \n\
6828: optionfile=%s\n\
6829: optionfilext=%s\n\
1.156 brouard 6830: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6831:
1.197 brouard 6832: syscompilerinfo(1);
1.167 brouard 6833:
1.126 brouard 6834: printf("Local time (at start):%s",strstart);
6835: fprintf(ficlog,"Local time (at start): %s",strstart);
6836: fflush(ficlog);
6837: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6838: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6839:
6840: /* */
6841: strcpy(fileres,"r");
6842: strcat(fileres, optionfilefiname);
1.201 brouard 6843: strcat(fileresu, optionfilefiname); /* Without r in front */
1.126 brouard 6844: strcat(fileres,".txt"); /* Other files have txt extension */
1.201 brouard 6845: strcat(fileresu,".txt"); /* Other files have txt extension */
1.126 brouard 6846:
1.186 brouard 6847: /* Main ---------arguments file --------*/
1.126 brouard 6848:
6849: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6850: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6851: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6852: fflush(ficlog);
1.149 brouard 6853: /* goto end; */
6854: exit(70);
1.126 brouard 6855: }
6856:
6857:
6858:
6859: strcpy(filereso,"o");
1.201 brouard 6860: strcat(filereso,fileresu);
1.126 brouard 6861: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6862: printf("Problem with Output resultfile: %s\n", filereso);
6863: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6864: fflush(ficlog);
6865: goto end;
6866: }
6867:
6868: /* Reads comments: lines beginning with '#' */
6869: numlinepar=0;
1.197 brouard 6870:
6871: /* First parameter line */
6872: while(fgets(line, MAXLINE, ficpar)) {
6873: /* If line starts with a # it is a comment */
6874: if (line[0] == '#') {
6875: numlinepar++;
6876: fputs(line,stdout);
6877: fputs(line,ficparo);
6878: fputs(line,ficlog);
6879: continue;
6880: }else
6881: break;
6882: }
6883: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6884: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6885: if (num_filled != 5) {
6886: printf("Should be 5 parameters\n");
6887: }
1.126 brouard 6888: numlinepar++;
1.197 brouard 6889: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6890: }
6891: /* Second parameter line */
6892: while(fgets(line, MAXLINE, ficpar)) {
6893: /* If line starts with a # it is a comment */
6894: if (line[0] == '#') {
6895: numlinepar++;
6896: fputs(line,stdout);
6897: fputs(line,ficparo);
6898: fputs(line,ficlog);
6899: continue;
6900: }else
6901: break;
6902: }
6903: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6904: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
6905: if (num_filled != 8) {
6906: printf("Not 8\n");
6907: }
6908: 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);
1.126 brouard 6909: }
1.203 brouard 6910: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
6911: ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197 brouard 6912: /* Third parameter line */
6913: while(fgets(line, MAXLINE, ficpar)) {
6914: /* If line starts with a # it is a comment */
6915: if (line[0] == '#') {
6916: numlinepar++;
6917: fputs(line,stdout);
6918: fputs(line,ficparo);
6919: fputs(line,ficlog);
6920: continue;
6921: }else
6922: break;
6923: }
1.201 brouard 6924: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
6925: if (num_filled == 0)
6926: model[0]='\0';
6927: else if (num_filled != 1){
1.197 brouard 6928: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6929: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6930: model[0]='\0';
6931: goto end;
6932: }
6933: else{
6934: if (model[0]=='+'){
6935: for(i=1; i<=strlen(model);i++)
6936: modeltemp[i-1]=model[i];
1.201 brouard 6937: strcpy(model,modeltemp);
1.197 brouard 6938: }
6939: }
1.199 brouard 6940: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203 brouard 6941: printf("model=1+age+%s\n",model);fflush(stdout);
1.197 brouard 6942: }
6943: /* 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); */
6944: /* numlinepar=numlinepar+3; /\* In general *\/ */
6945: /* 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); */
1.203 brouard 6946: 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);
6947: 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);
1.126 brouard 6948: fflush(ficlog);
1.190 brouard 6949: /* if(model[0]=='#'|| model[0]== '\0'){ */
6950: if(model[0]=='#'){
1.187 brouard 6951: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6952: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6953: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6954: if(mle != -1){
6955: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6956: exit(1);
6957: }
6958: }
1.126 brouard 6959: while((c=getc(ficpar))=='#' && c!= EOF){
6960: ungetc(c,ficpar);
6961: fgets(line, MAXLINE, ficpar);
6962: numlinepar++;
1.195 brouard 6963: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
6964: z[0]=line[1];
6965: }
6966: /* printf("****line [1] = %c \n",line[1]); */
1.141 brouard 6967: fputs(line, stdout);
6968: //puts(line);
1.126 brouard 6969: fputs(line,ficparo);
6970: fputs(line,ficlog);
6971: }
6972: ungetc(c,ficpar);
6973:
6974:
1.145 brouard 6975: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6976: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6977: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6978: v1+v2*age+v2*v3 makes cptcovn = 3
6979: */
6980: if (strlen(model)>1)
1.187 brouard 6981: 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*/
1.145 brouard 6982: else
1.187 brouard 6983: ncovmodel=2; /* Constant and age */
1.133 brouard 6984: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6985: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6986: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6987: 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);
6988: 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);
6989: fflush(stdout);
6990: fclose (ficlog);
6991: goto end;
6992: }
1.126 brouard 6993: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6994: delti=delti3[1][1];
6995: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6996: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6997: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 6998: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6999: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7000: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7001: fclose (ficparo);
7002: fclose (ficlog);
7003: goto end;
7004: exit(0);
7005: }
1.186 brouard 7006: else if(mle==-3) { /* Main Wizard */
1.126 brouard 7007: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 7008: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7009: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7010: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7011: matcov=matrix(1,npar,1,npar);
1.203 brouard 7012: hess=matrix(1,npar,1,npar);
1.126 brouard 7013: }
7014: else{
1.145 brouard 7015: /* Read guessed parameters */
1.126 brouard 7016: /* Reads comments: lines beginning with '#' */
7017: while((c=getc(ficpar))=='#' && c!= EOF){
7018: ungetc(c,ficpar);
7019: fgets(line, MAXLINE, ficpar);
7020: numlinepar++;
1.141 brouard 7021: fputs(line,stdout);
1.126 brouard 7022: fputs(line,ficparo);
7023: fputs(line,ficlog);
7024: }
7025: ungetc(c,ficpar);
7026:
7027: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7028: for(i=1; i <=nlstate; i++){
7029: j=0;
7030: for(jj=1; jj <=nlstate+ndeath; jj++){
7031: if(jj==i) continue;
7032: j++;
7033: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 7034: if ((i1 != i) || (j1 != jj)){
1.126 brouard 7035: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7036: It might be a problem of design; if ncovcol and the model are correct\n \
7037: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7038: exit(1);
7039: }
7040: fprintf(ficparo,"%1d%1d",i1,j1);
7041: if(mle==1)
1.193 brouard 7042: printf("%1d%1d",i,jj);
7043: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 7044: for(k=1; k<=ncovmodel;k++){
7045: fscanf(ficpar," %lf",¶m[i][j][k]);
7046: if(mle==1){
7047: printf(" %lf",param[i][j][k]);
7048: fprintf(ficlog," %lf",param[i][j][k]);
7049: }
7050: else
7051: fprintf(ficlog," %lf",param[i][j][k]);
7052: fprintf(ficparo," %lf",param[i][j][k]);
7053: }
7054: fscanf(ficpar,"\n");
7055: numlinepar++;
7056: if(mle==1)
7057: printf("\n");
7058: fprintf(ficlog,"\n");
7059: fprintf(ficparo,"\n");
7060: }
7061: }
7062: fflush(ficlog);
7063:
1.145 brouard 7064: /* Reads scales values */
1.126 brouard 7065: p=param[1][1];
7066:
7067: /* Reads comments: lines beginning with '#' */
7068: while((c=getc(ficpar))=='#' && c!= EOF){
7069: ungetc(c,ficpar);
7070: fgets(line, MAXLINE, ficpar);
7071: numlinepar++;
1.141 brouard 7072: fputs(line,stdout);
1.126 brouard 7073: fputs(line,ficparo);
7074: fputs(line,ficlog);
7075: }
7076: ungetc(c,ficpar);
7077:
7078: for(i=1; i <=nlstate; i++){
7079: for(j=1; j <=nlstate+ndeath-1; j++){
7080: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 7081: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 7082: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7083: exit(1);
7084: }
7085: printf("%1d%1d",i,j);
7086: fprintf(ficparo,"%1d%1d",i1,j1);
7087: fprintf(ficlog,"%1d%1d",i1,j1);
7088: for(k=1; k<=ncovmodel;k++){
7089: fscanf(ficpar,"%le",&delti3[i][j][k]);
7090: printf(" %le",delti3[i][j][k]);
7091: fprintf(ficparo," %le",delti3[i][j][k]);
7092: fprintf(ficlog," %le",delti3[i][j][k]);
7093: }
7094: fscanf(ficpar,"\n");
7095: numlinepar++;
7096: printf("\n");
7097: fprintf(ficparo,"\n");
7098: fprintf(ficlog,"\n");
7099: }
7100: }
7101: fflush(ficlog);
7102:
1.145 brouard 7103: /* Reads covariance matrix */
1.126 brouard 7104: delti=delti3[1][1];
7105:
7106:
7107: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7108:
7109: /* Reads comments: lines beginning with '#' */
7110: while((c=getc(ficpar))=='#' && c!= EOF){
7111: ungetc(c,ficpar);
7112: fgets(line, MAXLINE, ficpar);
7113: numlinepar++;
1.141 brouard 7114: fputs(line,stdout);
1.126 brouard 7115: fputs(line,ficparo);
7116: fputs(line,ficlog);
7117: }
7118: ungetc(c,ficpar);
7119:
7120: matcov=matrix(1,npar,1,npar);
1.203 brouard 7121: hess=matrix(1,npar,1,npar);
1.131 brouard 7122: for(i=1; i <=npar; i++)
7123: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7124:
1.194 brouard 7125: /* Scans npar lines */
1.126 brouard 7126: for(i=1; i <=npar; i++){
1.194 brouard 7127: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7128: if(count != 3){
7129: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7130: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7131: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7132: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7133: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7134: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7135: exit(1);
7136: }else
1.126 brouard 7137: if(mle==1)
1.194 brouard 7138: printf("%1d%1d%1d",i1,j1,jk);
7139: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7140: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 7141: for(j=1; j <=i; j++){
7142: fscanf(ficpar," %le",&matcov[i][j]);
7143: if(mle==1){
7144: printf(" %.5le",matcov[i][j]);
7145: }
7146: fprintf(ficlog," %.5le",matcov[i][j]);
7147: fprintf(ficparo," %.5le",matcov[i][j]);
7148: }
7149: fscanf(ficpar,"\n");
7150: numlinepar++;
7151: if(mle==1)
7152: printf("\n");
7153: fprintf(ficlog,"\n");
7154: fprintf(ficparo,"\n");
7155: }
1.194 brouard 7156: /* End of read covariance matrix npar lines */
1.126 brouard 7157: for(i=1; i <=npar; i++)
7158: for(j=i+1;j<=npar;j++)
7159: matcov[i][j]=matcov[j][i];
7160:
7161: if(mle==1)
7162: printf("\n");
7163: fprintf(ficlog,"\n");
7164:
7165: fflush(ficlog);
7166:
7167: /*-------- Rewriting parameter file ----------*/
7168: strcpy(rfileres,"r"); /* "Rparameterfile */
7169: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7170: strcat(rfileres,"."); /* */
7171: strcat(rfileres,optionfilext); /* Other files have txt extension */
7172: if((ficres =fopen(rfileres,"w"))==NULL) {
1.201 brouard 7173: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7174: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126 brouard 7175: }
7176: fprintf(ficres,"#%s\n",version);
7177: } /* End of mle != -3 */
7178:
1.186 brouard 7179: /* Main data
7180: */
1.126 brouard 7181: n= lastobs;
7182: num=lvector(1,n);
7183: moisnais=vector(1,n);
7184: annais=vector(1,n);
7185: moisdc=vector(1,n);
7186: andc=vector(1,n);
7187: agedc=vector(1,n);
7188: cod=ivector(1,n);
7189: weight=vector(1,n);
7190: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7191: mint=matrix(1,maxwav,1,n);
7192: anint=matrix(1,maxwav,1,n);
1.131 brouard 7193: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 7194: tab=ivector(1,NCOVMAX);
1.144 brouard 7195: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 7196: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 7197:
1.136 brouard 7198: /* Reads data from file datafile */
7199: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7200: goto end;
7201:
7202: /* Calculation of the number of parameters from char model */
1.137 brouard 7203: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7204: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7205: k=3 V4 Tvar[k=3]= 4 (from V4)
7206: k=2 V1 Tvar[k=2]= 1 (from V1)
7207: k=1 Tvar[1]=2 (from V2)
7208: */
7209: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7210: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7211: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7212: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7213: */
7214: /* For model-covariate k tells which data-covariate to use but
7215: because this model-covariate is a construction we invent a new column
7216: ncovcol + k1
7217: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7218: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 7219: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 7220: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7221: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7222: */
1.145 brouard 7223: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7224: 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
1.141 brouard 7225: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7226: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 7227: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 7228: 4 covariates (3 plus signs)
7229: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7230: */
1.136 brouard 7231:
1.186 brouard 7232: /* Main decodemodel */
7233:
1.187 brouard 7234:
1.136 brouard 7235: if(decodemodel(model, lastobs) == 1)
7236: goto end;
7237:
1.137 brouard 7238: if((double)(lastobs-imx)/(double)imx > 1.10){
7239: nbwarn++;
7240: 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);
7241: 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);
7242: }
1.136 brouard 7243: /* if(mle==1){*/
1.137 brouard 7244: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7245: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 7246: }
7247:
7248: /*-calculation of age at interview from date of interview and age at death -*/
7249: agev=matrix(1,maxwav,1,imx);
7250:
7251: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7252: goto end;
7253:
1.126 brouard 7254:
1.136 brouard 7255: agegomp=(int)agemin;
7256: free_vector(moisnais,1,n);
7257: free_vector(annais,1,n);
1.126 brouard 7258: /* free_matrix(mint,1,maxwav,1,n);
7259: free_matrix(anint,1,maxwav,1,n);*/
7260: free_vector(moisdc,1,n);
7261: free_vector(andc,1,n);
1.145 brouard 7262: /* */
7263:
1.126 brouard 7264: wav=ivector(1,imx);
7265: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7266: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7267: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7268:
7269: /* Concatenates waves */
7270: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 7271: /* */
7272:
1.126 brouard 7273: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7274:
7275: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7276: ncodemax[1]=1;
1.145 brouard 7277: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 7278: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 7279: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 7280: /* Nbcode gives the value of the lth modality of jth covariate, in
7281: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7282: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 7283:
1.200 brouard 7284: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198 brouard 7285: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186 brouard 7286: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 7287: h=0;
7288:
7289:
7290: /*if (cptcovn > 0) */
1.126 brouard 7291:
1.145 brouard 7292:
1.126 brouard 7293: m=pow(2,cptcoveff);
7294:
1.144 brouard 7295: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 7296: * For k=4 covariates, h goes from 1 to 2**k
7297: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
7298: * h\k 1 2 3 4
1.143 brouard 7299: *______________________________
7300: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7301: * 2 2 1 1 1
7302: * 3 i=2 1 2 1 1
7303: * 4 2 2 1 1
7304: * 5 i=3 1 i=2 1 2 1
7305: * 6 2 1 2 1
7306: * 7 i=4 1 2 2 1
7307: * 8 2 2 2 1
1.197 brouard 7308: * 9 i=5 1 i=3 1 i=2 1 2
7309: * 10 2 1 1 2
7310: * 11 i=6 1 2 1 2
7311: * 12 2 2 1 2
7312: * 13 i=7 1 i=4 1 2 2
7313: * 14 2 1 2 2
7314: * 15 i=8 1 2 2 2
7315: * 16 2 2 2 2
1.143 brouard 7316: */
1.202 brouard 7317: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7318: /* /\* printf("h=%2d ", h); *\/ */
7319: /* /\* for(k=1; k <=10; k++){ *\/ */
7320: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7321: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7322: /* /\* } *\/ */
7323: /* /\* printf("\n"); *\/ */
7324: /* } */
1.197 brouard 7325: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7326: /* 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 *\/ */
7327: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7328: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7329: /* h++; */
7330: /* if (h>m) */
7331: /* h=1; */
7332: /* codtab[h][k]=j; */
7333: /* /\* codtab[12][3]=1; *\/ */
7334: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7335: /* /\* 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]]); *\/ */
7336: /* } */
7337: /* } */
7338: /* } */
7339: /* } */
1.126 brouard 7340: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7341: codtab[1][2]=1;codtab[2][2]=2; */
1.197 brouard 7342: /* for(i=1; i <=m ;i++){ */
7343: /* for(k=1; k <=cptcovn; k++){ */
7344: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7345: /* } */
7346: /* printf("\n"); */
7347: /* } */
7348: /* scanf("%d",i);*/
1.145 brouard 7349:
7350: free_ivector(Ndum,-1,NCOVMAX);
7351:
7352:
1.126 brouard 7353:
1.186 brouard 7354: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 7355: strcpy(optionfilegnuplot,optionfilefiname);
7356: if(mle==-3)
1.201 brouard 7357: strcat(optionfilegnuplot,"-MORT_");
1.126 brouard 7358: strcat(optionfilegnuplot,".gp");
7359:
7360: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7361: printf("Problem with file %s",optionfilegnuplot);
7362: }
7363: else{
1.204 brouard 7364: fprintf(ficgp,"\n# IMaCh-%s\n", version);
1.126 brouard 7365: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 7366: //fprintf(ficgp,"set missing 'NaNq'\n");
7367: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 7368: }
7369: /* fclose(ficgp);*/
1.186 brouard 7370:
7371:
7372: /* Initialisation of --------- index.htm --------*/
1.126 brouard 7373:
7374: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7375: if(mle==-3)
1.201 brouard 7376: strcat(optionfilehtm,"-MORT_");
1.126 brouard 7377: strcat(optionfilehtm,".htm");
7378: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 7379: printf("Problem with %s \n",optionfilehtm);
7380: exit(0);
1.126 brouard 7381: }
7382:
7383: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7384: strcat(optionfilehtmcov,"-cov.htm");
7385: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7386: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7387: }
7388: else{
7389: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7390: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7391: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126 brouard 7392: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7393: }
7394:
1.204 brouard 7395: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br> \
7396: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7397: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126 brouard 7398: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7399: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126 brouard 7400: \n\
7401: <hr size=\"2\" color=\"#EC5E5E\">\
7402: <ul><li><h4>Parameter files</h4>\n\
7403: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7404: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7405: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7406: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7407: - Date and time at start: %s</ul>\n",\
7408: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7409: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7410: fileres,fileres,\
7411: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7412: fflush(fichtm);
7413:
7414: strcpy(pathr,path);
7415: strcat(pathr,optionfilefiname);
1.184 brouard 7416: #ifdef WIN32
7417: _chdir(optionfilefiname); /* Move to directory named optionfile */
7418: #else
1.126 brouard 7419: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 7420: #endif
7421:
1.126 brouard 7422:
7423: /* Calculates basic frequencies. Computes observed prevalence at single age
7424: and prints on file fileres'p'. */
7425: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7426:
7427: fprintf(fichtm,"\n");
7428: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7429: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7430: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7431: imx,agemin,agemax,jmin,jmax,jmean);
7432: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7433: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7434: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7435: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7436: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7437:
7438:
7439: /* For Powell, parameters are in a vector p[] starting at p[1]
7440: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7441: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7442:
7443: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 7444: /* For mortality only */
1.126 brouard 7445: if (mle==-3){
1.136 brouard 7446: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 7447: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 7448: cens=ivector(1,n);
7449: ageexmed=vector(1,n);
7450: agecens=vector(1,n);
7451: dcwave=ivector(1,n);
7452:
7453: for (i=1; i<=imx; i++){
7454: dcwave[i]=-1;
7455: for (m=firstpass; m<=lastpass; m++)
7456: if (s[m][i]>nlstate) {
7457: dcwave[i]=m;
7458: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7459: break;
7460: }
7461: }
7462:
7463: for (i=1; i<=imx; i++) {
7464: if (wav[i]>0){
7465: ageexmed[i]=agev[mw[1][i]][i];
7466: j=wav[i];
7467: agecens[i]=1.;
7468:
7469: if (ageexmed[i]> 1 && wav[i] > 0){
7470: agecens[i]=agev[mw[j][i]][i];
7471: cens[i]= 1;
7472: }else if (ageexmed[i]< 1)
7473: cens[i]= -1;
7474: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7475: cens[i]=0 ;
7476: }
7477: else cens[i]=-1;
7478: }
7479:
7480: for (i=1;i<=NDIM;i++) {
7481: for (j=1;j<=NDIM;j++)
7482: ximort[i][j]=(i == j ? 1.0 : 0.0);
7483: }
7484:
1.145 brouard 7485: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7486: /*printf("%lf %lf", p[1], p[2]);*/
7487:
7488:
1.136 brouard 7489: #ifdef GSL
7490: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7491: #else
1.126 brouard 7492: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7493: #endif
1.201 brouard 7494: strcpy(filerespow,"POW-MORT_");
7495: strcat(filerespow,fileresu);
1.126 brouard 7496: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7497: printf("Problem with resultfile: %s\n", filerespow);
7498: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7499: }
1.136 brouard 7500: #ifdef GSL
7501: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7502: #else
1.126 brouard 7503: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7504: #endif
1.126 brouard 7505: /* for (i=1;i<=nlstate;i++)
7506: for(j=1;j<=nlstate+ndeath;j++)
7507: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7508: */
7509: fprintf(ficrespow,"\n");
1.136 brouard 7510: #ifdef GSL
7511: /* gsl starts here */
7512: T = gsl_multimin_fminimizer_nmsimplex;
7513: gsl_multimin_fminimizer *sfm = NULL;
7514: gsl_vector *ss, *x;
7515: gsl_multimin_function minex_func;
7516:
7517: /* Initial vertex size vector */
7518: ss = gsl_vector_alloc (NDIM);
7519:
7520: if (ss == NULL){
7521: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7522: }
7523: /* Set all step sizes to 1 */
7524: gsl_vector_set_all (ss, 0.001);
7525:
7526: /* Starting point */
1.126 brouard 7527:
1.136 brouard 7528: x = gsl_vector_alloc (NDIM);
7529:
7530: if (x == NULL){
7531: gsl_vector_free(ss);
7532: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7533: }
7534:
7535: /* Initialize method and iterate */
7536: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7537: /* gsl_vector_set(x, 0, 0.0268); */
7538: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7539: gsl_vector_set(x, 0, p[1]);
7540: gsl_vector_set(x, 1, p[2]);
7541:
7542: minex_func.f = &gompertz_f;
7543: minex_func.n = NDIM;
7544: minex_func.params = (void *)&p; /* ??? */
7545:
7546: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7547: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7548:
7549: printf("Iterations beginning .....\n\n");
7550: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7551:
7552: iteri=0;
7553: while (rval == GSL_CONTINUE){
7554: iteri++;
7555: status = gsl_multimin_fminimizer_iterate(sfm);
7556:
7557: if (status) printf("error: %s\n", gsl_strerror (status));
7558: fflush(0);
7559:
7560: if (status)
7561: break;
7562:
7563: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7564: ssval = gsl_multimin_fminimizer_size (sfm);
7565:
7566: if (rval == GSL_SUCCESS)
7567: printf ("converged to a local maximum at\n");
7568:
7569: printf("%5d ", iteri);
7570: for (it = 0; it < NDIM; it++){
7571: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7572: }
7573: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7574: }
7575:
7576: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7577:
7578: gsl_vector_free(x); /* initial values */
7579: gsl_vector_free(ss); /* inital step size */
7580: for (it=0; it<NDIM; it++){
7581: p[it+1]=gsl_vector_get(sfm->x,it);
7582: fprintf(ficrespow," %.12lf", p[it]);
7583: }
7584: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7585: #endif
7586: #ifdef POWELL
7587: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7588: #endif
1.126 brouard 7589: fclose(ficrespow);
7590:
1.203 brouard 7591: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
1.126 brouard 7592:
7593: for(i=1; i <=NDIM; i++)
7594: for(j=i+1;j<=NDIM;j++)
7595: matcov[i][j]=matcov[j][i];
7596:
7597: printf("\nCovariance matrix\n ");
1.203 brouard 7598: fprintf(ficlog,"\nCovariance matrix\n ");
1.126 brouard 7599: for(i=1; i <=NDIM; i++) {
7600: for(j=1;j<=NDIM;j++){
7601: printf("%f ",matcov[i][j]);
1.203 brouard 7602: fprintf(ficlog,"%f ",matcov[i][j]);
1.126 brouard 7603: }
1.203 brouard 7604: printf("\n "); fprintf(ficlog,"\n ");
1.126 brouard 7605: }
7606:
7607: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7608: for (i=1;i<=NDIM;i++) {
1.126 brouard 7609: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7610: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7611: }
1.126 brouard 7612: lsurv=vector(1,AGESUP);
7613: lpop=vector(1,AGESUP);
7614: tpop=vector(1,AGESUP);
7615: lsurv[agegomp]=100000;
7616:
7617: for (k=agegomp;k<=AGESUP;k++) {
7618: agemortsup=k;
7619: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7620: }
7621:
7622: for (k=agegomp;k<agemortsup;k++)
7623: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7624:
7625: for (k=agegomp;k<agemortsup;k++){
7626: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7627: sumlpop=sumlpop+lpop[k];
7628: }
7629:
7630: tpop[agegomp]=sumlpop;
7631: for (k=agegomp;k<(agemortsup-3);k++){
7632: /* tpop[k+1]=2;*/
7633: tpop[k+1]=tpop[k]-lpop[k];
7634: }
7635:
7636:
7637: printf("\nAge lx qx dx Lx Tx e(x)\n");
7638: for (k=agegomp;k<(agemortsup-2);k++)
7639: 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]);
7640:
7641:
7642: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7643: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7644: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7645: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7646: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7647: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7648: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7649: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7650: }else
1.201 brouard 7651: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7652: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126 brouard 7653: stepm, weightopt,\
7654: model,imx,p,matcov,agemortsup);
7655:
7656: free_vector(lsurv,1,AGESUP);
7657: free_vector(lpop,1,AGESUP);
7658: free_vector(tpop,1,AGESUP);
1.136 brouard 7659: #ifdef GSL
7660: free_ivector(cens,1,n);
7661: free_vector(agecens,1,n);
7662: free_ivector(dcwave,1,n);
7663: free_matrix(ximort,1,NDIM,1,NDIM);
7664: #endif
1.186 brouard 7665: } /* Endof if mle==-3 mortality only */
1.205 ! brouard 7666: /* Standard */
! 7667: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
! 7668: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
! 7669: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132 brouard 7670: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7671: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7672: for (k=1; k<=npar;k++)
7673: printf(" %d %8.5f",k,p[k]);
7674: printf("\n");
1.205 ! brouard 7675: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
! 7676: /* mlikeli uses func not funcone */
! 7677: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
! 7678: }
! 7679: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
! 7680: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
! 7681: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
! 7682: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
! 7683: }
! 7684: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126 brouard 7685: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7686: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7687: for (k=1; k<=npar;k++)
7688: printf(" %d %8.5f",k,p[k]);
7689: printf("\n");
7690:
7691: /*--------- results files --------------*/
1.192 brouard 7692: 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);
1.126 brouard 7693:
7694:
7695: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7696: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7697: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7698: for(i=1,jk=1; i <=nlstate; i++){
7699: for(k=1; k <=(nlstate+ndeath); k++){
7700: if (k != i) {
7701: printf("%d%d ",i,k);
7702: fprintf(ficlog,"%d%d ",i,k);
7703: fprintf(ficres,"%1d%1d ",i,k);
7704: for(j=1; j <=ncovmodel; j++){
1.190 brouard 7705: printf("%12.7f ",p[jk]);
7706: fprintf(ficlog,"%12.7f ",p[jk]);
7707: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 7708: jk++;
7709: }
7710: printf("\n");
7711: fprintf(ficlog,"\n");
7712: fprintf(ficres,"\n");
7713: }
7714: }
7715: }
1.203 brouard 7716: if(mle != 0){
7717: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126 brouard 7718: ftolhess=ftol; /* Usually correct */
1.203 brouard 7719: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
7720: 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");
7721: 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");
7722: for(i=1,jk=1; i <=nlstate; i++){
7723: for(k=1; k <=(nlstate+ndeath); k++){
7724: if (k != i) {
7725: printf("%d%d ",i,k);
7726: fprintf(ficlog,"%d%d ",i,k);
7727: for(j=1; j <=ncovmodel; j++){
7728: 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]));
7729: 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]));
7730: jk++;
7731: }
7732: printf("\n");
7733: fprintf(ficlog,"\n");
1.193 brouard 7734: }
7735: }
7736: }
1.203 brouard 7737: } /* end of hesscov and Wald tests */
1.193 brouard 7738:
1.203 brouard 7739: /* */
1.126 brouard 7740: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7741: printf("# Scales (for hessian or gradient estimation)\n");
7742: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7743: for(i=1,jk=1; i <=nlstate; i++){
7744: for(j=1; j <=nlstate+ndeath; j++){
7745: if (j!=i) {
7746: fprintf(ficres,"%1d%1d",i,j);
7747: printf("%1d%1d",i,j);
7748: fprintf(ficlog,"%1d%1d",i,j);
7749: for(k=1; k<=ncovmodel;k++){
7750: printf(" %.5e",delti[jk]);
7751: fprintf(ficlog," %.5e",delti[jk]);
7752: fprintf(ficres," %.5e",delti[jk]);
7753: jk++;
7754: }
7755: printf("\n");
7756: fprintf(ficlog,"\n");
7757: fprintf(ficres,"\n");
7758: }
7759: }
7760: }
7761:
7762: 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");
1.203 brouard 7763: if(mle >= 1) /* To big for the screen */
1.126 brouard 7764: 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");
7765: 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");
7766: /* # 121 Var(a12)\n\ */
7767: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7768: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7769: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7770: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7771: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7772: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7773: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7774:
7775:
7776: /* Just to have a covariance matrix which will be more understandable
7777: even is we still don't want to manage dictionary of variables
7778: */
7779: for(itimes=1;itimes<=2;itimes++){
7780: jj=0;
7781: for(i=1; i <=nlstate; i++){
7782: for(j=1; j <=nlstate+ndeath; j++){
7783: if(j==i) continue;
7784: for(k=1; k<=ncovmodel;k++){
7785: jj++;
7786: ca[0]= k+'a'-1;ca[1]='\0';
7787: if(itimes==1){
7788: if(mle>=1)
7789: printf("#%1d%1d%d",i,j,k);
7790: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7791: fprintf(ficres,"#%1d%1d%d",i,j,k);
7792: }else{
7793: if(mle>=1)
7794: printf("%1d%1d%d",i,j,k);
7795: fprintf(ficlog,"%1d%1d%d",i,j,k);
7796: fprintf(ficres,"%1d%1d%d",i,j,k);
7797: }
7798: ll=0;
7799: for(li=1;li <=nlstate; li++){
7800: for(lj=1;lj <=nlstate+ndeath; lj++){
7801: if(lj==li) continue;
7802: for(lk=1;lk<=ncovmodel;lk++){
7803: ll++;
7804: if(ll<=jj){
7805: cb[0]= lk +'a'-1;cb[1]='\0';
7806: if(ll<jj){
7807: if(itimes==1){
7808: if(mle>=1)
7809: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7810: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7811: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7812: }else{
7813: if(mle>=1)
7814: printf(" %.5e",matcov[jj][ll]);
7815: fprintf(ficlog," %.5e",matcov[jj][ll]);
7816: fprintf(ficres," %.5e",matcov[jj][ll]);
7817: }
7818: }else{
7819: if(itimes==1){
7820: if(mle>=1)
7821: printf(" Var(%s%1d%1d)",ca,i,j);
7822: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7823: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7824: }else{
7825: if(mle>=1)
1.203 brouard 7826: printf(" %.7e",matcov[jj][ll]);
7827: fprintf(ficlog," %.7e",matcov[jj][ll]);
7828: fprintf(ficres," %.7e",matcov[jj][ll]);
1.126 brouard 7829: }
7830: }
7831: }
7832: } /* end lk */
7833: } /* end lj */
7834: } /* end li */
7835: if(mle>=1)
7836: printf("\n");
7837: fprintf(ficlog,"\n");
7838: fprintf(ficres,"\n");
7839: numlinepar++;
7840: } /* end k*/
7841: } /*end j */
7842: } /* end i */
7843: } /* end itimes */
7844:
7845: fflush(ficlog);
7846: fflush(ficres);
7847:
7848: while((c=getc(ficpar))=='#' && c!= EOF){
7849: ungetc(c,ficpar);
7850: fgets(line, MAXLINE, ficpar);
1.141 brouard 7851: fputs(line,stdout);
1.126 brouard 7852: fputs(line,ficparo);
7853: }
7854: ungetc(c,ficpar);
7855:
7856: estepm=0;
7857: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7858: if (estepm==0 || estepm < stepm) estepm=stepm;
7859: if (fage <= 2) {
7860: bage = ageminpar;
7861: fage = agemaxpar;
7862: }
7863:
7864: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7865: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7866: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7867:
7868: /* Other stuffs, more or less useful */
1.126 brouard 7869: while((c=getc(ficpar))=='#' && c!= EOF){
7870: ungetc(c,ficpar);
7871: fgets(line, MAXLINE, ficpar);
1.141 brouard 7872: fputs(line,stdout);
1.126 brouard 7873: fputs(line,ficparo);
7874: }
7875: ungetc(c,ficpar);
7876:
7877: 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);
7878: 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);
7879: 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);
7880: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7881: 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);
7882:
7883: while((c=getc(ficpar))=='#' && c!= EOF){
7884: ungetc(c,ficpar);
7885: fgets(line, MAXLINE, ficpar);
1.141 brouard 7886: fputs(line,stdout);
1.126 brouard 7887: fputs(line,ficparo);
7888: }
7889: ungetc(c,ficpar);
7890:
7891:
7892: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7893: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7894:
7895: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 7896: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 7897: fprintf(ficparo,"pop_based=%d\n",popbased);
7898: fprintf(ficres,"pop_based=%d\n",popbased);
7899:
7900: while((c=getc(ficpar))=='#' && c!= EOF){
7901: ungetc(c,ficpar);
7902: fgets(line, MAXLINE, ficpar);
1.141 brouard 7903: fputs(line,stdout);
1.126 brouard 7904: fputs(line,ficparo);
7905: }
7906: ungetc(c,ficpar);
7907:
7908: 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);
7909: 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);
7910: 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);
7911: 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);
7912: 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);
7913: /* day and month of proj2 are not used but only year anproj2.*/
7914:
7915:
7916:
1.145 brouard 7917: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7918: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7919:
7920: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7921: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
7922: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7923: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7924: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7925: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7926: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7927: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7928: }else
1.201 brouard 7929: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7930:
1.201 brouard 7931: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126 brouard 7932: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7933: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7934:
7935: /*------------ free_vector -------------*/
7936: /* chdir(path); */
7937:
7938: free_ivector(wav,1,imx);
7939: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7940: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7941: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7942: free_lvector(num,1,n);
7943: free_vector(agedc,1,n);
7944: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7945: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7946: fclose(ficparo);
7947: fclose(ficres);
7948:
7949:
1.186 brouard 7950: /* Other results (useful)*/
7951:
7952:
1.126 brouard 7953: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7954: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7955: prlim=matrix(1,nlstate,1,nlstate);
1.203 brouard 7956: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, ncvyear);
1.126 brouard 7957: fclose(ficrespl);
7958:
1.145 brouard 7959: #ifdef FREEEXIT2
7960: #include "freeexit2.h"
7961: #endif
7962:
1.126 brouard 7963: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7964: /*#include "hpijx.h"*/
7965: hPijx(p, bage, fage);
1.145 brouard 7966: fclose(ficrespij);
1.126 brouard 7967:
1.145 brouard 7968: /*-------------- Variance of one-step probabilities---*/
7969: k=1;
1.126 brouard 7970: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7971:
7972:
7973: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7974: for(i=1;i<=AGESUP;i++)
7975: for(j=1;j<=NCOVMAX;j++)
7976: for(k=1;k<=NCOVMAX;k++)
7977: probs[i][j][k]=0.;
7978:
7979: /*---------- Forecasting ------------------*/
7980: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7981: if(prevfcast==1){
7982: /* if(stepm ==1){*/
1.201 brouard 7983: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126 brouard 7984: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7985: /* } */
7986: /* else{ */
7987: /* erreur=108; */
7988: /* printf("Warning %d!! You can only forecast the prevalences if the optimization\n has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
7989: /* fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
7990: /* } */
7991: }
1.186 brouard 7992:
7993: /* ------ Other prevalence ratios------------ */
1.126 brouard 7994:
1.127 brouard 7995: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7996:
7997: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7998: /* printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d, mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
7999: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8000: */
1.126 brouard 8001:
1.127 brouard 8002: if (mobilav!=0) {
8003: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8004: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8005: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8006: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8007: }
1.126 brouard 8008: }
8009:
8010:
1.127 brouard 8011: /*---------- Health expectancies, no variances ------------*/
8012:
1.201 brouard 8013: strcpy(filerese,"E_");
8014: strcat(filerese,fileresu);
1.126 brouard 8015: if((ficreseij=fopen(filerese,"w"))==NULL) {
8016: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8017: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8018: }
8019: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
8020: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 8021: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8022: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8023:
8024: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 8025: fprintf(ficreseij,"\n#****** ");
8026: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 8027: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127 brouard 8028: }
8029: fprintf(ficreseij,"******\n");
8030:
8031: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8032: oldm=oldms;savm=savms;
8033: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8034:
8035: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8036: /*}*/
1.127 brouard 8037: }
8038: fclose(ficreseij);
8039:
8040:
8041: /*---------- Health expectancies and variances ------------*/
8042:
8043:
1.201 brouard 8044: strcpy(filerest,"T_");
8045: strcat(filerest,fileresu);
1.127 brouard 8046: if((ficrest=fopen(filerest,"w"))==NULL) {
8047: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8048: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8049: }
8050: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
8051: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
8052:
1.126 brouard 8053:
1.201 brouard 8054: strcpy(fileresstde,"STDE_");
8055: strcat(fileresstde,fileresu);
1.126 brouard 8056: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8057: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8058: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8059: }
8060: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8061: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8062:
1.201 brouard 8063: strcpy(filerescve,"CVE_");
8064: strcat(filerescve,fileresu);
1.126 brouard 8065: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8066: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8067: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8068: }
8069: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8070: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8071:
1.201 brouard 8072: strcpy(fileresv,"V_");
8073: strcat(fileresv,fileresu);
1.126 brouard 8074: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8075: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8076: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8077: }
8078: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
8079: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
8080:
1.145 brouard 8081: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8082: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8083:
8084: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8085: fprintf(ficrest,"\n#****** ");
1.126 brouard 8086: for(j=1;j<=cptcoveff;j++)
1.200 brouard 8087: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8088: fprintf(ficrest,"******\n");
8089:
8090: fprintf(ficresstdeij,"\n#****** ");
8091: fprintf(ficrescveij,"\n#****** ");
8092: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 8093: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8094: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8095: }
8096: fprintf(ficresstdeij,"******\n");
8097: fprintf(ficrescveij,"******\n");
8098:
8099: fprintf(ficresvij,"\n#****** ");
8100: for(j=1;j<=cptcoveff;j++)
1.200 brouard 8101: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8102: fprintf(ficresvij,"******\n");
8103:
8104: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8105: oldm=oldms;savm=savms;
1.127 brouard 8106: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 8107: /*
8108: */
8109: /* goto endfree; */
1.126 brouard 8110:
8111: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8112: pstamp(ficrest);
1.145 brouard 8113:
8114:
1.128 brouard 8115: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199 brouard 8116: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161 brouard 8117: cptcod= 0; /* To be deleted */
1.203 brouard 8118: 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 */
1.145 brouard 8119: 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 ");
1.128 brouard 8120: if(vpopbased==1)
8121: 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);
8122: else
8123: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201 brouard 8124: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128 brouard 8125: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8126: fprintf(ficrest,"\n");
1.199 brouard 8127: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128 brouard 8128: epj=vector(1,nlstate+1);
8129: for(age=bage; age <=fage ;age++){
1.203 brouard 8130: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
1.128 brouard 8131: if (vpopbased==1) {
8132: if(mobilav ==0){
8133: for(i=1; i<=nlstate;i++)
8134: prlim[i][i]=probs[(int)age][i][k];
8135: }else{ /* mobilav */
8136: for(i=1; i<=nlstate;i++)
8137: prlim[i][i]=mobaverage[(int)age][i][k];
8138: }
1.126 brouard 8139: }
8140:
1.201 brouard 8141: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.205 ! brouard 8142: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
1.199 brouard 8143: /* printf(" age %4.0f ",age); */
1.128 brouard 8144: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8145: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8146: epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199 brouard 8147: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8148: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128 brouard 8149: }
8150: epj[nlstate+1] +=epj[j];
1.126 brouard 8151: }
1.199 brouard 8152: /* printf(" age %4.0f \n",age); */
1.126 brouard 8153:
1.128 brouard 8154: for(i=1, vepp=0.;i <=nlstate;i++)
8155: for(j=1;j <=nlstate;j++)
8156: vepp += vareij[i][j][(int)age];
8157: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8158: for(j=1;j <=nlstate;j++){
8159: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8160: }
8161: fprintf(ficrest,"\n");
1.126 brouard 8162: }
8163: }
8164: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8165: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8166: free_vector(epj,1,nlstate+1);
1.145 brouard 8167: /*}*/
1.126 brouard 8168: }
8169: free_vector(weight,1,n);
1.145 brouard 8170: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 8171: free_imatrix(s,1,maxwav+1,1,n);
8172: free_matrix(anint,1,maxwav,1,n);
8173: free_matrix(mint,1,maxwav,1,n);
8174: free_ivector(cod,1,n);
8175: free_ivector(tab,1,NCOVMAX);
8176: fclose(ficresstdeij);
8177: fclose(ficrescveij);
8178: fclose(ficresvij);
8179: fclose(ficrest);
8180: fclose(ficpar);
8181:
8182: /*------- Variance of period (stable) prevalence------*/
8183:
1.201 brouard 8184: strcpy(fileresvpl,"VPL_");
8185: strcat(fileresvpl,fileresu);
1.126 brouard 8186: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8187: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8188: exit(0);
8189: }
8190: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
8191:
1.145 brouard 8192: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8193: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8194:
8195: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8196: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 8197: for(j=1;j<=cptcoveff;j++)
1.200 brouard 8198: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8199: fprintf(ficresvpl,"******\n");
8200:
8201: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8202: oldm=oldms;savm=savms;
1.203 brouard 8203: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
1.126 brouard 8204: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8205: /*}*/
1.126 brouard 8206: }
8207:
8208: fclose(ficresvpl);
8209:
8210: /*---------- End : free ----------------*/
8211: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8212: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8213: } /* mle==-3 arrives here for freeing */
1.164 brouard 8214: /* endfree:*/
1.141 brouard 8215: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 8216: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8217: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8218: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8219: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8220: free_matrix(covar,0,NCOVMAX,1,n);
8221: free_matrix(matcov,1,npar,1,npar);
1.203 brouard 8222: free_matrix(hess,1,npar,1,npar);
1.126 brouard 8223: /*free_vector(delti,1,npar);*/
8224: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8225: free_matrix(agev,1,maxwav,1,imx);
8226: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8227:
1.145 brouard 8228: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 8229: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 8230: free_ivector(Tvar,1,NCOVMAX);
8231: free_ivector(Tprod,1,NCOVMAX);
8232: free_ivector(Tvaraff,1,NCOVMAX);
8233: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 8234:
8235: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200 brouard 8236: /* free_imatrix(codtab,1,100,1,10); */
1.126 brouard 8237: fflush(fichtm);
8238: fflush(ficgp);
8239:
8240:
8241: if((nberr >0) || (nbwarn>0)){
8242: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8243: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8244: }else{
8245: printf("End of Imach\n");
8246: fprintf(ficlog,"End of Imach\n");
8247: }
8248: printf("See log file on %s\n",filelog);
8249: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 8250: /*(void) gettimeofday(&end_time,&tzp);*/
8251: rend_time = time(NULL);
8252: end_time = *localtime(&rend_time);
8253: /* tml = *localtime(&end_time.tm_sec); */
8254: strcpy(strtend,asctime(&end_time));
1.126 brouard 8255: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8256: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 8257: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 8258:
1.157 brouard 8259: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8260: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8261: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 8262: /* printf("Total time was %d uSec.\n", total_usecs);*/
8263: /* if(fileappend(fichtm,optionfilehtm)){ */
8264: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8265: fclose(fichtm);
8266: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8267: fclose(fichtmcov);
8268: fclose(ficgp);
8269: fclose(ficlog);
8270: /*------ End -----------*/
8271:
8272:
8273: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 8274: #ifdef WIN32
8275: if (_chdir(pathcd) != 0)
8276: printf("Can't move to directory %s!\n",path);
8277: if(_getcwd(pathcd,MAXLINE) > 0)
8278: #else
1.126 brouard 8279: if(chdir(pathcd) != 0)
1.184 brouard 8280: printf("Can't move to directory %s!\n", path);
8281: if (getcwd(pathcd, MAXLINE) > 0)
8282: #endif
1.126 brouard 8283: printf("Current directory %s!\n",pathcd);
8284: /*strcat(plotcmd,CHARSEPARATOR);*/
8285: sprintf(plotcmd,"gnuplot");
1.157 brouard 8286: #ifdef _WIN32
1.126 brouard 8287: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8288: #endif
8289: if(!stat(plotcmd,&info)){
1.158 brouard 8290: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8291: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 8292: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 8293: }else
8294: strcpy(pplotcmd,plotcmd);
1.157 brouard 8295: #ifdef __unix
1.126 brouard 8296: strcpy(plotcmd,GNUPLOTPROGRAM);
8297: if(!stat(plotcmd,&info)){
1.158 brouard 8298: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8299: }else
8300: strcpy(pplotcmd,plotcmd);
8301: #endif
8302: }else
8303: strcpy(pplotcmd,plotcmd);
8304:
8305: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 8306: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8307:
8308: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 8309: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 8310: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 8311: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 8312: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 8313: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 8314: }
1.158 brouard 8315: printf(" Successful, please wait...");
1.126 brouard 8316: while (z[0] != 'q') {
8317: /* chdir(path); */
1.154 brouard 8318: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 8319: scanf("%s",z);
8320: /* if (z[0] == 'c') system("./imach"); */
8321: if (z[0] == 'e') {
1.158 brouard 8322: #ifdef __APPLE__
1.152 brouard 8323: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 8324: #elif __linux
8325: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 8326: #else
1.152 brouard 8327: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 8328: #endif
8329: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8330: system(pplotcmd);
1.126 brouard 8331: }
8332: else if (z[0] == 'g') system(plotcmd);
8333: else if (z[0] == 'q') exit(0);
8334: }
8335: end:
8336: while (z[0] != 'q') {
1.195 brouard 8337: printf("\nType q for exiting: "); fflush(stdout);
1.126 brouard 8338: scanf("%s",z);
8339: }
8340: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>