Annotation of imach/src/imach.c, revision 1.198
1.198 ! brouard 1: /* $Id: imach.c,v 1.197 2015/09/01 18:24:39 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.198 ! brouard 4: Revision 1.197 2015/09/01 18:24:39 brouard
! 5: *** empty log message ***
! 6:
1.197 brouard 7: Revision 1.196 2015/08/18 23:17:52 brouard
8: Summary: 0.98q5
9:
1.196 brouard 10: Revision 1.195 2015/08/18 16:28:39 brouard
11: Summary: Adding a hack for testing purpose
12:
13: After reading the title, ftol and model lines, if the comment line has
14: a q, starting with #q, the answer at the end of the run is quit. It
15: permits to run test files in batch with ctest. The former workaround was
16: $ echo q | imach foo.imach
17:
1.195 brouard 18: Revision 1.194 2015/08/18 13:32:00 brouard
19: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
20:
1.194 brouard 21: Revision 1.193 2015/08/04 07:17:42 brouard
22: Summary: 0.98q4
23:
1.193 brouard 24: Revision 1.192 2015/07/16 16:49:02 brouard
25: Summary: Fixing some outputs
26:
1.192 brouard 27: Revision 1.191 2015/07/14 10:00:33 brouard
28: Summary: Some fixes
29:
1.191 brouard 30: Revision 1.190 2015/05/05 08:51:13 brouard
31: Summary: Adding digits in output parameters (7 digits instead of 6)
32:
33: Fix 1+age+.
34:
1.190 brouard 35: Revision 1.189 2015/04/30 14:45:16 brouard
36: Summary: 0.98q2
37:
1.189 brouard 38: Revision 1.188 2015/04/30 08:27:53 brouard
39: *** empty log message ***
40:
1.188 brouard 41: Revision 1.187 2015/04/29 09:11:15 brouard
42: *** empty log message ***
43:
1.187 brouard 44: Revision 1.186 2015/04/23 12:01:52 brouard
45: Summary: V1*age is working now, version 0.98q1
46:
47: Some codes had been disabled in order to simplify and Vn*age was
48: working in the optimization phase, ie, giving correct MLE parameters,
49: but, as usual, outputs were not correct and program core dumped.
50:
1.186 brouard 51: Revision 1.185 2015/03/11 13:26:42 brouard
52: Summary: Inclusion of compile and links command line for Intel Compiler
53:
1.185 brouard 54: Revision 1.184 2015/03/11 11:52:39 brouard
55: Summary: Back from Windows 8. Intel Compiler
56:
1.184 brouard 57: Revision 1.183 2015/03/10 20:34:32 brouard
58: Summary: 0.98q0, trying with directest, mnbrak fixed
59:
60: We use directest instead of original Powell test; probably no
61: incidence on the results, but better justifications;
62: We fixed Numerical Recipes mnbrak routine which was wrong and gave
63: wrong results.
64:
1.183 brouard 65: Revision 1.182 2015/02/12 08:19:57 brouard
66: Summary: Trying to keep directest which seems simpler and more general
67: Author: Nicolas Brouard
68:
1.182 brouard 69: Revision 1.181 2015/02/11 23:22:24 brouard
70: Summary: Comments on Powell added
71:
72: Author:
73:
1.181 brouard 74: Revision 1.180 2015/02/11 17:33:45 brouard
75: Summary: Finishing move from main to function (hpijx and prevalence_limit)
76:
1.180 brouard 77: Revision 1.179 2015/01/04 09:57:06 brouard
78: Summary: back to OS/X
79:
1.179 brouard 80: Revision 1.178 2015/01/04 09:35:48 brouard
81: *** empty log message ***
82:
1.178 brouard 83: Revision 1.177 2015/01/03 18:40:56 brouard
84: Summary: Still testing ilc32 on OSX
85:
1.177 brouard 86: Revision 1.176 2015/01/03 16:45:04 brouard
87: *** empty log message ***
88:
1.176 brouard 89: Revision 1.175 2015/01/03 16:33:42 brouard
90: *** empty log message ***
91:
1.175 brouard 92: Revision 1.174 2015/01/03 16:15:49 brouard
93: Summary: Still in cross-compilation
94:
1.174 brouard 95: Revision 1.173 2015/01/03 12:06:26 brouard
96: Summary: trying to detect cross-compilation
97:
1.173 brouard 98: Revision 1.172 2014/12/27 12:07:47 brouard
99: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
100:
1.172 brouard 101: Revision 1.171 2014/12/23 13:26:59 brouard
102: Summary: Back from Visual C
103:
104: Still problem with utsname.h on Windows
105:
1.171 brouard 106: Revision 1.170 2014/12/23 11:17:12 brouard
107: Summary: Cleaning some \%% back to %%
108:
109: The escape was mandatory for a specific compiler (which one?), but too many warnings.
110:
1.170 brouard 111: Revision 1.169 2014/12/22 23:08:31 brouard
112: Summary: 0.98p
113:
114: Outputs some informations on compiler used, OS etc. Testing on different platforms.
115:
1.169 brouard 116: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 117: Summary: update
1.169 brouard 118:
1.168 brouard 119: Revision 1.167 2014/12/22 13:50:56 brouard
120: Summary: Testing uname and compiler version and if compiled 32 or 64
121:
122: Testing on Linux 64
123:
1.167 brouard 124: Revision 1.166 2014/12/22 11:40:47 brouard
125: *** empty log message ***
126:
1.166 brouard 127: Revision 1.165 2014/12/16 11:20:36 brouard
128: Summary: After compiling on Visual C
129:
130: * imach.c (Module): Merging 1.61 to 1.162
131:
1.165 brouard 132: Revision 1.164 2014/12/16 10:52:11 brouard
133: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
134:
135: * imach.c (Module): Merging 1.61 to 1.162
136:
1.164 brouard 137: Revision 1.163 2014/12/16 10:30:11 brouard
138: * imach.c (Module): Merging 1.61 to 1.162
139:
1.163 brouard 140: Revision 1.162 2014/09/25 11:43:39 brouard
141: Summary: temporary backup 0.99!
142:
1.162 brouard 143: Revision 1.1 2014/09/16 11:06:58 brouard
144: Summary: With some code (wrong) for nlopt
145:
146: Author:
147:
148: Revision 1.161 2014/09/15 20:41:41 brouard
149: Summary: Problem with macro SQR on Intel compiler
150:
1.161 brouard 151: Revision 1.160 2014/09/02 09:24:05 brouard
152: *** empty log message ***
153:
1.160 brouard 154: Revision 1.159 2014/09/01 10:34:10 brouard
155: Summary: WIN32
156: Author: Brouard
157:
1.159 brouard 158: Revision 1.158 2014/08/27 17:11:51 brouard
159: *** empty log message ***
160:
1.158 brouard 161: Revision 1.157 2014/08/27 16:26:55 brouard
162: Summary: Preparing windows Visual studio version
163: Author: Brouard
164:
165: In order to compile on Visual studio, time.h is now correct and time_t
166: and tm struct should be used. difftime should be used but sometimes I
167: just make the differences in raw time format (time(&now).
168: Trying to suppress #ifdef LINUX
169: Add xdg-open for __linux in order to open default browser.
170:
1.157 brouard 171: Revision 1.156 2014/08/25 20:10:10 brouard
172: *** empty log message ***
173:
1.156 brouard 174: Revision 1.155 2014/08/25 18:32:34 brouard
175: Summary: New compile, minor changes
176: Author: Brouard
177:
1.155 brouard 178: Revision 1.154 2014/06/20 17:32:08 brouard
179: Summary: Outputs now all graphs of convergence to period prevalence
180:
1.154 brouard 181: Revision 1.153 2014/06/20 16:45:46 brouard
182: Summary: If 3 live state, convergence to period prevalence on same graph
183: Author: Brouard
184:
1.153 brouard 185: Revision 1.152 2014/06/18 17:54:09 brouard
186: Summary: open browser, use gnuplot on same dir than imach if not found in the path
187:
1.152 brouard 188: Revision 1.151 2014/06/18 16:43:30 brouard
189: *** empty log message ***
190:
1.151 brouard 191: Revision 1.150 2014/06/18 16:42:35 brouard
192: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
193: Author: brouard
194:
1.150 brouard 195: Revision 1.149 2014/06/18 15:51:14 brouard
196: Summary: Some fixes in parameter files errors
197: Author: Nicolas Brouard
198:
1.149 brouard 199: Revision 1.148 2014/06/17 17:38:48 brouard
200: Summary: Nothing new
201: Author: Brouard
202:
203: Just a new packaging for OS/X version 0.98nS
204:
1.148 brouard 205: Revision 1.147 2014/06/16 10:33:11 brouard
206: *** empty log message ***
207:
1.147 brouard 208: Revision 1.146 2014/06/16 10:20:28 brouard
209: Summary: Merge
210: Author: Brouard
211:
212: Merge, before building revised version.
213:
1.146 brouard 214: Revision 1.145 2014/06/10 21:23:15 brouard
215: Summary: Debugging with valgrind
216: Author: Nicolas Brouard
217:
218: Lot of changes in order to output the results with some covariates
219: After the Edimburgh REVES conference 2014, it seems mandatory to
220: improve the code.
221: No more memory valgrind error but a lot has to be done in order to
222: continue the work of splitting the code into subroutines.
223: Also, decodemodel has been improved. Tricode is still not
224: optimal. nbcode should be improved. Documentation has been added in
225: the source code.
226:
1.144 brouard 227: Revision 1.143 2014/01/26 09:45:38 brouard
228: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
229:
230: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
231: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
232:
1.143 brouard 233: Revision 1.142 2014/01/26 03:57:36 brouard
234: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
235:
236: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
237:
1.142 brouard 238: Revision 1.141 2014/01/26 02:42:01 brouard
239: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
240:
1.141 brouard 241: Revision 1.140 2011/09/02 10:37:54 brouard
242: Summary: times.h is ok with mingw32 now.
243:
1.140 brouard 244: Revision 1.139 2010/06/14 07:50:17 brouard
245: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
246: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
247:
1.139 brouard 248: Revision 1.138 2010/04/30 18:19:40 brouard
249: *** empty log message ***
250:
1.138 brouard 251: Revision 1.137 2010/04/29 18:11:38 brouard
252: (Module): Checking covariates for more complex models
253: than V1+V2. A lot of change to be done. Unstable.
254:
1.137 brouard 255: Revision 1.136 2010/04/26 20:30:53 brouard
256: (Module): merging some libgsl code. Fixing computation
257: of likelione (using inter/intrapolation if mle = 0) in order to
258: get same likelihood as if mle=1.
259: Some cleaning of code and comments added.
260:
1.136 brouard 261: Revision 1.135 2009/10/29 15:33:14 brouard
262: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
263:
1.135 brouard 264: Revision 1.134 2009/10/29 13:18:53 brouard
265: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
266:
1.134 brouard 267: Revision 1.133 2009/07/06 10:21:25 brouard
268: just nforces
269:
1.133 brouard 270: Revision 1.132 2009/07/06 08:22:05 brouard
271: Many tings
272:
1.132 brouard 273: Revision 1.131 2009/06/20 16:22:47 brouard
274: Some dimensions resccaled
275:
1.131 brouard 276: Revision 1.130 2009/05/26 06:44:34 brouard
277: (Module): Max Covariate is now set to 20 instead of 8. A
278: lot of cleaning with variables initialized to 0. Trying to make
279: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
280:
1.130 brouard 281: Revision 1.129 2007/08/31 13:49:27 lievre
282: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
283:
1.129 lievre 284: Revision 1.128 2006/06/30 13:02:05 brouard
285: (Module): Clarifications on computing e.j
286:
1.128 brouard 287: Revision 1.127 2006/04/28 18:11:50 brouard
288: (Module): Yes the sum of survivors was wrong since
289: imach-114 because nhstepm was no more computed in the age
290: loop. Now we define nhstepma in the age loop.
291: (Module): In order to speed up (in case of numerous covariates) we
292: compute health expectancies (without variances) in a first step
293: and then all the health expectancies with variances or standard
294: deviation (needs data from the Hessian matrices) which slows the
295: computation.
296: In the future we should be able to stop the program is only health
297: expectancies and graph are needed without standard deviations.
298:
1.127 brouard 299: Revision 1.126 2006/04/28 17:23:28 brouard
300: (Module): Yes the sum of survivors was wrong since
301: imach-114 because nhstepm was no more computed in the age
302: loop. Now we define nhstepma in the age loop.
303: Version 0.98h
304:
1.126 brouard 305: Revision 1.125 2006/04/04 15:20:31 lievre
306: Errors in calculation of health expectancies. Age was not initialized.
307: Forecasting file added.
308:
309: Revision 1.124 2006/03/22 17:13:53 lievre
310: Parameters are printed with %lf instead of %f (more numbers after the comma).
311: The log-likelihood is printed in the log file
312:
313: Revision 1.123 2006/03/20 10:52:43 brouard
314: * imach.c (Module): <title> changed, corresponds to .htm file
315: name. <head> headers where missing.
316:
317: * imach.c (Module): Weights can have a decimal point as for
318: English (a comma might work with a correct LC_NUMERIC environment,
319: otherwise the weight is truncated).
320: Modification of warning when the covariates values are not 0 or
321: 1.
322: Version 0.98g
323:
324: Revision 1.122 2006/03/20 09:45:41 brouard
325: (Module): Weights can have a decimal point as for
326: English (a comma might work with a correct LC_NUMERIC environment,
327: otherwise the weight is truncated).
328: Modification of warning when the covariates values are not 0 or
329: 1.
330: Version 0.98g
331:
332: Revision 1.121 2006/03/16 17:45:01 lievre
333: * imach.c (Module): Comments concerning covariates added
334:
335: * imach.c (Module): refinements in the computation of lli if
336: status=-2 in order to have more reliable computation if stepm is
337: not 1 month. Version 0.98f
338:
339: Revision 1.120 2006/03/16 15:10:38 lievre
340: (Module): refinements in the computation of lli if
341: status=-2 in order to have more reliable computation if stepm is
342: not 1 month. Version 0.98f
343:
344: Revision 1.119 2006/03/15 17:42:26 brouard
345: (Module): Bug if status = -2, the loglikelihood was
346: computed as likelihood omitting the logarithm. Version O.98e
347:
348: Revision 1.118 2006/03/14 18:20:07 brouard
349: (Module): varevsij Comments added explaining the second
350: table of variances if popbased=1 .
351: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
352: (Module): Function pstamp added
353: (Module): Version 0.98d
354:
355: Revision 1.117 2006/03/14 17:16:22 brouard
356: (Module): varevsij Comments added explaining the second
357: table of variances if popbased=1 .
358: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
359: (Module): Function pstamp added
360: (Module): Version 0.98d
361:
362: Revision 1.116 2006/03/06 10:29:27 brouard
363: (Module): Variance-covariance wrong links and
364: varian-covariance of ej. is needed (Saito).
365:
366: Revision 1.115 2006/02/27 12:17:45 brouard
367: (Module): One freematrix added in mlikeli! 0.98c
368:
369: Revision 1.114 2006/02/26 12:57:58 brouard
370: (Module): Some improvements in processing parameter
371: filename with strsep.
372:
373: Revision 1.113 2006/02/24 14:20:24 brouard
374: (Module): Memory leaks checks with valgrind and:
375: datafile was not closed, some imatrix were not freed and on matrix
376: allocation too.
377:
378: Revision 1.112 2006/01/30 09:55:26 brouard
379: (Module): Back to gnuplot.exe instead of wgnuplot.exe
380:
381: Revision 1.111 2006/01/25 20:38:18 brouard
382: (Module): Lots of cleaning and bugs added (Gompertz)
383: (Module): Comments can be added in data file. Missing date values
384: can be a simple dot '.'.
385:
386: Revision 1.110 2006/01/25 00:51:50 brouard
387: (Module): Lots of cleaning and bugs added (Gompertz)
388:
389: Revision 1.109 2006/01/24 19:37:15 brouard
390: (Module): Comments (lines starting with a #) are allowed in data.
391:
392: Revision 1.108 2006/01/19 18:05:42 lievre
393: Gnuplot problem appeared...
394: To be fixed
395:
396: Revision 1.107 2006/01/19 16:20:37 brouard
397: Test existence of gnuplot in imach path
398:
399: Revision 1.106 2006/01/19 13:24:36 brouard
400: Some cleaning and links added in html output
401:
402: Revision 1.105 2006/01/05 20:23:19 lievre
403: *** empty log message ***
404:
405: Revision 1.104 2005/09/30 16:11:43 lievre
406: (Module): sump fixed, loop imx fixed, and simplifications.
407: (Module): If the status is missing at the last wave but we know
408: that the person is alive, then we can code his/her status as -2
409: (instead of missing=-1 in earlier versions) and his/her
410: contributions to the likelihood is 1 - Prob of dying from last
411: health status (= 1-p13= p11+p12 in the easiest case of somebody in
412: the healthy state at last known wave). Version is 0.98
413:
414: Revision 1.103 2005/09/30 15:54:49 lievre
415: (Module): sump fixed, loop imx fixed, and simplifications.
416:
417: Revision 1.102 2004/09/15 17:31:30 brouard
418: Add the possibility to read data file including tab characters.
419:
420: Revision 1.101 2004/09/15 10:38:38 brouard
421: Fix on curr_time
422:
423: Revision 1.100 2004/07/12 18:29:06 brouard
424: Add version for Mac OS X. Just define UNIX in Makefile
425:
426: Revision 1.99 2004/06/05 08:57:40 brouard
427: *** empty log message ***
428:
429: Revision 1.98 2004/05/16 15:05:56 brouard
430: New version 0.97 . First attempt to estimate force of mortality
431: directly from the data i.e. without the need of knowing the health
432: state at each age, but using a Gompertz model: log u =a + b*age .
433: This is the basic analysis of mortality and should be done before any
434: other analysis, in order to test if the mortality estimated from the
435: cross-longitudinal survey is different from the mortality estimated
436: from other sources like vital statistic data.
437:
438: The same imach parameter file can be used but the option for mle should be -3.
439:
1.133 brouard 440: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 441: former routines in order to include the new code within the former code.
442:
443: The output is very simple: only an estimate of the intercept and of
444: the slope with 95% confident intervals.
445:
446: Current limitations:
447: A) Even if you enter covariates, i.e. with the
448: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
449: B) There is no computation of Life Expectancy nor Life Table.
450:
451: Revision 1.97 2004/02/20 13:25:42 lievre
452: Version 0.96d. Population forecasting command line is (temporarily)
453: suppressed.
454:
455: Revision 1.96 2003/07/15 15:38:55 brouard
456: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
457: rewritten within the same printf. Workaround: many printfs.
458:
459: Revision 1.95 2003/07/08 07:54:34 brouard
460: * imach.c (Repository):
461: (Repository): Using imachwizard code to output a more meaningful covariance
462: matrix (cov(a12,c31) instead of numbers.
463:
464: Revision 1.94 2003/06/27 13:00:02 brouard
465: Just cleaning
466:
467: Revision 1.93 2003/06/25 16:33:55 brouard
468: (Module): On windows (cygwin) function asctime_r doesn't
469: exist so I changed back to asctime which exists.
470: (Module): Version 0.96b
471:
472: Revision 1.92 2003/06/25 16:30:45 brouard
473: (Module): On windows (cygwin) function asctime_r doesn't
474: exist so I changed back to asctime which exists.
475:
476: Revision 1.91 2003/06/25 15:30:29 brouard
477: * imach.c (Repository): Duplicated warning errors corrected.
478: (Repository): Elapsed time after each iteration is now output. It
479: helps to forecast when convergence will be reached. Elapsed time
480: is stamped in powell. We created a new html file for the graphs
481: concerning matrix of covariance. It has extension -cov.htm.
482:
483: Revision 1.90 2003/06/24 12:34:15 brouard
484: (Module): Some bugs corrected for windows. Also, when
485: mle=-1 a template is output in file "or"mypar.txt with the design
486: of the covariance matrix to be input.
487:
488: Revision 1.89 2003/06/24 12:30:52 brouard
489: (Module): Some bugs corrected for windows. Also, when
490: mle=-1 a template is output in file "or"mypar.txt with the design
491: of the covariance matrix to be input.
492:
493: Revision 1.88 2003/06/23 17:54:56 brouard
494: * 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.
495:
496: Revision 1.87 2003/06/18 12:26:01 brouard
497: Version 0.96
498:
499: Revision 1.86 2003/06/17 20:04:08 brouard
500: (Module): Change position of html and gnuplot routines and added
501: routine fileappend.
502:
503: Revision 1.85 2003/06/17 13:12:43 brouard
504: * imach.c (Repository): Check when date of death was earlier that
505: current date of interview. It may happen when the death was just
506: prior to the death. In this case, dh was negative and likelihood
507: was wrong (infinity). We still send an "Error" but patch by
508: assuming that the date of death was just one stepm after the
509: interview.
510: (Repository): Because some people have very long ID (first column)
511: we changed int to long in num[] and we added a new lvector for
512: memory allocation. But we also truncated to 8 characters (left
513: truncation)
514: (Repository): No more line truncation errors.
515:
516: Revision 1.84 2003/06/13 21:44:43 brouard
517: * imach.c (Repository): Replace "freqsummary" at a correct
518: place. It differs from routine "prevalence" which may be called
519: many times. Probs is memory consuming and must be used with
520: parcimony.
521: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
522:
523: Revision 1.83 2003/06/10 13:39:11 lievre
524: *** empty log message ***
525:
526: Revision 1.82 2003/06/05 15:57:20 brouard
527: Add log in imach.c and fullversion number is now printed.
528:
529: */
530: /*
531: Interpolated Markov Chain
532:
533: Short summary of the programme:
534:
535: This program computes Healthy Life Expectancies from
536: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
537: first survey ("cross") where individuals from different ages are
538: interviewed on their health status or degree of disability (in the
539: case of a health survey which is our main interest) -2- at least a
540: second wave of interviews ("longitudinal") which measure each change
541: (if any) in individual health status. Health expectancies are
542: computed from the time spent in each health state according to a
543: model. More health states you consider, more time is necessary to reach the
544: Maximum Likelihood of the parameters involved in the model. The
545: simplest model is the multinomial logistic model where pij is the
546: probability to be observed in state j at the second wave
547: conditional to be observed in state i at the first wave. Therefore
548: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
549: 'age' is age and 'sex' is a covariate. If you want to have a more
550: complex model than "constant and age", you should modify the program
551: where the markup *Covariates have to be included here again* invites
552: you to do it. More covariates you add, slower the
553: convergence.
554:
555: The advantage of this computer programme, compared to a simple
556: multinomial logistic model, is clear when the delay between waves is not
557: identical for each individual. Also, if a individual missed an
558: intermediate interview, the information is lost, but taken into
559: account using an interpolation or extrapolation.
560:
561: hPijx is the probability to be observed in state i at age x+h
562: conditional to the observed state i at age x. The delay 'h' can be
563: split into an exact number (nh*stepm) of unobserved intermediate
564: states. This elementary transition (by month, quarter,
565: semester or year) is modelled as a multinomial logistic. The hPx
566: matrix is simply the matrix product of nh*stepm elementary matrices
567: and the contribution of each individual to the likelihood is simply
568: hPijx.
569:
570: Also this programme outputs the covariance matrix of the parameters but also
571: of the life expectancies. It also computes the period (stable) prevalence.
572:
1.133 brouard 573: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
574: Institut national d'études démographiques, Paris.
1.126 brouard 575: This software have been partly granted by Euro-REVES, a concerted action
576: from the European Union.
577: It is copyrighted identically to a GNU software product, ie programme and
578: software can be distributed freely for non commercial use. Latest version
579: can be accessed at http://euroreves.ined.fr/imach .
580:
581: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
582: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
583:
584: **********************************************************************/
585: /*
586: main
587: read parameterfile
588: read datafile
589: concatwav
590: freqsummary
591: if (mle >= 1)
592: mlikeli
593: print results files
594: if mle==1
595: computes hessian
596: read end of parameter file: agemin, agemax, bage, fage, estepm
597: begin-prev-date,...
598: open gnuplot file
599: open html file
1.145 brouard 600: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
601: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
602: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
603: freexexit2 possible for memory heap.
604:
605: h Pij x | pij_nom ficrestpij
606: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
607: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
608: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
609:
610: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
611: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
612: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
613: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
614: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
615:
1.126 brouard 616: forecasting if prevfcast==1 prevforecast call prevalence()
617: health expectancies
618: Variance-covariance of DFLE
619: prevalence()
620: movingaverage()
621: varevsij()
622: if popbased==1 varevsij(,popbased)
623: total life expectancies
624: Variance of period (stable) prevalence
625: end
626: */
627:
1.187 brouard 628: /* #define DEBUG */
629: /* #define DEBUGBRENT */
1.165 brouard 630: #define POWELL /* Instead of NLOPT */
1.192 brouard 631: #define POWELLF1F3 /* Skip test */
1.186 brouard 632: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
633: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 634:
635: #include <math.h>
636: #include <stdio.h>
637: #include <stdlib.h>
638: #include <string.h>
1.159 brouard 639:
640: #ifdef _WIN32
641: #include <io.h>
1.172 brouard 642: #include <windows.h>
643: #include <tchar.h>
1.159 brouard 644: #else
1.126 brouard 645: #include <unistd.h>
1.159 brouard 646: #endif
1.126 brouard 647:
648: #include <limits.h>
649: #include <sys/types.h>
1.171 brouard 650:
651: #if defined(__GNUC__)
652: #include <sys/utsname.h> /* Doesn't work on Windows */
653: #endif
654:
1.126 brouard 655: #include <sys/stat.h>
656: #include <errno.h>
1.159 brouard 657: /* extern int errno; */
1.126 brouard 658:
1.157 brouard 659: /* #ifdef LINUX */
660: /* #include <time.h> */
661: /* #include "timeval.h" */
662: /* #else */
663: /* #include <sys/time.h> */
664: /* #endif */
665:
1.126 brouard 666: #include <time.h>
667:
1.136 brouard 668: #ifdef GSL
669: #include <gsl/gsl_errno.h>
670: #include <gsl/gsl_multimin.h>
671: #endif
672:
1.167 brouard 673:
1.162 brouard 674: #ifdef NLOPT
675: #include <nlopt.h>
676: typedef struct {
677: double (* function)(double [] );
678: } myfunc_data ;
679: #endif
680:
1.126 brouard 681: /* #include <libintl.h> */
682: /* #define _(String) gettext (String) */
683:
1.141 brouard 684: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 685:
686: #define GNUPLOTPROGRAM "gnuplot"
687: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
688: #define FILENAMELENGTH 132
689:
690: #define GLOCK_ERROR_NOPATH -1 /* empty path */
691: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
692:
1.144 brouard 693: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
694: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 695:
696: #define NINTERVMAX 8
1.144 brouard 697: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
698: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
699: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197 brouard 700: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.126 brouard 701: #define MAXN 20000
1.144 brouard 702: #define YEARM 12. /**< Number of months per year */
1.126 brouard 703: #define AGESUP 130
704: #define AGEBASE 40
1.194 brouard 705: #define AGEOVERFLOW 1.e20
1.164 brouard 706: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 707: #ifdef _WIN32
708: #define DIRSEPARATOR '\\'
709: #define CHARSEPARATOR "\\"
710: #define ODIRSEPARATOR '/'
711: #else
1.126 brouard 712: #define DIRSEPARATOR '/'
713: #define CHARSEPARATOR "/"
714: #define ODIRSEPARATOR '\\'
715: #endif
716:
1.198 ! brouard 717: /* $Id: imach.c,v 1.197 2015/09/01 18:24:39 brouard Exp $ */
1.126 brouard 718: /* $State: Exp $ */
1.196 brouard 719: #include "version.h"
720: char version[]=__IMACH_VERSION__;
1.197 brouard 721: char copyright[]="September 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.198 ! brouard 722: char fullversion[]="$Revision: 1.197 $ $Date: 2015/09/01 18:24:39 $";
1.126 brouard 723: char strstart[80];
724: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 725: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 726: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 727: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
728: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
729: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
730: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
731: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
732: int cptcovprodnoage=0; /**< Number of covariate products without age */
733: int cptcoveff=0; /* Total number of covariates to vary for printing results */
734: int cptcov=0; /* Working variable */
1.126 brouard 735: int npar=NPARMAX;
736: int nlstate=2; /* Number of live states */
737: int ndeath=1; /* Number of dead states */
1.130 brouard 738: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 739: int popbased=0;
740:
741: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 742: int maxwav=0; /* Maxim number of waves */
743: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
744: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
745: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 746: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 747: int mle=1, weightopt=0;
1.126 brouard 748: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
749: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
750: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
751: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 752: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 753: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 754: double **matprod2(); /* test */
1.126 brouard 755: double **oldm, **newm, **savm; /* Working pointers to matrices */
756: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 757: /*FILE *fic ; */ /* Used in readdata only */
758: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 759: FILE *ficlog, *ficrespow;
1.130 brouard 760: int globpr=0; /* Global variable for printing or not */
1.126 brouard 761: double fretone; /* Only one call to likelihood */
1.130 brouard 762: long ipmx=0; /* Number of contributions */
1.126 brouard 763: double sw; /* Sum of weights */
764: char filerespow[FILENAMELENGTH];
765: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
766: FILE *ficresilk;
767: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
768: FILE *ficresprobmorprev;
769: FILE *fichtm, *fichtmcov; /* Html File */
770: FILE *ficreseij;
771: char filerese[FILENAMELENGTH];
772: FILE *ficresstdeij;
773: char fileresstde[FILENAMELENGTH];
774: FILE *ficrescveij;
775: char filerescve[FILENAMELENGTH];
776: FILE *ficresvij;
777: char fileresv[FILENAMELENGTH];
778: FILE *ficresvpl;
779: char fileresvpl[FILENAMELENGTH];
780: char title[MAXLINE];
781: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
782: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
783: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
784: char command[FILENAMELENGTH];
785: int outcmd=0;
786:
787: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
788:
789: char filelog[FILENAMELENGTH]; /* Log file */
790: char filerest[FILENAMELENGTH];
791: char fileregp[FILENAMELENGTH];
792: char popfile[FILENAMELENGTH];
793:
794: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
795:
1.157 brouard 796: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
797: /* struct timezone tzp; */
798: /* extern int gettimeofday(); */
799: struct tm tml, *gmtime(), *localtime();
800:
801: extern time_t time();
802:
803: struct tm start_time, end_time, curr_time, last_time, forecast_time;
804: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
805: struct tm tm;
806:
1.126 brouard 807: char strcurr[80], strfor[80];
808:
809: char *endptr;
810: long lval;
811: double dval;
812:
813: #define NR_END 1
814: #define FREE_ARG char*
815: #define FTOL 1.0e-10
816:
817: #define NRANSI
818: #define ITMAX 200
819:
820: #define TOL 2.0e-4
821:
822: #define CGOLD 0.3819660
823: #define ZEPS 1.0e-10
824: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
825:
826: #define GOLD 1.618034
827: #define GLIMIT 100.0
828: #define TINY 1.0e-20
829:
830: static double maxarg1,maxarg2;
831: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
832: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
833:
834: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
835: #define rint(a) floor(a+0.5)
1.166 brouard 836: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 837: #define mytinydouble 1.0e-16
1.166 brouard 838: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
839: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
840: /* static double dsqrarg; */
841: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 842: static double sqrarg;
843: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
844: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
845: int agegomp= AGEGOMP;
846:
847: int imx;
848: int stepm=1;
849: /* Stepm, step in month: minimum step interpolation*/
850:
851: int estepm;
852: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
853:
854: int m,nb;
855: long *num;
1.197 brouard 856: int firstpass=0, lastpass=4,*cod, *cens;
1.192 brouard 857: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
858: covariate for which somebody answered excluding
859: undefined. Usually 2: 0 and 1. */
860: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
861: covariate for which somebody answered including
862: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 863: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
864: double **pmmij, ***probs;
865: double *ageexmed,*agecens;
866: double dateintmean=0;
867:
868: double *weight;
869: int **s; /* Status */
1.141 brouard 870: double *agedc;
1.145 brouard 871: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 872: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 873: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 874: double idx;
875: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197 brouard 876: int *Tage;
1.145 brouard 877: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 878: int **codtab; /**< codtab=imatrix(1,100,1,10); */
879: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 880: double *lsurv, *lpop, *tpop;
881:
1.143 brouard 882: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
883: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 884:
885: /**************** split *************************/
886: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
887: {
888: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
889: the name of the file (name), its extension only (ext) and its first part of the name (finame)
890: */
891: char *ss; /* pointer */
1.186 brouard 892: int l1=0, l2=0; /* length counters */
1.126 brouard 893:
894: l1 = strlen(path ); /* length of path */
895: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
896: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
897: if ( ss == NULL ) { /* no directory, so determine current directory */
898: strcpy( name, path ); /* we got the fullname name because no directory */
899: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
900: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
901: /* get current working directory */
902: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 903: #ifdef WIN32
904: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
905: #else
906: if (getcwd(dirc, FILENAME_MAX) == NULL) {
907: #endif
1.126 brouard 908: return( GLOCK_ERROR_GETCWD );
909: }
910: /* got dirc from getcwd*/
911: printf(" DIRC = %s \n",dirc);
912: } else { /* strip direcotry from path */
913: ss++; /* after this, the filename */
914: l2 = strlen( ss ); /* length of filename */
915: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
916: strcpy( name, ss ); /* save file name */
917: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 918: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 919: printf(" DIRC2 = %s \n",dirc);
920: }
921: /* We add a separator at the end of dirc if not exists */
922: l1 = strlen( dirc ); /* length of directory */
923: if( dirc[l1-1] != DIRSEPARATOR ){
924: dirc[l1] = DIRSEPARATOR;
925: dirc[l1+1] = 0;
926: printf(" DIRC3 = %s \n",dirc);
927: }
928: ss = strrchr( name, '.' ); /* find last / */
929: if (ss >0){
930: ss++;
931: strcpy(ext,ss); /* save extension */
932: l1= strlen( name);
933: l2= strlen(ss)+1;
934: strncpy( finame, name, l1-l2);
935: finame[l1-l2]= 0;
936: }
937:
938: return( 0 ); /* we're done */
939: }
940:
941:
942: /******************************************/
943:
944: void replace_back_to_slash(char *s, char*t)
945: {
946: int i;
947: int lg=0;
948: i=0;
949: lg=strlen(t);
950: for(i=0; i<= lg; i++) {
951: (s[i] = t[i]);
952: if (t[i]== '\\') s[i]='/';
953: }
954: }
955:
1.132 brouard 956: char *trimbb(char *out, char *in)
1.137 brouard 957: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 958: char *s;
959: s=out;
960: while (*in != '\0'){
1.137 brouard 961: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 962: in++;
963: }
964: *out++ = *in++;
965: }
966: *out='\0';
967: return s;
968: }
969:
1.187 brouard 970: /* char *substrchaine(char *out, char *in, char *chain) */
971: /* { */
972: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
973: /* char *s, *t; */
974: /* t=in;s=out; */
975: /* while ((*in != *chain) && (*in != '\0')){ */
976: /* *out++ = *in++; */
977: /* } */
978:
979: /* /\* *in matches *chain *\/ */
980: /* while ((*in++ == *chain++) && (*in != '\0')){ */
981: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
982: /* } */
983: /* in--; chain--; */
984: /* while ( (*in != '\0')){ */
985: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
986: /* *out++ = *in++; */
987: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
988: /* } */
989: /* *out='\0'; */
990: /* out=s; */
991: /* return out; */
992: /* } */
993: char *substrchaine(char *out, char *in, char *chain)
994: {
995: /* Substract chain 'chain' from 'in', return and output 'out' */
996: /* in="V1+V1*age+age*age+V2", chain="age*age" */
997:
998: char *strloc;
999:
1000: strcpy (out, in);
1001: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1002: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1003: if(strloc != NULL){
1004: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1005: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1006: /* strcpy (strloc, strloc +strlen(chain));*/
1007: }
1008: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1009: return out;
1010: }
1011:
1012:
1.145 brouard 1013: char *cutl(char *blocc, char *alocc, char *in, char occ)
1014: {
1.187 brouard 1015: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 1016: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 1017: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 1018: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1019: */
1.160 brouard 1020: char *s, *t;
1.145 brouard 1021: t=in;s=in;
1022: while ((*in != occ) && (*in != '\0')){
1023: *alocc++ = *in++;
1024: }
1025: if( *in == occ){
1026: *(alocc)='\0';
1027: s=++in;
1028: }
1029:
1030: if (s == t) {/* occ not found */
1031: *(alocc-(in-s))='\0';
1032: in=s;
1033: }
1034: while ( *in != '\0'){
1035: *blocc++ = *in++;
1036: }
1037:
1038: *blocc='\0';
1039: return t;
1040: }
1.137 brouard 1041: char *cutv(char *blocc, char *alocc, char *in, char occ)
1042: {
1.187 brouard 1043: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1044: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1045: gives blocc="abcdef2ghi" and alocc="j".
1046: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1047: */
1048: char *s, *t;
1049: t=in;s=in;
1050: while (*in != '\0'){
1051: while( *in == occ){
1052: *blocc++ = *in++;
1053: s=in;
1054: }
1055: *blocc++ = *in++;
1056: }
1057: if (s == t) /* occ not found */
1058: *(blocc-(in-s))='\0';
1059: else
1060: *(blocc-(in-s)-1)='\0';
1061: in=s;
1062: while ( *in != '\0'){
1063: *alocc++ = *in++;
1064: }
1065:
1066: *alocc='\0';
1067: return s;
1068: }
1069:
1.126 brouard 1070: int nbocc(char *s, char occ)
1071: {
1072: int i,j=0;
1073: int lg=20;
1074: i=0;
1075: lg=strlen(s);
1076: for(i=0; i<= lg; i++) {
1077: if (s[i] == occ ) j++;
1078: }
1079: return j;
1080: }
1081:
1.137 brouard 1082: /* void cutv(char *u,char *v, char*t, char occ) */
1083: /* { */
1084: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1085: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1086: /* gives u="abcdef2ghi" and v="j" *\/ */
1087: /* int i,lg,j,p=0; */
1088: /* i=0; */
1089: /* lg=strlen(t); */
1090: /* for(j=0; j<=lg-1; j++) { */
1091: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1092: /* } */
1.126 brouard 1093:
1.137 brouard 1094: /* for(j=0; j<p; j++) { */
1095: /* (u[j] = t[j]); */
1096: /* } */
1097: /* u[p]='\0'; */
1.126 brouard 1098:
1.137 brouard 1099: /* for(j=0; j<= lg; j++) { */
1100: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1101: /* } */
1102: /* } */
1.126 brouard 1103:
1.160 brouard 1104: #ifdef _WIN32
1105: char * strsep(char **pp, const char *delim)
1106: {
1107: char *p, *q;
1108:
1109: if ((p = *pp) == NULL)
1110: return 0;
1111: if ((q = strpbrk (p, delim)) != NULL)
1112: {
1113: *pp = q + 1;
1114: *q = '\0';
1115: }
1116: else
1117: *pp = 0;
1118: return p;
1119: }
1120: #endif
1121:
1.126 brouard 1122: /********************** nrerror ********************/
1123:
1124: void nrerror(char error_text[])
1125: {
1126: fprintf(stderr,"ERREUR ...\n");
1127: fprintf(stderr,"%s\n",error_text);
1128: exit(EXIT_FAILURE);
1129: }
1130: /*********************** vector *******************/
1131: double *vector(int nl, int nh)
1132: {
1133: double *v;
1134: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1135: if (!v) nrerror("allocation failure in vector");
1136: return v-nl+NR_END;
1137: }
1138:
1139: /************************ free vector ******************/
1140: void free_vector(double*v, int nl, int nh)
1141: {
1142: free((FREE_ARG)(v+nl-NR_END));
1143: }
1144:
1145: /************************ivector *******************************/
1146: int *ivector(long nl,long nh)
1147: {
1148: int *v;
1149: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1150: if (!v) nrerror("allocation failure in ivector");
1151: return v-nl+NR_END;
1152: }
1153:
1154: /******************free ivector **************************/
1155: void free_ivector(int *v, long nl, long nh)
1156: {
1157: free((FREE_ARG)(v+nl-NR_END));
1158: }
1159:
1160: /************************lvector *******************************/
1161: long *lvector(long nl,long nh)
1162: {
1163: long *v;
1164: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1165: if (!v) nrerror("allocation failure in ivector");
1166: return v-nl+NR_END;
1167: }
1168:
1169: /******************free lvector **************************/
1170: void free_lvector(long *v, long nl, long nh)
1171: {
1172: free((FREE_ARG)(v+nl-NR_END));
1173: }
1174:
1175: /******************* imatrix *******************************/
1176: int **imatrix(long nrl, long nrh, long ncl, long nch)
1177: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1178: {
1179: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1180: int **m;
1181:
1182: /* allocate pointers to rows */
1183: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1184: if (!m) nrerror("allocation failure 1 in matrix()");
1185: m += NR_END;
1186: m -= nrl;
1187:
1188:
1189: /* allocate rows and set pointers to them */
1190: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1191: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1192: m[nrl] += NR_END;
1193: m[nrl] -= ncl;
1194:
1195: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1196:
1197: /* return pointer to array of pointers to rows */
1198: return m;
1199: }
1200:
1201: /****************** free_imatrix *************************/
1202: void free_imatrix(m,nrl,nrh,ncl,nch)
1203: int **m;
1204: long nch,ncl,nrh,nrl;
1205: /* free an int matrix allocated by imatrix() */
1206: {
1207: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1208: free((FREE_ARG) (m+nrl-NR_END));
1209: }
1210:
1211: /******************* matrix *******************************/
1212: double **matrix(long nrl, long nrh, long ncl, long nch)
1213: {
1214: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1215: double **m;
1216:
1217: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1218: if (!m) nrerror("allocation failure 1 in matrix()");
1219: m += NR_END;
1220: m -= nrl;
1221:
1222: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1223: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1224: m[nrl] += NR_END;
1225: m[nrl] -= ncl;
1226:
1227: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1228: return m;
1.145 brouard 1229: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1230: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1231: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1232: */
1233: }
1234:
1235: /*************************free matrix ************************/
1236: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1237: {
1238: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1239: free((FREE_ARG)(m+nrl-NR_END));
1240: }
1241:
1242: /******************* ma3x *******************************/
1243: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1244: {
1245: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1246: double ***m;
1247:
1248: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1249: if (!m) nrerror("allocation failure 1 in matrix()");
1250: m += NR_END;
1251: m -= nrl;
1252:
1253: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1254: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1255: m[nrl] += NR_END;
1256: m[nrl] -= ncl;
1257:
1258: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1259:
1260: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1261: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1262: m[nrl][ncl] += NR_END;
1263: m[nrl][ncl] -= nll;
1264: for (j=ncl+1; j<=nch; j++)
1265: m[nrl][j]=m[nrl][j-1]+nlay;
1266:
1267: for (i=nrl+1; i<=nrh; i++) {
1268: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1269: for (j=ncl+1; j<=nch; j++)
1270: m[i][j]=m[i][j-1]+nlay;
1271: }
1272: return m;
1273: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1274: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1275: */
1276: }
1277:
1278: /*************************free ma3x ************************/
1279: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1280: {
1281: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1282: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1283: free((FREE_ARG)(m+nrl-NR_END));
1284: }
1285:
1286: /*************** function subdirf ***********/
1287: char *subdirf(char fileres[])
1288: {
1289: /* Caution optionfilefiname is hidden */
1290: strcpy(tmpout,optionfilefiname);
1291: strcat(tmpout,"/"); /* Add to the right */
1292: strcat(tmpout,fileres);
1293: return tmpout;
1294: }
1295:
1296: /*************** function subdirf2 ***********/
1297: char *subdirf2(char fileres[], char *preop)
1298: {
1299:
1300: /* Caution optionfilefiname is hidden */
1301: strcpy(tmpout,optionfilefiname);
1302: strcat(tmpout,"/");
1303: strcat(tmpout,preop);
1304: strcat(tmpout,fileres);
1305: return tmpout;
1306: }
1307:
1308: /*************** function subdirf3 ***********/
1309: char *subdirf3(char fileres[], char *preop, char *preop2)
1310: {
1311:
1312: /* Caution optionfilefiname is hidden */
1313: strcpy(tmpout,optionfilefiname);
1314: strcat(tmpout,"/");
1315: strcat(tmpout,preop);
1316: strcat(tmpout,preop2);
1317: strcat(tmpout,fileres);
1318: return tmpout;
1319: }
1320:
1.162 brouard 1321: char *asc_diff_time(long time_sec, char ascdiff[])
1322: {
1323: long sec_left, days, hours, minutes;
1324: days = (time_sec) / (60*60*24);
1325: sec_left = (time_sec) % (60*60*24);
1326: hours = (sec_left) / (60*60) ;
1327: sec_left = (sec_left) %(60*60);
1328: minutes = (sec_left) /60;
1329: sec_left = (sec_left) % (60);
1330: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1331: return ascdiff;
1332: }
1333:
1.126 brouard 1334: /***************** f1dim *************************/
1335: extern int ncom;
1336: extern double *pcom,*xicom;
1337: extern double (*nrfunc)(double []);
1338:
1339: double f1dim(double x)
1340: {
1341: int j;
1342: double f;
1343: double *xt;
1344:
1345: xt=vector(1,ncom);
1346: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1347: f=(*nrfunc)(xt);
1348: free_vector(xt,1,ncom);
1349: return f;
1350: }
1351:
1352: /*****************brent *************************/
1353: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1354: {
1355: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1356: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1357: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1358: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1359: * returned function value.
1360: */
1.126 brouard 1361: int iter;
1362: double a,b,d,etemp;
1.159 brouard 1363: double fu=0,fv,fw,fx;
1.164 brouard 1364: double ftemp=0.;
1.126 brouard 1365: double p,q,r,tol1,tol2,u,v,w,x,xm;
1366: double e=0.0;
1367:
1368: a=(ax < cx ? ax : cx);
1369: b=(ax > cx ? ax : cx);
1370: x=w=v=bx;
1371: fw=fv=fx=(*f)(x);
1372: for (iter=1;iter<=ITMAX;iter++) {
1373: xm=0.5*(a+b);
1374: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1375: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1376: printf(".");fflush(stdout);
1377: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1378: #ifdef DEBUGBRENT
1.126 brouard 1379: 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);
1380: 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);
1381: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1382: #endif
1383: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1384: *xmin=x;
1385: return fx;
1386: }
1387: ftemp=fu;
1388: if (fabs(e) > tol1) {
1389: r=(x-w)*(fx-fv);
1390: q=(x-v)*(fx-fw);
1391: p=(x-v)*q-(x-w)*r;
1392: q=2.0*(q-r);
1393: if (q > 0.0) p = -p;
1394: q=fabs(q);
1395: etemp=e;
1396: e=d;
1397: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1398: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1399: else {
1400: d=p/q;
1401: u=x+d;
1402: if (u-a < tol2 || b-u < tol2)
1403: d=SIGN(tol1,xm-x);
1404: }
1405: } else {
1406: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1407: }
1408: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1409: fu=(*f)(u);
1410: if (fu <= fx) {
1411: if (u >= x) a=x; else b=x;
1412: SHFT(v,w,x,u)
1.183 brouard 1413: SHFT(fv,fw,fx,fu)
1414: } else {
1415: if (u < x) a=u; else b=u;
1416: if (fu <= fw || w == x) {
1417: v=w;
1418: w=u;
1419: fv=fw;
1420: fw=fu;
1421: } else if (fu <= fv || v == x || v == w) {
1422: v=u;
1423: fv=fu;
1424: }
1425: }
1.126 brouard 1426: }
1427: nrerror("Too many iterations in brent");
1428: *xmin=x;
1429: return fx;
1430: }
1431:
1432: /****************** mnbrak ***********************/
1433:
1434: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1435: double (*func)(double))
1.183 brouard 1436: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1437: the downhill direction (defined by the function as evaluated at the initial points) and returns
1438: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1439: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1440: */
1.126 brouard 1441: double ulim,u,r,q, dum;
1442: double fu;
1.187 brouard 1443:
1444: double scale=10.;
1445: int iterscale=0;
1446:
1447: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1448: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1449:
1450:
1451: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1452: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1453: /* *bx = *ax - (*ax - *bx)/scale; */
1454: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1455: /* } */
1456:
1.126 brouard 1457: if (*fb > *fa) {
1458: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1459: SHFT(dum,*fb,*fa,dum)
1460: }
1.126 brouard 1461: *cx=(*bx)+GOLD*(*bx-*ax);
1462: *fc=(*func)(*cx);
1.183 brouard 1463: #ifdef DEBUG
1464: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1465: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1466: #endif
1467: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1468: r=(*bx-*ax)*(*fb-*fc);
1469: q=(*bx-*cx)*(*fb-*fa);
1470: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1471: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1472: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1473: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1474: fu=(*func)(u);
1.163 brouard 1475: #ifdef DEBUG
1476: /* f(x)=A(x-u)**2+f(u) */
1477: double A, fparabu;
1478: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1479: fparabu= *fa - A*(*ax-u)*(*ax-u);
1480: 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);
1481: 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 1482: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1483: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1484: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1485: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1486: #endif
1.184 brouard 1487: #ifdef MNBRAKORIGINAL
1.183 brouard 1488: #else
1.191 brouard 1489: /* if (fu > *fc) { */
1490: /* #ifdef DEBUG */
1491: /* printf("mnbrak4 fu > fc \n"); */
1492: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1493: /* #endif */
1494: /* /\* 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 *\\/ *\/ */
1495: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1496: /* dum=u; /\* Shifting c and u *\/ */
1497: /* u = *cx; */
1498: /* *cx = dum; */
1499: /* dum = fu; */
1500: /* fu = *fc; */
1501: /* *fc =dum; */
1502: /* } else { /\* end *\/ */
1503: /* #ifdef DEBUG */
1504: /* printf("mnbrak3 fu < fc \n"); */
1505: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1506: /* #endif */
1507: /* dum=u; /\* Shifting c and u *\/ */
1508: /* u = *cx; */
1509: /* *cx = dum; */
1510: /* dum = fu; */
1511: /* fu = *fc; */
1512: /* *fc =dum; */
1513: /* } */
1.183 brouard 1514: #ifdef DEBUG
1.191 brouard 1515: printf("mnbrak34 fu < or >= fc \n");
1516: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1517: #endif
1.191 brouard 1518: dum=u; /* Shifting c and u */
1519: u = *cx;
1520: *cx = dum;
1521: dum = fu;
1522: fu = *fc;
1523: *fc =dum;
1.183 brouard 1524: #endif
1.162 brouard 1525: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1526: #ifdef DEBUG
1527: printf("mnbrak2 u after c but before ulim\n");
1528: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1529: #endif
1.126 brouard 1530: fu=(*func)(u);
1531: if (fu < *fc) {
1.183 brouard 1532: #ifdef DEBUG
1533: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1534: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1535: #endif
1.126 brouard 1536: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1537: SHFT(*fb,*fc,fu,(*func)(u))
1538: }
1.162 brouard 1539: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1540: #ifdef DEBUG
1541: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1542: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1543: #endif
1.126 brouard 1544: u=ulim;
1545: fu=(*func)(u);
1.183 brouard 1546: } else { /* u could be left to b (if r > q parabola has a maximum) */
1547: #ifdef DEBUG
1548: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1549: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1550: #endif
1.126 brouard 1551: u=(*cx)+GOLD*(*cx-*bx);
1552: fu=(*func)(u);
1.183 brouard 1553: } /* end tests */
1.126 brouard 1554: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1555: SHFT(*fa,*fb,*fc,fu)
1556: #ifdef DEBUG
1557: 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);
1558: 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);
1559: #endif
1560: } /* 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 1561: }
1562:
1563: /*************** linmin ************************/
1.162 brouard 1564: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1565: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1566: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1567: the value of func at the returned location p . This is actually all accomplished by calling the
1568: routines mnbrak and brent .*/
1.126 brouard 1569: int ncom;
1570: double *pcom,*xicom;
1571: double (*nrfunc)(double []);
1572:
1573: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1574: {
1575: double brent(double ax, double bx, double cx,
1576: double (*f)(double), double tol, double *xmin);
1577: double f1dim(double x);
1578: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1579: double *fc, double (*func)(double));
1580: int j;
1581: double xx,xmin,bx,ax;
1582: double fx,fb,fa;
1.187 brouard 1583:
1584: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126 brouard 1585:
1586: ncom=n;
1587: pcom=vector(1,n);
1588: xicom=vector(1,n);
1589: nrfunc=func;
1590: for (j=1;j<=n;j++) {
1591: pcom[j]=p[j];
1592: xicom[j]=xi[j];
1593: }
1.187 brouard 1594:
1.192 brouard 1595: /* axs=0.0; */
1596: /* xxss=1; /\* 1 and using scale *\/ */
1.187 brouard 1597: xxs=1;
1.192 brouard 1598: /* do{ */
1.187 brouard 1599: ax=0.;
1600: xx= xxs;
1601: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1602: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1603: /* 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)) */
1604: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1605: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1606: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1607: /* 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.192 brouard 1608: /* if (fx != fx){ */
1609: /* xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
1610: /* 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); */
1611: /* } */
1612: /* }while(fx != fx); */
1.187 brouard 1613:
1.191 brouard 1614: #ifdef DEBUGLINMIN
1615: 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);
1616: #endif
1.187 brouard 1617: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1618: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1619: /* fmin = f(p[j] + xmin * xi[j]) */
1620: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1621: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1622: #ifdef DEBUG
1623: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1624: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1625: #endif
1.191 brouard 1626: #ifdef DEBUGLINMIN
1627: printf("linmin end ");
1628: #endif
1.126 brouard 1629: for (j=1;j<=n;j++) {
1.188 brouard 1630: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187 brouard 1631: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189 brouard 1632: /* if(xxs <1.0) */
1633: /* 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 ); */
1.187 brouard 1634: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1635: }
1.189 brouard 1636: /* printf("\n"); */
1.191 brouard 1637: #ifdef DEBUGLINMIN
1638: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1639: for (j=1;j<=n;j++) {
1640: printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
1641: if(j % ncovmodel == 0)
1642: printf("\n");
1643: }
1644: #endif
1.126 brouard 1645: free_vector(xicom,1,n);
1646: free_vector(pcom,1,n);
1647: }
1648:
1649:
1650: /*************** powell ************************/
1.162 brouard 1651: /*
1652: Minimization of a function func of n variables. Input consists of an initial starting point
1653: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1654: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1655: such that failure to decrease by more than this amount on one iteration signals doneness. On
1656: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1657: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1658: */
1.126 brouard 1659: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1660: double (*func)(double []))
1661: {
1662: void linmin(double p[], double xi[], int n, double *fret,
1663: double (*func)(double []));
1664: int i,ibig,j;
1665: double del,t,*pt,*ptt,*xit;
1.181 brouard 1666: double directest;
1.126 brouard 1667: double fp,fptt;
1668: double *xits;
1669: int niterf, itmp;
1670:
1671: pt=vector(1,n);
1672: ptt=vector(1,n);
1673: xit=vector(1,n);
1674: xits=vector(1,n);
1675: *fret=(*func)(p);
1676: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1677: rcurr_time = time(NULL);
1.126 brouard 1678: for (*iter=1;;++(*iter)) {
1.187 brouard 1679: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1680: ibig=0;
1681: del=0.0;
1.157 brouard 1682: rlast_time=rcurr_time;
1683: /* (void) gettimeofday(&curr_time,&tzp); */
1684: rcurr_time = time(NULL);
1685: curr_time = *localtime(&rcurr_time);
1686: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1687: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1688: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1689: for (i=1;i<=n;i++) {
1.126 brouard 1690: printf(" %d %.12f",i, p[i]);
1691: fprintf(ficlog," %d %.12lf",i, p[i]);
1692: fprintf(ficrespow," %.12lf", p[i]);
1693: }
1694: printf("\n");
1695: fprintf(ficlog,"\n");
1696: fprintf(ficrespow,"\n");fflush(ficrespow);
1697: if(*iter <=3){
1.157 brouard 1698: tml = *localtime(&rcurr_time);
1699: strcpy(strcurr,asctime(&tml));
1700: rforecast_time=rcurr_time;
1.126 brouard 1701: itmp = strlen(strcurr);
1702: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1703: strcurr[itmp-1]='\0';
1.162 brouard 1704: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1705: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1706: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1707: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1708: forecast_time = *localtime(&rforecast_time);
1709: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1710: itmp = strlen(strfor);
1711: if(strfor[itmp-1]=='\n')
1712: strfor[itmp-1]='\0';
1.157 brouard 1713: 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);
1714: 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 1715: }
1716: }
1.187 brouard 1717: for (i=1;i<=n;i++) { /* For each direction i */
1718: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1719: fptt=(*fret);
1720: #ifdef DEBUG
1.164 brouard 1721: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1722: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1723: #endif
1.187 brouard 1724: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1725: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1726: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1727: /* Outputs are fret(new point p) p is updated and xit rescaled */
1728: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1729: /* because that direction will be replaced unless the gain del is small */
1730: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1731: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1732: /* with the new direction. */
1.126 brouard 1733: del=fabs(fptt-(*fret));
1734: ibig=i;
1735: }
1736: #ifdef DEBUG
1737: printf("%d %.12e",i,(*fret));
1738: fprintf(ficlog,"%d %.12e",i,(*fret));
1739: for (j=1;j<=n;j++) {
1740: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1741: printf(" x(%d)=%.12e",j,xit[j]);
1742: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1743: }
1744: for(j=1;j<=n;j++) {
1.162 brouard 1745: printf(" p(%d)=%.12e",j,p[j]);
1746: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1747: }
1748: printf("\n");
1749: fprintf(ficlog,"\n");
1750: #endif
1.187 brouard 1751: } /* end loop on each direction i */
1752: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1753: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1754: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1755: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1756: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1757: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1758: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1759: /* decreased of more than 3.84 */
1760: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1761: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1762: /* By adding 10 parameters more the gain should be 18.31 */
1763:
1764: /* Starting the program with initial values given by a former maximization will simply change */
1765: /* the scales of the directions and the directions, because the are reset to canonical directions */
1766: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1767: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1768: #ifdef DEBUG
1769: int k[2],l;
1770: k[0]=1;
1771: k[1]=-1;
1772: printf("Max: %.12e",(*func)(p));
1773: fprintf(ficlog,"Max: %.12e",(*func)(p));
1774: for (j=1;j<=n;j++) {
1775: printf(" %.12e",p[j]);
1776: fprintf(ficlog," %.12e",p[j]);
1777: }
1778: printf("\n");
1779: fprintf(ficlog,"\n");
1780: for(l=0;l<=1;l++) {
1781: for (j=1;j<=n;j++) {
1782: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1783: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1784: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1785: }
1786: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1787: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1788: }
1789: #endif
1790:
1791:
1792: free_vector(xit,1,n);
1793: free_vector(xits,1,n);
1794: free_vector(ptt,1,n);
1795: free_vector(pt,1,n);
1796: return;
1.192 brouard 1797: } /* enough precision */
1.126 brouard 1798: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1799: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1800: ptt[j]=2.0*p[j]-pt[j];
1801: xit[j]=p[j]-pt[j];
1802: pt[j]=p[j];
1803: }
1.181 brouard 1804: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1805: #ifdef POWELLF1F3
1806: #else
1.161 brouard 1807: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1808: #endif
1.162 brouard 1809: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1810: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1811: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1812: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1813: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1814: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1815: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1816: #ifdef NRCORIGINAL
1817: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1818: #else
1819: 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 1820: t= t- del*SQR(fp-fptt);
1.183 brouard 1821: #endif
1.182 brouard 1822: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1823: #ifdef DEBUG
1.181 brouard 1824: 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);
1825: 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 1826: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1827: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1828: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1829: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1830: 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);
1831: 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);
1832: #endif
1.183 brouard 1833: #ifdef POWELLORIGINAL
1834: if (t < 0.0) { /* Then we use it for new direction */
1835: #else
1.182 brouard 1836: if (directest*t < 0.0) { /* Contradiction between both tests */
1.192 brouard 1837: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1838: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1839: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1840: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1841: }
1.181 brouard 1842: if (directest < 0.0) { /* Then we use it for new direction */
1843: #endif
1.191 brouard 1844: #ifdef DEBUGLINMIN
1845: printf("Before linmin in direction P%d-P0\n",n);
1846: for (j=1;j<=n;j++) {
1847: printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1848: if(j % ncovmodel == 0)
1849: printf("\n");
1850: }
1851: #endif
1.187 brouard 1852: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1853: #ifdef DEBUGLINMIN
1854: for (j=1;j<=n;j++) {
1855: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1856: if(j % ncovmodel == 0)
1857: printf("\n");
1858: }
1859: #endif
1.126 brouard 1860: for (j=1;j<=n;j++) {
1.181 brouard 1861: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1862: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1863: }
1.181 brouard 1864: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1865: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1866:
1.126 brouard 1867: #ifdef DEBUG
1.164 brouard 1868: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1869: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1870: for(j=1;j<=n;j++){
1871: printf(" %.12e",xit[j]);
1872: fprintf(ficlog," %.12e",xit[j]);
1873: }
1874: printf("\n");
1875: fprintf(ficlog,"\n");
1876: #endif
1.192 brouard 1877: } /* end of t or directest negative */
1878: #ifdef POWELLF1F3
1879: #else
1.162 brouard 1880: } /* end if (fptt < fp) */
1.192 brouard 1881: #endif
1882: } /* loop iteration */
1.126 brouard 1883: }
1884:
1885: /**** Prevalence limit (stable or period prevalence) ****************/
1886:
1887: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1888: {
1889: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1890: matrix by transitions matrix until convergence is reached */
1.169 brouard 1891:
1.126 brouard 1892: int i, ii,j,k;
1893: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1894: /* double **matprod2(); */ /* test */
1.131 brouard 1895: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1896: double **newm;
1897: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1898:
1.126 brouard 1899: for (ii=1;ii<=nlstate+ndeath;ii++)
1900: for (j=1;j<=nlstate+ndeath;j++){
1901: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1902: }
1.169 brouard 1903:
1904: cov[1]=1.;
1905:
1906: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1907: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1908: newm=savm;
1909: /* Covariates have to be included here again */
1.138 brouard 1910: cov[2]=agefin;
1.187 brouard 1911: if(nagesqr==1)
1912: cov[3]= agefin*agefin;;
1.138 brouard 1913: for (k=1; k<=cptcovn;k++) {
1.198 ! brouard 1914: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])];
! 1915: /* 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 1916: }
1.186 brouard 1917: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198 ! brouard 1918: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2];
1.186 brouard 1919: for (k=1; k<=cptcovprod;k++) /* Useless */
1.198 ! brouard 1920: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.138 brouard 1921:
1922: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1923: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1924: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1925: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1926: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1927: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1928:
1.126 brouard 1929: savm=oldm;
1930: oldm=newm;
1931: maxmax=0.;
1932: for(j=1;j<=nlstate;j++){
1933: min=1.;
1934: max=0.;
1935: for(i=1; i<=nlstate; i++) {
1936: sumnew=0;
1937: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1938: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1939: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1.126 brouard 1940: max=FMAX(max,prlim[i][j]);
1941: min=FMIN(min,prlim[i][j]);
1942: }
1943: maxmin=max-min;
1944: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1945: } /* j loop */
1.126 brouard 1946: if(maxmax < ftolpl){
1947: return prlim;
1948: }
1.169 brouard 1949: } /* age loop */
1950: return prlim; /* should not reach here */
1.126 brouard 1951: }
1952:
1953: /*************** transition probabilities ***************/
1954:
1955: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1956: {
1.138 brouard 1957: /* According to parameters values stored in x and the covariate's values stored in cov,
1958: computes the probability to be observed in state j being in state i by appying the
1959: model to the ncovmodel covariates (including constant and age).
1960: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1961: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1962: ncth covariate in the global vector x is given by the formula:
1963: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1964: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1965: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1966: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1967: Outputs ps[i][j] the probability to be observed in j being in j according to
1968: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1969: */
1970: double s1, lnpijopii;
1.126 brouard 1971: /*double t34;*/
1.164 brouard 1972: int i,j, nc, ii, jj;
1.126 brouard 1973:
1974: for(i=1; i<= nlstate; i++){
1975: for(j=1; j<i;j++){
1.138 brouard 1976: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1977: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1978: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1979: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1980: }
1.138 brouard 1981: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1982: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1983: }
1984: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1985: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1986: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1987: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1988: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1989: }
1.138 brouard 1990: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1991: }
1992: }
1993:
1994: for(i=1; i<= nlstate; i++){
1995: s1=0;
1.131 brouard 1996: for(j=1; j<i; j++){
1.138 brouard 1997: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1998: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1999: }
2000: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 2001: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2002: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2003: }
1.138 brouard 2004: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 2005: ps[i][i]=1./(s1+1.);
1.138 brouard 2006: /* Computing other pijs */
1.126 brouard 2007: for(j=1; j<i; j++)
2008: ps[i][j]= exp(ps[i][j])*ps[i][i];
2009: for(j=i+1; j<=nlstate+ndeath; j++)
2010: ps[i][j]= exp(ps[i][j])*ps[i][i];
2011: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2012: } /* end i */
2013:
2014: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2015: for(jj=1; jj<= nlstate+ndeath; jj++){
2016: ps[ii][jj]=0;
2017: ps[ii][ii]=1;
2018: }
2019: }
2020:
1.145 brouard 2021:
2022: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2023: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2024: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2025: /* } */
2026: /* printf("\n "); */
2027: /* } */
2028: /* printf("\n ");printf("%lf ",cov[2]);*/
2029: /*
1.126 brouard 2030: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2031: goto end;*/
2032: return ps;
2033: }
2034:
2035: /**************** Product of 2 matrices ******************/
2036:
1.145 brouard 2037: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2038: {
2039: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2040: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2041: /* in, b, out are matrice of pointers which should have been initialized
2042: before: only the contents of out is modified. The function returns
2043: a pointer to pointers identical to out */
1.145 brouard 2044: int i, j, k;
1.126 brouard 2045: for(i=nrl; i<= nrh; i++)
1.145 brouard 2046: for(k=ncolol; k<=ncoloh; k++){
2047: out[i][k]=0.;
2048: for(j=ncl; j<=nch; j++)
2049: out[i][k] +=in[i][j]*b[j][k];
2050: }
1.126 brouard 2051: return out;
2052: }
2053:
2054:
2055: /************* Higher Matrix Product ***************/
2056:
2057: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2058: {
2059: /* Computes the transition matrix starting at age 'age' over
2060: 'nhstepm*hstepm*stepm' months (i.e. until
2061: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2062: nhstepm*hstepm matrices.
2063: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2064: (typically every 2 years instead of every month which is too big
2065: for the memory).
2066: Model is determined by parameters x and covariates have to be
2067: included manually here.
2068:
2069: */
2070:
2071: int i, j, d, h, k;
1.131 brouard 2072: double **out, cov[NCOVMAX+1];
1.126 brouard 2073: double **newm;
1.187 brouard 2074: double agexact;
1.126 brouard 2075:
2076: /* Hstepm could be zero and should return the unit matrix */
2077: for (i=1;i<=nlstate+ndeath;i++)
2078: for (j=1;j<=nlstate+ndeath;j++){
2079: oldm[i][j]=(i==j ? 1.0 : 0.0);
2080: po[i][j][0]=(i==j ? 1.0 : 0.0);
2081: }
2082: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2083: for(h=1; h <=nhstepm; h++){
2084: for(d=1; d <=hstepm; d++){
2085: newm=savm;
2086: /* Covariates have to be included here again */
2087: cov[1]=1.;
1.187 brouard 2088: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2089: cov[2]=agexact;
2090: if(nagesqr==1)
2091: cov[3]= agexact*agexact;
1.131 brouard 2092: for (k=1; k<=cptcovn;k++)
1.198 ! brouard 2093: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])];
1.186 brouard 2094: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2095: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198 ! brouard 2096: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.145 brouard 2097: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.198 ! brouard 2098: 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 2099:
2100:
2101: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2102: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2103: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2104: pmij(pmmij,cov,ncovmodel,x,nlstate));
2105: savm=oldm;
2106: oldm=newm;
2107: }
2108: for(i=1; i<=nlstate+ndeath; i++)
2109: for(j=1;j<=nlstate+ndeath;j++) {
2110: po[i][j][h]=newm[i][j];
1.128 brouard 2111: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2112: }
1.128 brouard 2113: /*printf("h=%d ",h);*/
1.126 brouard 2114: } /* end h */
1.128 brouard 2115: /* printf("\n H=%d \n",h); */
1.126 brouard 2116: return po;
2117: }
2118:
1.162 brouard 2119: #ifdef NLOPT
2120: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2121: double fret;
2122: double *xt;
2123: int j;
2124: myfunc_data *d2 = (myfunc_data *) pd;
2125: /* xt = (p1-1); */
2126: xt=vector(1,n);
2127: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2128:
2129: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2130: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2131: printf("Function = %.12lf ",fret);
2132: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2133: printf("\n");
2134: free_vector(xt,1,n);
2135: return fret;
2136: }
2137: #endif
1.126 brouard 2138:
2139: /*************** log-likelihood *************/
2140: double func( double *x)
2141: {
2142: int i, ii, j, k, mi, d, kk;
1.131 brouard 2143: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2144: double **out;
2145: double sw; /* Sum of weights */
2146: double lli; /* Individual log likelihood */
2147: int s1, s2;
2148: double bbh, survp;
2149: long ipmx;
1.187 brouard 2150: double agexact;
1.126 brouard 2151: /*extern weight */
2152: /* We are differentiating ll according to initial status */
2153: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2154: /*for(i=1;i<imx;i++)
2155: printf(" %d\n",s[4][i]);
2156: */
1.162 brouard 2157:
2158: ++countcallfunc;
2159:
1.126 brouard 2160: cov[1]=1.;
2161:
2162: for(k=1; k<=nlstate; k++) ll[k]=0.;
2163:
2164: if(mle==1){
2165: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2166: /* Computes the values of the ncovmodel covariates of the model
2167: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2168: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2169: to be observed in j being in i according to the model.
2170: */
1.145 brouard 2171: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2172: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2173: }
1.137 brouard 2174: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2175: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2176: has been calculated etc */
1.126 brouard 2177: for(mi=1; mi<= wav[i]-1; mi++){
2178: for (ii=1;ii<=nlstate+ndeath;ii++)
2179: for (j=1;j<=nlstate+ndeath;j++){
2180: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2181: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2182: }
2183: for(d=0; d<dh[mi][i]; d++){
2184: newm=savm;
1.187 brouard 2185: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2186: cov[2]=agexact;
2187: if(nagesqr==1)
2188: cov[3]= agexact*agexact;
1.126 brouard 2189: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2190: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2191: }
2192: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2193: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2194: savm=oldm;
2195: oldm=newm;
2196: } /* end mult */
2197:
2198: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2199: /* But now since version 0.9 we anticipate for bias at large stepm.
2200: * If stepm is larger than one month (smallest stepm) and if the exact delay
2201: * (in months) between two waves is not a multiple of stepm, we rounded to
2202: * the nearest (and in case of equal distance, to the lowest) interval but now
2203: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2204: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2205: * probability in order to take into account the bias as a fraction of the way
2206: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2207: * -stepm/2 to stepm/2 .
2208: * For stepm=1 the results are the same as for previous versions of Imach.
2209: * For stepm > 1 the results are less biased than in previous versions.
2210: */
2211: s1=s[mw[mi][i]][i];
2212: s2=s[mw[mi+1][i]][i];
2213: bbh=(double)bh[mi][i]/(double)stepm;
2214: /* bias bh is positive if real duration
2215: * is higher than the multiple of stepm and negative otherwise.
2216: */
2217: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2218: if( s2 > nlstate){
2219: /* i.e. if s2 is a death state and if the date of death is known
2220: then the contribution to the likelihood is the probability to
2221: die between last step unit time and current step unit time,
2222: which is also equal to probability to die before dh
2223: minus probability to die before dh-stepm .
2224: In version up to 0.92 likelihood was computed
2225: as if date of death was unknown. Death was treated as any other
2226: health state: the date of the interview describes the actual state
2227: and not the date of a change in health state. The former idea was
2228: to consider that at each interview the state was recorded
2229: (healthy, disable or death) and IMaCh was corrected; but when we
2230: introduced the exact date of death then we should have modified
2231: the contribution of an exact death to the likelihood. This new
2232: contribution is smaller and very dependent of the step unit
2233: stepm. It is no more the probability to die between last interview
2234: and month of death but the probability to survive from last
2235: interview up to one month before death multiplied by the
2236: probability to die within a month. Thanks to Chris
2237: Jackson for correcting this bug. Former versions increased
2238: mortality artificially. The bad side is that we add another loop
2239: which slows down the processing. The difference can be up to 10%
2240: lower mortality.
2241: */
1.183 brouard 2242: /* If, at the beginning of the maximization mostly, the
2243: cumulative probability or probability to be dead is
2244: constant (ie = 1) over time d, the difference is equal to
2245: 0. out[s1][3] = savm[s1][3]: probability, being at state
2246: s1 at precedent wave, to be dead a month before current
2247: wave is equal to probability, being at state s1 at
2248: precedent wave, to be dead at mont of the current
2249: wave. Then the observed probability (that this person died)
2250: is null according to current estimated parameter. In fact,
2251: it should be very low but not zero otherwise the log go to
2252: infinity.
2253: */
2254: /* #ifdef INFINITYORIGINAL */
2255: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2256: /* #else */
2257: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2258: /* lli=log(mytinydouble); */
2259: /* else */
2260: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2261: /* #endif */
2262: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2263:
2264: } else if (s2==-2) {
2265: for (j=1,survp=0. ; j<=nlstate; j++)
2266: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2267: /*survp += out[s1][j]; */
2268: lli= log(survp);
2269: }
2270:
2271: else if (s2==-4) {
2272: for (j=3,survp=0. ; j<=nlstate; j++)
2273: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2274: lli= log(survp);
2275: }
2276:
2277: else if (s2==-5) {
2278: for (j=1,survp=0. ; j<=2; j++)
2279: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2280: lli= log(survp);
2281: }
2282:
2283: else{
2284: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2285: /* 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 */
2286: }
2287: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2288: /*if(lli ==000.0)*/
2289: /*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); */
2290: ipmx +=1;
2291: sw += weight[i];
2292: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2293: /* if (lli < log(mytinydouble)){ */
2294: /* 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); */
2295: /* 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]); */
2296: /* } */
1.126 brouard 2297: } /* end of wave */
2298: } /* end of individual */
2299: } else if(mle==2){
2300: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2301: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2302: for(mi=1; mi<= wav[i]-1; mi++){
2303: for (ii=1;ii<=nlstate+ndeath;ii++)
2304: for (j=1;j<=nlstate+ndeath;j++){
2305: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2306: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2307: }
2308: for(d=0; d<=dh[mi][i]; d++){
2309: newm=savm;
1.187 brouard 2310: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2311: cov[2]=agexact;
2312: if(nagesqr==1)
2313: cov[3]= agexact*agexact;
1.126 brouard 2314: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2315: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2316: }
2317: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2318: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2319: savm=oldm;
2320: oldm=newm;
2321: } /* end mult */
2322:
2323: s1=s[mw[mi][i]][i];
2324: s2=s[mw[mi+1][i]][i];
2325: bbh=(double)bh[mi][i]/(double)stepm;
2326: 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 */
2327: ipmx +=1;
2328: sw += weight[i];
2329: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2330: } /* end of wave */
2331: } /* end of individual */
2332: } else if(mle==3){ /* exponential inter-extrapolation */
2333: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2334: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2335: for(mi=1; mi<= wav[i]-1; mi++){
2336: for (ii=1;ii<=nlstate+ndeath;ii++)
2337: for (j=1;j<=nlstate+ndeath;j++){
2338: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2339: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2340: }
2341: for(d=0; d<dh[mi][i]; d++){
2342: newm=savm;
1.187 brouard 2343: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2344: cov[2]=agexact;
2345: if(nagesqr==1)
2346: cov[3]= agexact*agexact;
1.126 brouard 2347: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2348: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2349: }
2350: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2351: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2352: savm=oldm;
2353: oldm=newm;
2354: } /* end mult */
2355:
2356: s1=s[mw[mi][i]][i];
2357: s2=s[mw[mi+1][i]][i];
2358: bbh=(double)bh[mi][i]/(double)stepm;
2359: 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 */
2360: ipmx +=1;
2361: sw += weight[i];
2362: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2363: } /* end of wave */
2364: } /* end of individual */
2365: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2366: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2367: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2368: for(mi=1; mi<= wav[i]-1; mi++){
2369: for (ii=1;ii<=nlstate+ndeath;ii++)
2370: for (j=1;j<=nlstate+ndeath;j++){
2371: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2372: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2373: }
2374: for(d=0; d<dh[mi][i]; d++){
2375: newm=savm;
1.187 brouard 2376: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2377: cov[2]=agexact;
2378: if(nagesqr==1)
2379: cov[3]= agexact*agexact;
1.126 brouard 2380: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2381: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2382: }
2383:
2384: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2385: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2386: savm=oldm;
2387: oldm=newm;
2388: } /* end mult */
2389:
2390: s1=s[mw[mi][i]][i];
2391: s2=s[mw[mi+1][i]][i];
2392: if( s2 > nlstate){
2393: lli=log(out[s1][s2] - savm[s1][s2]);
2394: }else{
2395: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2396: }
2397: ipmx +=1;
2398: sw += weight[i];
2399: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2400: /* 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]); */
2401: } /* end of wave */
2402: } /* end of individual */
2403: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2404: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2405: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2406: for(mi=1; mi<= wav[i]-1; mi++){
2407: for (ii=1;ii<=nlstate+ndeath;ii++)
2408: for (j=1;j<=nlstate+ndeath;j++){
2409: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2410: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2411: }
2412: for(d=0; d<dh[mi][i]; d++){
2413: newm=savm;
1.187 brouard 2414: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2415: cov[2]=agexact;
2416: if(nagesqr==1)
2417: cov[3]= agexact*agexact;
1.126 brouard 2418: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2419: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2420: }
2421:
2422: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2423: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2424: savm=oldm;
2425: oldm=newm;
2426: } /* end mult */
2427:
2428: s1=s[mw[mi][i]][i];
2429: s2=s[mw[mi+1][i]][i];
2430: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2431: ipmx +=1;
2432: sw += weight[i];
2433: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2434: /*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]);*/
2435: } /* end of wave */
2436: } /* end of individual */
2437: } /* End of if */
2438: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2439: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2440: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2441: return -l;
2442: }
2443:
2444: /*************** log-likelihood *************/
2445: double funcone( double *x)
2446: {
2447: /* Same as likeli but slower because of a lot of printf and if */
2448: int i, ii, j, k, mi, d, kk;
1.131 brouard 2449: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2450: double **out;
2451: double lli; /* Individual log likelihood */
2452: double llt;
2453: int s1, s2;
2454: double bbh, survp;
1.187 brouard 2455: double agexact;
1.126 brouard 2456: /*extern weight */
2457: /* We are differentiating ll according to initial status */
2458: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2459: /*for(i=1;i<imx;i++)
2460: printf(" %d\n",s[4][i]);
2461: */
2462: cov[1]=1.;
2463:
2464: for(k=1; k<=nlstate; k++) ll[k]=0.;
2465:
2466: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2467: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2468: for(mi=1; mi<= wav[i]-1; mi++){
2469: for (ii=1;ii<=nlstate+ndeath;ii++)
2470: for (j=1;j<=nlstate+ndeath;j++){
2471: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2472: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2473: }
2474: for(d=0; d<dh[mi][i]; d++){
2475: newm=savm;
1.187 brouard 2476: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2477: cov[2]=agexact;
2478: if(nagesqr==1)
2479: cov[3]= agexact*agexact;
1.126 brouard 2480: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2481: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2482: }
1.187 brouard 2483:
1.145 brouard 2484: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2485: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2486: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2487: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2488: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2489: savm=oldm;
2490: oldm=newm;
2491: } /* end mult */
2492:
2493: s1=s[mw[mi][i]][i];
2494: s2=s[mw[mi+1][i]][i];
2495: bbh=(double)bh[mi][i]/(double)stepm;
2496: /* bias is positive if real duration
2497: * is higher than the multiple of stepm and negative otherwise.
2498: */
2499: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2500: lli=log(out[s1][s2] - savm[s1][s2]);
2501: } else if (s2==-2) {
2502: for (j=1,survp=0. ; j<=nlstate; j++)
2503: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2504: lli= log(survp);
2505: }else if (mle==1){
2506: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2507: } else if(mle==2){
2508: 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 */
2509: } else if(mle==3){ /* exponential inter-extrapolation */
2510: 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 */
2511: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2512: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2513: } else{ /* mle=0 back to 1 */
2514: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2515: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2516: } /* End of if */
2517: ipmx +=1;
2518: sw += weight[i];
2519: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2520: /*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 2521: if(globpr){
1.141 brouard 2522: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2523: %11.6f %11.6f %11.6f ", \
2524: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2525: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2526: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2527: llt +=ll[k]*gipmx/gsw;
2528: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2529: }
2530: fprintf(ficresilk," %10.6f\n", -llt);
2531: }
2532: } /* end of wave */
2533: } /* end of individual */
2534: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2535: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2536: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2537: if(globpr==0){ /* First time we count the contributions and weights */
2538: gipmx=ipmx;
2539: gsw=sw;
2540: }
2541: return -l;
2542: }
2543:
2544:
2545: /*************** function likelione ***********/
2546: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2547: {
2548: /* This routine should help understanding what is done with
2549: the selection of individuals/waves and
2550: to check the exact contribution to the likelihood.
2551: Plotting could be done.
2552: */
2553: int k;
2554:
2555: if(*globpri !=0){ /* Just counts and sums, no printings */
2556: strcpy(fileresilk,"ilk");
2557: strcat(fileresilk,fileres);
2558: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2559: printf("Problem with resultfile: %s\n", fileresilk);
2560: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2561: }
2562: fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
2563: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2564: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2565: for(k=1; k<=nlstate; k++)
2566: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2567: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2568: }
2569:
2570: *fretone=(*funcone)(p);
2571: if(*globpri !=0){
2572: fclose(ficresilk);
2573: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2574: fflush(fichtm);
2575: }
2576: return;
2577: }
2578:
2579:
2580: /*********** Maximum Likelihood Estimation ***************/
2581:
2582: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2583: {
1.165 brouard 2584: int i,j, iter=0;
1.126 brouard 2585: double **xi;
2586: double fret;
2587: double fretone; /* Only one call to likelihood */
2588: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2589:
2590: #ifdef NLOPT
2591: int creturn;
2592: nlopt_opt opt;
2593: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2594: double *lb;
2595: double minf; /* the minimum objective value, upon return */
2596: double * p1; /* Shifted parameters from 0 instead of 1 */
2597: myfunc_data dinst, *d = &dinst;
2598: #endif
2599:
2600:
1.126 brouard 2601: xi=matrix(1,npar,1,npar);
2602: for (i=1;i<=npar;i++)
2603: for (j=1;j<=npar;j++)
2604: xi[i][j]=(i==j ? 1.0 : 0.0);
2605: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2606: strcpy(filerespow,"pow");
2607: strcat(filerespow,fileres);
2608: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2609: printf("Problem with resultfile: %s\n", filerespow);
2610: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2611: }
2612: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2613: for (i=1;i<=nlstate;i++)
2614: for(j=1;j<=nlstate+ndeath;j++)
2615: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2616: fprintf(ficrespow,"\n");
1.162 brouard 2617: #ifdef POWELL
1.126 brouard 2618: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2619: #endif
1.126 brouard 2620:
1.162 brouard 2621: #ifdef NLOPT
2622: #ifdef NEWUOA
2623: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2624: #else
2625: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2626: #endif
2627: lb=vector(0,npar-1);
2628: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2629: nlopt_set_lower_bounds(opt, lb);
2630: nlopt_set_initial_step1(opt, 0.1);
2631:
2632: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2633: d->function = func;
2634: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2635: nlopt_set_min_objective(opt, myfunc, d);
2636: nlopt_set_xtol_rel(opt, ftol);
2637: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2638: printf("nlopt failed! %d\n",creturn);
2639: }
2640: else {
2641: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2642: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2643: iter=1; /* not equal */
2644: }
2645: nlopt_destroy(opt);
2646: #endif
1.126 brouard 2647: free_matrix(xi,1,npar,1,npar);
2648: fclose(ficrespow);
1.180 brouard 2649: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2650: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2651: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2652:
2653: }
2654:
2655: /**** Computes Hessian and covariance matrix ***/
2656: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2657: {
2658: double **a,**y,*x,pd;
2659: double **hess;
1.164 brouard 2660: int i, j;
1.126 brouard 2661: int *indx;
2662:
2663: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2664: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2665: void lubksb(double **a, int npar, int *indx, double b[]) ;
2666: void ludcmp(double **a, int npar, int *indx, double *d) ;
2667: double gompertz(double p[]);
2668: hess=matrix(1,npar,1,npar);
2669:
2670: printf("\nCalculation of the hessian matrix. Wait...\n");
2671: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2672: for (i=1;i<=npar;i++){
2673: printf("%d",i);fflush(stdout);
2674: fprintf(ficlog,"%d",i);fflush(ficlog);
2675:
2676: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2677:
2678: /* printf(" %f ",p[i]);
2679: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2680: }
2681:
2682: for (i=1;i<=npar;i++) {
2683: for (j=1;j<=npar;j++) {
2684: if (j>i) {
2685: printf(".%d%d",i,j);fflush(stdout);
2686: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2687: hess[i][j]=hessij(p,delti,i,j,func,npar);
2688:
2689: hess[j][i]=hess[i][j];
2690: /*printf(" %lf ",hess[i][j]);*/
2691: }
2692: }
2693: }
2694: printf("\n");
2695: fprintf(ficlog,"\n");
2696:
2697: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2698: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2699:
2700: a=matrix(1,npar,1,npar);
2701: y=matrix(1,npar,1,npar);
2702: x=vector(1,npar);
2703: indx=ivector(1,npar);
2704: for (i=1;i<=npar;i++)
2705: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2706: ludcmp(a,npar,indx,&pd);
2707:
2708: for (j=1;j<=npar;j++) {
2709: for (i=1;i<=npar;i++) x[i]=0;
2710: x[j]=1;
2711: lubksb(a,npar,indx,x);
2712: for (i=1;i<=npar;i++){
2713: matcov[i][j]=x[i];
2714: }
2715: }
2716:
2717: printf("\n#Hessian matrix#\n");
2718: fprintf(ficlog,"\n#Hessian matrix#\n");
2719: for (i=1;i<=npar;i++) {
2720: for (j=1;j<=npar;j++) {
2721: printf("%.3e ",hess[i][j]);
2722: fprintf(ficlog,"%.3e ",hess[i][j]);
2723: }
2724: printf("\n");
2725: fprintf(ficlog,"\n");
2726: }
2727:
2728: /* Recompute Inverse */
2729: for (i=1;i<=npar;i++)
2730: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2731: ludcmp(a,npar,indx,&pd);
2732:
2733: /* printf("\n#Hessian matrix recomputed#\n");
2734:
2735: for (j=1;j<=npar;j++) {
2736: for (i=1;i<=npar;i++) x[i]=0;
2737: x[j]=1;
2738: lubksb(a,npar,indx,x);
2739: for (i=1;i<=npar;i++){
2740: y[i][j]=x[i];
2741: printf("%.3e ",y[i][j]);
2742: fprintf(ficlog,"%.3e ",y[i][j]);
2743: }
2744: printf("\n");
2745: fprintf(ficlog,"\n");
2746: }
2747: */
2748:
2749: free_matrix(a,1,npar,1,npar);
2750: free_matrix(y,1,npar,1,npar);
2751: free_vector(x,1,npar);
2752: free_ivector(indx,1,npar);
2753: free_matrix(hess,1,npar,1,npar);
2754:
2755:
2756: }
2757:
2758: /*************** hessian matrix ****************/
2759: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2760: {
2761: int i;
2762: int l=1, lmax=20;
2763: double k1,k2;
1.132 brouard 2764: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2765: double res;
2766: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2767: double fx;
2768: int k=0,kmax=10;
2769: double l1;
2770:
2771: fx=func(x);
2772: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2773: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2774: l1=pow(10,l);
2775: delts=delt;
2776: for(k=1 ; k <kmax; k=k+1){
2777: delt = delta*(l1*k);
2778: p2[theta]=x[theta] +delt;
1.145 brouard 2779: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2780: p2[theta]=x[theta]-delt;
2781: k2=func(p2)-fx;
2782: /*res= (k1-2.0*fx+k2)/delt/delt; */
2783: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2784:
1.132 brouard 2785: #ifdef DEBUGHESS
1.126 brouard 2786: 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);
2787: 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);
2788: #endif
2789: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2790: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2791: k=kmax;
2792: }
2793: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2794: k=kmax; l=lmax*10;
1.126 brouard 2795: }
2796: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2797: delts=delt;
2798: }
2799: }
2800: }
2801: delti[theta]=delts;
2802: return res;
2803:
2804: }
2805:
2806: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2807: {
2808: int i;
1.164 brouard 2809: int l=1, lmax=20;
1.126 brouard 2810: double k1,k2,k3,k4,res,fx;
1.132 brouard 2811: double p2[MAXPARM+1];
1.126 brouard 2812: int k;
2813:
2814: fx=func(x);
2815: for (k=1; k<=2; k++) {
2816: for (i=1;i<=npar;i++) p2[i]=x[i];
2817: p2[thetai]=x[thetai]+delti[thetai]/k;
2818: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2819: k1=func(p2)-fx;
2820:
2821: p2[thetai]=x[thetai]+delti[thetai]/k;
2822: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2823: k2=func(p2)-fx;
2824:
2825: p2[thetai]=x[thetai]-delti[thetai]/k;
2826: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2827: k3=func(p2)-fx;
2828:
2829: p2[thetai]=x[thetai]-delti[thetai]/k;
2830: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2831: k4=func(p2)-fx;
2832: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2833: #ifdef DEBUG
2834: 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);
2835: 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);
2836: #endif
2837: }
2838: return res;
2839: }
2840:
2841: /************** Inverse of matrix **************/
2842: void ludcmp(double **a, int n, int *indx, double *d)
2843: {
2844: int i,imax,j,k;
2845: double big,dum,sum,temp;
2846: double *vv;
2847:
2848: vv=vector(1,n);
2849: *d=1.0;
2850: for (i=1;i<=n;i++) {
2851: big=0.0;
2852: for (j=1;j<=n;j++)
2853: if ((temp=fabs(a[i][j])) > big) big=temp;
2854: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2855: vv[i]=1.0/big;
2856: }
2857: for (j=1;j<=n;j++) {
2858: for (i=1;i<j;i++) {
2859: sum=a[i][j];
2860: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2861: a[i][j]=sum;
2862: }
2863: big=0.0;
2864: for (i=j;i<=n;i++) {
2865: sum=a[i][j];
2866: for (k=1;k<j;k++)
2867: sum -= a[i][k]*a[k][j];
2868: a[i][j]=sum;
2869: if ( (dum=vv[i]*fabs(sum)) >= big) {
2870: big=dum;
2871: imax=i;
2872: }
2873: }
2874: if (j != imax) {
2875: for (k=1;k<=n;k++) {
2876: dum=a[imax][k];
2877: a[imax][k]=a[j][k];
2878: a[j][k]=dum;
2879: }
2880: *d = -(*d);
2881: vv[imax]=vv[j];
2882: }
2883: indx[j]=imax;
2884: if (a[j][j] == 0.0) a[j][j]=TINY;
2885: if (j != n) {
2886: dum=1.0/(a[j][j]);
2887: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2888: }
2889: }
2890: free_vector(vv,1,n); /* Doesn't work */
2891: ;
2892: }
2893:
2894: void lubksb(double **a, int n, int *indx, double b[])
2895: {
2896: int i,ii=0,ip,j;
2897: double sum;
2898:
2899: for (i=1;i<=n;i++) {
2900: ip=indx[i];
2901: sum=b[ip];
2902: b[ip]=b[i];
2903: if (ii)
2904: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2905: else if (sum) ii=i;
2906: b[i]=sum;
2907: }
2908: for (i=n;i>=1;i--) {
2909: sum=b[i];
2910: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2911: b[i]=sum/a[i][i];
2912: }
2913: }
2914:
2915: void pstamp(FILE *fichier)
2916: {
1.196 brouard 2917: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126 brouard 2918: }
2919:
2920: /************ Frequencies ********************/
2921: 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[])
2922: { /* Some frequencies */
2923:
1.164 brouard 2924: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2925: int first;
2926: double ***freq; /* Frequencies */
2927: double *pp, **prop;
2928: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2929: char fileresp[FILENAMELENGTH];
2930:
2931: pp=vector(1,nlstate);
2932: prop=matrix(1,nlstate,iagemin,iagemax+3);
2933: strcpy(fileresp,"p");
2934: strcat(fileresp,fileres);
2935: if((ficresp=fopen(fileresp,"w"))==NULL) {
2936: printf("Problem with prevalence resultfile: %s\n", fileresp);
2937: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2938: exit(0);
2939: }
2940: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2941: j1=0;
2942:
2943: j=cptcoveff;
2944: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2945:
2946: first=1;
2947:
1.169 brouard 2948: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2949: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2950: /* j1++; */
1.145 brouard 2951: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2952: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2953: scanf("%d", i);*/
2954: for (i=-5; i<=nlstate+ndeath; i++)
2955: for (jk=-5; jk<=nlstate+ndeath; jk++)
2956: for(m=iagemin; m <= iagemax+3; m++)
2957: freq[i][jk][m]=0;
1.143 brouard 2958:
2959: for (i=1; i<=nlstate; i++)
2960: for(m=iagemin; m <= iagemax+3; m++)
2961: prop[i][m]=0;
1.126 brouard 2962:
2963: dateintsum=0;
2964: k2cpt=0;
2965: for (i=1; i<=imx; i++) {
2966: bool=1;
1.144 brouard 2967: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2968: for (z1=1; z1<=cptcoveff; z1++)
1.198 ! brouard 2969: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145 brouard 2970: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2971: bool=0;
1.198 ! brouard 2972: /* 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",
! 2973: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
! 2974: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
! 2975: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144 brouard 2976: }
1.126 brouard 2977: }
1.144 brouard 2978:
1.126 brouard 2979: if (bool==1){
2980: for(m=firstpass; m<=lastpass; m++){
2981: k2=anint[m][i]+(mint[m][i]/12.);
2982: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2983: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2984: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2985: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2986: if (m<lastpass) {
2987: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2988: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2989: }
2990:
2991: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2992: dateintsum=dateintsum+k2;
2993: k2cpt++;
2994: }
2995: /*}*/
2996: }
2997: }
1.145 brouard 2998: } /* end i */
1.126 brouard 2999:
3000: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3001: pstamp(ficresp);
3002: if (cptcovn>0) {
3003: fprintf(ficresp, "\n#********** Variable ");
1.198 ! brouard 3004: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 3005: fprintf(ficresp, "**********\n#");
1.143 brouard 3006: fprintf(ficlog, "\n#********** Variable ");
1.198 ! brouard 3007: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143 brouard 3008: fprintf(ficlog, "**********\n#");
1.126 brouard 3009: }
3010: for(i=1; i<=nlstate;i++)
3011: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3012: fprintf(ficresp, "\n");
3013:
3014: for(i=iagemin; i <= iagemax+3; i++){
3015: if(i==iagemax+3){
3016: fprintf(ficlog,"Total");
3017: }else{
3018: if(first==1){
3019: first=0;
3020: printf("See log file for details...\n");
3021: }
3022: fprintf(ficlog,"Age %d", i);
3023: }
3024: for(jk=1; jk <=nlstate ; jk++){
3025: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3026: pp[jk] += freq[jk][m][i];
3027: }
3028: for(jk=1; jk <=nlstate ; jk++){
3029: for(m=-1, pos=0; m <=0 ; m++)
3030: pos += freq[jk][m][i];
3031: if(pp[jk]>=1.e-10){
3032: if(first==1){
1.132 brouard 3033: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3034: }
3035: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3036: }else{
3037: if(first==1)
3038: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3039: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3040: }
3041: }
3042:
3043: for(jk=1; jk <=nlstate ; jk++){
3044: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3045: pp[jk] += freq[jk][m][i];
3046: }
3047: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3048: pos += pp[jk];
3049: posprop += prop[jk][i];
3050: }
3051: for(jk=1; jk <=nlstate ; jk++){
3052: if(pos>=1.e-5){
3053: if(first==1)
3054: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3055: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3056: }else{
3057: if(first==1)
3058: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3059: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3060: }
3061: if( i <= iagemax){
3062: if(pos>=1.e-5){
3063: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3064: /*probs[i][jk][j1]= pp[jk]/pos;*/
3065: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3066: }
3067: else
3068: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3069: }
3070: }
3071:
3072: for(jk=-1; jk <=nlstate+ndeath; jk++)
3073: for(m=-1; m <=nlstate+ndeath; m++)
3074: if(freq[jk][m][i] !=0 ) {
3075: if(first==1)
3076: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3077: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3078: }
3079: if(i <= iagemax)
3080: fprintf(ficresp,"\n");
3081: if(first==1)
3082: printf("Others in log...\n");
3083: fprintf(ficlog,"\n");
3084: }
1.145 brouard 3085: /*}*/
1.126 brouard 3086: }
3087: dateintmean=dateintsum/k2cpt;
3088:
3089: fclose(ficresp);
3090: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3091: free_vector(pp,1,nlstate);
3092: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3093: /* End of Freq */
3094: }
3095:
3096: /************ Prevalence ********************/
3097: 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)
3098: {
3099: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3100: in each health status at the date of interview (if between dateprev1 and dateprev2).
3101: We still use firstpass and lastpass as another selection.
3102: */
3103:
1.164 brouard 3104: int i, m, jk, j1, bool, z1,j;
3105:
3106: double **prop;
3107: double posprop;
1.126 brouard 3108: double y2; /* in fractional years */
3109: int iagemin, iagemax;
1.145 brouard 3110: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3111:
3112: iagemin= (int) agemin;
3113: iagemax= (int) agemax;
3114: /*pp=vector(1,nlstate);*/
3115: prop=matrix(1,nlstate,iagemin,iagemax+3);
3116: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3117: j1=0;
3118:
1.145 brouard 3119: /*j=cptcoveff;*/
1.126 brouard 3120: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3121:
1.145 brouard 3122: first=1;
3123: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3124: /*for(i1=1; i1<=ncodemax[k1];i1++){
3125: j1++;*/
1.126 brouard 3126:
3127: for (i=1; i<=nlstate; i++)
3128: for(m=iagemin; m <= iagemax+3; m++)
3129: prop[i][m]=0.0;
3130:
3131: for (i=1; i<=imx; i++) { /* Each individual */
3132: bool=1;
3133: if (cptcovn>0) {
3134: for (z1=1; z1<=cptcoveff; z1++)
1.198 ! brouard 3135: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
1.126 brouard 3136: bool=0;
3137: }
3138: if (bool==1) {
3139: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3140: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3141: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3142: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3143: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3144: 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);
3145: if (s[m][i]>0 && s[m][i]<=nlstate) {
3146: /*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]]);*/
3147: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3148: prop[s[m][i]][iagemax+3] += weight[i];
3149: }
3150: }
3151: } /* end selection of waves */
3152: }
3153: }
3154: for(i=iagemin; i <= iagemax+3; i++){
3155: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3156: posprop += prop[jk][i];
3157: }
1.145 brouard 3158:
1.126 brouard 3159: for(jk=1; jk <=nlstate ; jk++){
3160: if( i <= iagemax){
3161: if(posprop>=1.e-5){
3162: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3163: } else{
3164: if(first==1){
3165: first=0;
3166: 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]);
3167: }
3168: }
1.126 brouard 3169: }
3170: }/* end jk */
3171: }/* end i */
1.145 brouard 3172: /*} *//* end i1 */
3173: } /* end j1 */
1.126 brouard 3174:
3175: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3176: /*free_vector(pp,1,nlstate);*/
3177: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3178: } /* End of prevalence */
3179:
3180: /************* Waves Concatenation ***************/
3181:
3182: 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)
3183: {
3184: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3185: Death is a valid wave (if date is known).
3186: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3187: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3188: and mw[mi+1][i]. dh depends on stepm.
3189: */
3190:
3191: int i, mi, m;
3192: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3193: double sum=0., jmean=0.;*/
3194: int first;
3195: int j, k=0,jk, ju, jl;
3196: double sum=0.;
3197: first=0;
1.164 brouard 3198: jmin=100000;
1.126 brouard 3199: jmax=-1;
3200: jmean=0.;
3201: for(i=1; i<=imx; i++){
3202: mi=0;
3203: m=firstpass;
3204: while(s[m][i] <= nlstate){
3205: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3206: mw[++mi][i]=m;
3207: if(m >=lastpass)
3208: break;
3209: else
3210: m++;
3211: }/* end while */
3212: if (s[m][i] > nlstate){
3213: mi++; /* Death is another wave */
3214: /* if(mi==0) never been interviewed correctly before death */
3215: /* Only death is a correct wave */
3216: mw[mi][i]=m;
3217: }
3218:
3219: wav[i]=mi;
3220: if(mi==0){
3221: nbwarn++;
3222: if(first==0){
3223: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3224: first=1;
3225: }
3226: if(first==1){
3227: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3228: }
3229: } /* end mi==0 */
3230: } /* End individuals */
3231:
3232: for(i=1; i<=imx; i++){
3233: for(mi=1; mi<wav[i];mi++){
3234: if (stepm <=0)
3235: dh[mi][i]=1;
3236: else{
3237: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3238: if (agedc[i] < 2*AGESUP) {
3239: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3240: if(j==0) j=1; /* Survives at least one month after exam */
3241: else if(j<0){
3242: nberr++;
3243: 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]);
3244: j=1; /* Temporary Dangerous patch */
3245: 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);
3246: 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]);
3247: 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);
3248: }
3249: k=k+1;
3250: if (j >= jmax){
3251: jmax=j;
3252: ijmax=i;
3253: }
3254: if (j <= jmin){
3255: jmin=j;
3256: ijmin=i;
3257: }
3258: sum=sum+j;
3259: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3260: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3261: }
3262: }
3263: else{
3264: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3265: /* 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]); */
3266:
3267: k=k+1;
3268: if (j >= jmax) {
3269: jmax=j;
3270: ijmax=i;
3271: }
3272: else if (j <= jmin){
3273: jmin=j;
3274: ijmin=i;
3275: }
3276: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3277: /*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]);*/
3278: if(j<0){
3279: nberr++;
3280: 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]);
3281: 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]);
3282: }
3283: sum=sum+j;
3284: }
3285: jk= j/stepm;
3286: jl= j -jk*stepm;
3287: ju= j -(jk+1)*stepm;
3288: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3289: if(jl==0){
3290: dh[mi][i]=jk;
3291: bh[mi][i]=0;
3292: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3293: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3294: dh[mi][i]=jk+1;
3295: bh[mi][i]=ju;
3296: }
3297: }else{
3298: if(jl <= -ju){
3299: dh[mi][i]=jk;
3300: bh[mi][i]=jl; /* bias is positive if real duration
3301: * is higher than the multiple of stepm and negative otherwise.
3302: */
3303: }
3304: else{
3305: dh[mi][i]=jk+1;
3306: bh[mi][i]=ju;
3307: }
3308: if(dh[mi][i]==0){
3309: dh[mi][i]=1; /* At least one step */
3310: bh[mi][i]=ju; /* At least one step */
3311: /* 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);*/
3312: }
3313: } /* end if mle */
3314: }
3315: } /* end wave */
3316: }
3317: jmean=sum/k;
3318: 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 3319: 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 3320: }
3321:
3322: /*********** Tricode ****************************/
1.145 brouard 3323: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3324: {
1.144 brouard 3325: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3326: /* 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 3327: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3328: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3329: * nbcode[Tvar[j]][1]=
1.144 brouard 3330: */
1.130 brouard 3331:
1.145 brouard 3332: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3333: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3334: int cptcode=0; /* Modality max of covariates j */
3335: int modmincovj=0; /* Modality min of covariates j */
3336:
3337:
1.126 brouard 3338: cptcoveff=0;
3339:
1.144 brouard 3340: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3341:
1.145 brouard 3342: /* Loop on covariates without age and products */
1.186 brouard 3343: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3344: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3345: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3346: modality of this covariate Vj*/
1.145 brouard 3347: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3348: * If product of Vn*Vm, still boolean *:
3349: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3350: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3351: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3352: modality of the nth covariate of individual i. */
1.145 brouard 3353: if (ij > modmaxcovj)
3354: modmaxcovj=ij;
3355: else if (ij < modmincovj)
3356: modmincovj=ij;
3357: if ((ij < -1) && (ij > NCOVMAX)){
3358: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3359: exit(1);
3360: }else
1.136 brouard 3361: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3362: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3363: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3364: /* getting the maximum value of the modality of the covariate
3365: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3366: female is 1, then modmaxcovj=1.*/
1.192 brouard 3367: } /* end for loop on individuals i */
1.145 brouard 3368: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3369: 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 3370: cptcode=modmaxcovj;
1.137 brouard 3371: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3372: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3373: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3374: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3375: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3376: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3377: if( k != -1){
3378: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3379: covariate for which somebody answered excluding
3380: undefined. Usually 2: 0 and 1. */
3381: }
3382: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3383: covariate for which somebody answered including
3384: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3385: }
3386: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3387: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3388: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3389:
1.136 brouard 3390: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3391: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3392: 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 3393: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3394: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3395: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3396: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3397: nbcode[Tvar[j]][ij]=k;
3398: nbcode[Tvar[j]][1]=0;
3399: nbcode[Tvar[j]][2]=1;
3400: nbcode[Tvar[j]][3]=2;
1.197 brouard 3401: To be continued (not working yet).
1.145 brouard 3402: */
1.197 brouard 3403: ij=0; /* ij is similar to i but can jump over null modalities */
3404: 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*/
3405: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192 brouard 3406: break;
3407: }
3408: ij++;
1.197 brouard 3409: 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 3410: cptcode = ij; /* New max modality for covar j */
3411: } /* end of loop on modality i=-1 to 1 or more */
3412:
3413: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3414: /* /\*recode from 0 *\/ */
3415: /* k is a modality. If we have model=V1+V1*sex */
3416: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3417: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3418: /* } */
3419: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3420: /* if (ij > ncodemax[j]) { */
3421: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3422: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3423: /* break; */
3424: /* } */
3425: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3426: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3427:
1.145 brouard 3428: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3429:
1.187 brouard 3430: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3431: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3432: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3433: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3434: }
1.126 brouard 3435:
1.192 brouard 3436: ij=0;
1.145 brouard 3437: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3438: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3439: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3440: ij++;
1.145 brouard 3441: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3442: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3443: }else{
3444: /* Tvaraff[ij]=0; */
3445: }
1.126 brouard 3446: }
1.192 brouard 3447: /* ij--; */
1.144 brouard 3448: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3449:
1.126 brouard 3450: }
3451:
1.145 brouard 3452:
1.126 brouard 3453: /*********** Health Expectancies ****************/
3454:
1.127 brouard 3455: 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 3456:
3457: {
3458: /* Health expectancies, no variances */
1.164 brouard 3459: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3460: int nhstepma, nstepma; /* Decreasing with age */
3461: double age, agelim, hf;
3462: double ***p3mat;
3463: double eip;
3464:
3465: pstamp(ficreseij);
3466: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3467: fprintf(ficreseij,"# Age");
3468: for(i=1; i<=nlstate;i++){
3469: for(j=1; j<=nlstate;j++){
3470: fprintf(ficreseij," e%1d%1d ",i,j);
3471: }
3472: fprintf(ficreseij," e%1d. ",i);
3473: }
3474: fprintf(ficreseij,"\n");
3475:
3476:
3477: if(estepm < stepm){
3478: printf ("Problem %d lower than %d\n",estepm, stepm);
3479: }
3480: else hstepm=estepm;
3481: /* We compute the life expectancy from trapezoids spaced every estepm months
3482: * This is mainly to measure the difference between two models: for example
3483: * if stepm=24 months pijx are given only every 2 years and by summing them
3484: * we are calculating an estimate of the Life Expectancy assuming a linear
3485: * progression in between and thus overestimating or underestimating according
3486: * to the curvature of the survival function. If, for the same date, we
3487: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3488: * to compare the new estimate of Life expectancy with the same linear
3489: * hypothesis. A more precise result, taking into account a more precise
3490: * curvature will be obtained if estepm is as small as stepm. */
3491:
3492: /* For example we decided to compute the life expectancy with the smallest unit */
3493: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3494: nhstepm is the number of hstepm from age to agelim
3495: nstepm is the number of stepm from age to agelin.
3496: Look at hpijx to understand the reason of that which relies in memory size
3497: and note for a fixed period like estepm months */
3498: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3499: survival function given by stepm (the optimization length). Unfortunately it
3500: means that if the survival funtion is printed only each two years of age and if
3501: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3502: results. So we changed our mind and took the option of the best precision.
3503: */
3504: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3505:
3506: agelim=AGESUP;
3507: /* If stepm=6 months */
3508: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3509: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3510:
3511: /* nhstepm age range expressed in number of stepm */
3512: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3513: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3514: /* if (stepm >= YEARM) hstepm=1;*/
3515: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3516: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3517:
3518: for (age=bage; age<=fage; age ++){
3519: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3520: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3521: /* if (stepm >= YEARM) hstepm=1;*/
3522: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3523:
3524: /* If stepm=6 months */
3525: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3526: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3527:
3528: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3529:
3530: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3531:
3532: printf("%d|",(int)age);fflush(stdout);
3533: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3534:
3535: /* Computing expectancies */
3536: for(i=1; i<=nlstate;i++)
3537: for(j=1; j<=nlstate;j++)
3538: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3539: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3540:
3541: /* 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]);*/
3542:
3543: }
3544:
3545: fprintf(ficreseij,"%3.0f",age );
3546: for(i=1; i<=nlstate;i++){
3547: eip=0;
3548: for(j=1; j<=nlstate;j++){
3549: eip +=eij[i][j][(int)age];
3550: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3551: }
3552: fprintf(ficreseij,"%9.4f", eip );
3553: }
3554: fprintf(ficreseij,"\n");
3555:
3556: }
3557: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3558: printf("\n");
3559: fprintf(ficlog,"\n");
3560:
3561: }
3562:
1.127 brouard 3563: 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 3564:
3565: {
3566: /* Covariances of health expectancies eij and of total life expectancies according
3567: to initial status i, ei. .
3568: */
3569: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3570: int nhstepma, nstepma; /* Decreasing with age */
3571: double age, agelim, hf;
3572: double ***p3matp, ***p3matm, ***varhe;
3573: double **dnewm,**doldm;
3574: double *xp, *xm;
3575: double **gp, **gm;
3576: double ***gradg, ***trgradg;
3577: int theta;
3578:
3579: double eip, vip;
3580:
3581: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3582: xp=vector(1,npar);
3583: xm=vector(1,npar);
3584: dnewm=matrix(1,nlstate*nlstate,1,npar);
3585: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3586:
3587: pstamp(ficresstdeij);
3588: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3589: fprintf(ficresstdeij,"# Age");
3590: for(i=1; i<=nlstate;i++){
3591: for(j=1; j<=nlstate;j++)
3592: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3593: fprintf(ficresstdeij," e%1d. ",i);
3594: }
3595: fprintf(ficresstdeij,"\n");
3596:
3597: pstamp(ficrescveij);
3598: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3599: fprintf(ficrescveij,"# Age");
3600: for(i=1; i<=nlstate;i++)
3601: for(j=1; j<=nlstate;j++){
3602: cptj= (j-1)*nlstate+i;
3603: for(i2=1; i2<=nlstate;i2++)
3604: for(j2=1; j2<=nlstate;j2++){
3605: cptj2= (j2-1)*nlstate+i2;
3606: if(cptj2 <= cptj)
3607: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3608: }
3609: }
3610: fprintf(ficrescveij,"\n");
3611:
3612: if(estepm < stepm){
3613: printf ("Problem %d lower than %d\n",estepm, stepm);
3614: }
3615: else hstepm=estepm;
3616: /* We compute the life expectancy from trapezoids spaced every estepm months
3617: * This is mainly to measure the difference between two models: for example
3618: * if stepm=24 months pijx are given only every 2 years and by summing them
3619: * we are calculating an estimate of the Life Expectancy assuming a linear
3620: * progression in between and thus overestimating or underestimating according
3621: * to the curvature of the survival function. If, for the same date, we
3622: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3623: * to compare the new estimate of Life expectancy with the same linear
3624: * hypothesis. A more precise result, taking into account a more precise
3625: * curvature will be obtained if estepm is as small as stepm. */
3626:
3627: /* For example we decided to compute the life expectancy with the smallest unit */
3628: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3629: nhstepm is the number of hstepm from age to agelim
3630: nstepm is the number of stepm from age to agelin.
3631: Look at hpijx to understand the reason of that which relies in memory size
3632: and note for a fixed period like estepm months */
3633: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3634: survival function given by stepm (the optimization length). Unfortunately it
3635: means that if the survival funtion is printed only each two years of age and if
3636: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3637: results. So we changed our mind and took the option of the best precision.
3638: */
3639: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3640:
3641: /* If stepm=6 months */
3642: /* nhstepm age range expressed in number of stepm */
3643: agelim=AGESUP;
3644: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3645: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3646: /* if (stepm >= YEARM) hstepm=1;*/
3647: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3648:
3649: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3650: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3651: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3652: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3653: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3654: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3655:
3656: for (age=bage; age<=fage; age ++){
3657: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3658: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3659: /* if (stepm >= YEARM) hstepm=1;*/
3660: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3661:
3662: /* If stepm=6 months */
3663: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3664: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3665:
3666: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3667:
3668: /* Computing Variances of health expectancies */
3669: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3670: decrease memory allocation */
3671: for(theta=1; theta <=npar; theta++){
3672: for(i=1; i<=npar; i++){
3673: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3674: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3675: }
3676: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3677: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3678:
3679: for(j=1; j<= nlstate; j++){
3680: for(i=1; i<=nlstate; i++){
3681: for(h=0; h<=nhstepm-1; h++){
3682: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3683: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3684: }
3685: }
3686: }
3687:
3688: for(ij=1; ij<= nlstate*nlstate; ij++)
3689: for(h=0; h<=nhstepm-1; h++){
3690: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3691: }
3692: }/* End theta */
3693:
3694:
3695: for(h=0; h<=nhstepm-1; h++)
3696: for(j=1; j<=nlstate*nlstate;j++)
3697: for(theta=1; theta <=npar; theta++)
3698: trgradg[h][j][theta]=gradg[h][theta][j];
3699:
3700:
3701: for(ij=1;ij<=nlstate*nlstate;ij++)
3702: for(ji=1;ji<=nlstate*nlstate;ji++)
3703: varhe[ij][ji][(int)age] =0.;
3704:
3705: printf("%d|",(int)age);fflush(stdout);
3706: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3707: for(h=0;h<=nhstepm-1;h++){
3708: for(k=0;k<=nhstepm-1;k++){
3709: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3710: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3711: for(ij=1;ij<=nlstate*nlstate;ij++)
3712: for(ji=1;ji<=nlstate*nlstate;ji++)
3713: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3714: }
3715: }
3716:
3717: /* Computing expectancies */
3718: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3719: for(i=1; i<=nlstate;i++)
3720: for(j=1; j<=nlstate;j++)
3721: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3722: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3723:
3724: /* 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]);*/
3725:
3726: }
3727:
3728: fprintf(ficresstdeij,"%3.0f",age );
3729: for(i=1; i<=nlstate;i++){
3730: eip=0.;
3731: vip=0.;
3732: for(j=1; j<=nlstate;j++){
3733: eip += eij[i][j][(int)age];
3734: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3735: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3736: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3737: }
3738: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3739: }
3740: fprintf(ficresstdeij,"\n");
3741:
3742: fprintf(ficrescveij,"%3.0f",age );
3743: for(i=1; i<=nlstate;i++)
3744: for(j=1; j<=nlstate;j++){
3745: cptj= (j-1)*nlstate+i;
3746: for(i2=1; i2<=nlstate;i2++)
3747: for(j2=1; j2<=nlstate;j2++){
3748: cptj2= (j2-1)*nlstate+i2;
3749: if(cptj2 <= cptj)
3750: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3751: }
3752: }
3753: fprintf(ficrescveij,"\n");
3754:
3755: }
3756: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3757: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3758: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3759: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3760: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3761: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3762: printf("\n");
3763: fprintf(ficlog,"\n");
3764:
3765: free_vector(xm,1,npar);
3766: free_vector(xp,1,npar);
3767: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3768: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3769: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3770: }
3771:
3772: /************ Variance ******************/
3773: 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 ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
3774: {
3775: /* Variance of health expectancies */
3776: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3777: /* double **newm;*/
1.169 brouard 3778: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3779:
3780: int movingaverage();
1.126 brouard 3781: double **dnewm,**doldm;
3782: double **dnewmp,**doldmp;
3783: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3784: int k;
1.126 brouard 3785: double *xp;
3786: double **gp, **gm; /* for var eij */
3787: double ***gradg, ***trgradg; /*for var eij */
3788: double **gradgp, **trgradgp; /* for var p point j */
3789: double *gpp, *gmp; /* for var p point j */
3790: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3791: double ***p3mat;
3792: double age,agelim, hf;
3793: double ***mobaverage;
3794: int theta;
3795: char digit[4];
3796: char digitp[25];
3797:
3798: char fileresprobmorprev[FILENAMELENGTH];
3799:
3800: if(popbased==1){
3801: if(mobilav!=0)
3802: strcpy(digitp,"-populbased-mobilav-");
3803: else strcpy(digitp,"-populbased-nomobil-");
3804: }
3805: else
3806: strcpy(digitp,"-stablbased-");
3807:
3808: if (mobilav!=0) {
3809: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3810: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3811: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3812: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3813: }
3814: }
3815:
3816: strcpy(fileresprobmorprev,"prmorprev");
3817: sprintf(digit,"%-d",ij);
3818: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3819: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3820: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3821: strcat(fileresprobmorprev,fileres);
3822: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3823: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3824: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3825: }
3826: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3827:
3828: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3829: pstamp(ficresprobmorprev);
3830: 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);
3831: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3832: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3833: fprintf(ficresprobmorprev," p.%-d SE",j);
3834: for(i=1; i<=nlstate;i++)
3835: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3836: }
3837: fprintf(ficresprobmorprev,"\n");
3838: fprintf(ficgp,"\n# Routine varevsij");
3839: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3840: 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");
3841: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3842: /* } */
3843: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3844: pstamp(ficresvij);
3845: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3846: if(popbased==1)
1.128 brouard 3847: 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 3848: else
3849: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3850: fprintf(ficresvij,"# Age");
3851: for(i=1; i<=nlstate;i++)
3852: for(j=1; j<=nlstate;j++)
3853: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3854: fprintf(ficresvij,"\n");
3855:
3856: xp=vector(1,npar);
3857: dnewm=matrix(1,nlstate,1,npar);
3858: doldm=matrix(1,nlstate,1,nlstate);
3859: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3860: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3861:
3862: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3863: gpp=vector(nlstate+1,nlstate+ndeath);
3864: gmp=vector(nlstate+1,nlstate+ndeath);
3865: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3866:
3867: if(estepm < stepm){
3868: printf ("Problem %d lower than %d\n",estepm, stepm);
3869: }
3870: else hstepm=estepm;
3871: /* For example we decided to compute the life expectancy with the smallest unit */
3872: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3873: nhstepm is the number of hstepm from age to agelim
3874: nstepm is the number of stepm from age to agelin.
1.128 brouard 3875: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3876: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3877: survival function given by stepm (the optimization length). Unfortunately it
3878: means that if the survival funtion is printed every two years of age and if
3879: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3880: results. So we changed our mind and took the option of the best precision.
3881: */
3882: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3883: agelim = AGESUP;
3884: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3885: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3886: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3887: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3888: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3889: gp=matrix(0,nhstepm,1,nlstate);
3890: gm=matrix(0,nhstepm,1,nlstate);
3891:
3892:
3893: for(theta=1; theta <=npar; theta++){
3894: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3895: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3896: }
3897: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3898: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3899:
3900: if (popbased==1) {
3901: if(mobilav ==0){
3902: for(i=1; i<=nlstate;i++)
3903: prlim[i][i]=probs[(int)age][i][ij];
3904: }else{ /* mobilav */
3905: for(i=1; i<=nlstate;i++)
3906: prlim[i][i]=mobaverage[(int)age][i][ij];
3907: }
3908: }
3909:
3910: for(j=1; j<= nlstate; j++){
3911: for(h=0; h<=nhstepm; h++){
3912: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3913: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3914: }
3915: }
3916: /* This for computing probability of death (h=1 means
3917: computed over hstepm matrices product = hstepm*stepm months)
3918: as a weighted average of prlim.
3919: */
3920: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3921: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3922: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3923: }
3924: /* end probability of death */
3925:
3926: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3927: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3928: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3929: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3930:
3931: if (popbased==1) {
3932: if(mobilav ==0){
3933: for(i=1; i<=nlstate;i++)
3934: prlim[i][i]=probs[(int)age][i][ij];
3935: }else{ /* mobilav */
3936: for(i=1; i<=nlstate;i++)
3937: prlim[i][i]=mobaverage[(int)age][i][ij];
3938: }
3939: }
3940:
1.128 brouard 3941: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3942: for(h=0; h<=nhstepm; h++){
3943: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3944: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3945: }
3946: }
3947: /* This for computing probability of death (h=1 means
3948: computed over hstepm matrices product = hstepm*stepm months)
3949: as a weighted average of prlim.
3950: */
3951: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3952: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3953: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3954: }
3955: /* end probability of death */
3956:
3957: for(j=1; j<= nlstate; j++) /* vareij */
3958: for(h=0; h<=nhstepm; h++){
3959: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3960: }
3961:
3962: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3963: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3964: }
3965:
3966: } /* End theta */
3967:
3968: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3969:
3970: for(h=0; h<=nhstepm; h++) /* veij */
3971: for(j=1; j<=nlstate;j++)
3972: for(theta=1; theta <=npar; theta++)
3973: trgradg[h][j][theta]=gradg[h][theta][j];
3974:
3975: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3976: for(theta=1; theta <=npar; theta++)
3977: trgradgp[j][theta]=gradgp[theta][j];
3978:
3979:
3980: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3981: for(i=1;i<=nlstate;i++)
3982: for(j=1;j<=nlstate;j++)
3983: vareij[i][j][(int)age] =0.;
3984:
3985: for(h=0;h<=nhstepm;h++){
3986: for(k=0;k<=nhstepm;k++){
3987: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3988: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3989: for(i=1;i<=nlstate;i++)
3990: for(j=1;j<=nlstate;j++)
3991: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3992: }
3993: }
3994:
3995: /* pptj */
3996: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3997: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3998: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3999: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4000: varppt[j][i]=doldmp[j][i];
4001: /* end ppptj */
4002: /* x centered again */
4003: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4004: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
4005:
4006: if (popbased==1) {
4007: if(mobilav ==0){
4008: for(i=1; i<=nlstate;i++)
4009: prlim[i][i]=probs[(int)age][i][ij];
4010: }else{ /* mobilav */
4011: for(i=1; i<=nlstate;i++)
4012: prlim[i][i]=mobaverage[(int)age][i][ij];
4013: }
4014: }
4015:
4016: /* This for computing probability of death (h=1 means
4017: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4018: as a weighted average of prlim.
4019: */
4020: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4021: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4022: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4023: }
4024: /* end probability of death */
4025:
4026: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4027: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4028: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4029: for(i=1; i<=nlstate;i++){
4030: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4031: }
4032: }
4033: fprintf(ficresprobmorprev,"\n");
4034:
4035: fprintf(ficresvij,"%.0f ",age );
4036: for(i=1; i<=nlstate;i++)
4037: for(j=1; j<=nlstate;j++){
4038: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4039: }
4040: fprintf(ficresvij,"\n");
4041: free_matrix(gp,0,nhstepm,1,nlstate);
4042: free_matrix(gm,0,nhstepm,1,nlstate);
4043: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4044: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4045: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4046: } /* End age */
4047: free_vector(gpp,nlstate+1,nlstate+ndeath);
4048: free_vector(gmp,nlstate+1,nlstate+ndeath);
4049: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4050: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 4051: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 4052: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4053: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 4054: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4055: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4056: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4057: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4058: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4059: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4060: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4061: fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4062: /* 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.png\"> <br>\n", stepm,YEARM,digitp,digit);
4063: */
4064: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
4065: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4066:
4067: free_vector(xp,1,npar);
4068: free_matrix(doldm,1,nlstate,1,nlstate);
4069: free_matrix(dnewm,1,nlstate,1,npar);
4070: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4071: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4072: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4073: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4074: fclose(ficresprobmorprev);
4075: fflush(ficgp);
4076: fflush(fichtm);
4077: } /* end varevsij */
4078:
4079: /************ Variance of prevlim ******************/
4080: 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 ij, char strstart[])
4081: {
4082: /* Variance of prevalence limit */
4083: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4084:
1.126 brouard 4085: double **dnewm,**doldm;
4086: int i, j, nhstepm, hstepm;
4087: double *xp;
4088: double *gp, *gm;
4089: double **gradg, **trgradg;
4090: double age,agelim;
4091: int theta;
4092:
4093: pstamp(ficresvpl);
4094: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4095: fprintf(ficresvpl,"# Age");
4096: for(i=1; i<=nlstate;i++)
4097: fprintf(ficresvpl," %1d-%1d",i,i);
4098: fprintf(ficresvpl,"\n");
4099:
4100: xp=vector(1,npar);
4101: dnewm=matrix(1,nlstate,1,npar);
4102: doldm=matrix(1,nlstate,1,nlstate);
4103:
4104: hstepm=1*YEARM; /* Every year of age */
4105: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4106: agelim = AGESUP;
4107: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4108: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4109: if (stepm >= YEARM) hstepm=1;
4110: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4111: gradg=matrix(1,npar,1,nlstate);
4112: gp=vector(1,nlstate);
4113: gm=vector(1,nlstate);
4114:
4115: for(theta=1; theta <=npar; theta++){
4116: for(i=1; i<=npar; i++){ /* Computes gradient */
4117: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4118: }
4119: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4120: for(i=1;i<=nlstate;i++)
4121: gp[i] = prlim[i][i];
4122:
4123: for(i=1; i<=npar; i++) /* Computes gradient */
4124: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4125: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4126: for(i=1;i<=nlstate;i++)
4127: gm[i] = prlim[i][i];
4128:
4129: for(i=1;i<=nlstate;i++)
4130: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4131: } /* End theta */
4132:
4133: trgradg =matrix(1,nlstate,1,npar);
4134:
4135: for(j=1; j<=nlstate;j++)
4136: for(theta=1; theta <=npar; theta++)
4137: trgradg[j][theta]=gradg[theta][j];
4138:
4139: for(i=1;i<=nlstate;i++)
4140: varpl[i][(int)age] =0.;
4141: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4142: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4143: for(i=1;i<=nlstate;i++)
4144: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4145:
4146: fprintf(ficresvpl,"%.0f ",age );
4147: for(i=1; i<=nlstate;i++)
4148: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4149: fprintf(ficresvpl,"\n");
4150: free_vector(gp,1,nlstate);
4151: free_vector(gm,1,nlstate);
4152: free_matrix(gradg,1,npar,1,nlstate);
4153: free_matrix(trgradg,1,nlstate,1,npar);
4154: } /* End age */
4155:
4156: free_vector(xp,1,npar);
4157: free_matrix(doldm,1,nlstate,1,npar);
4158: free_matrix(dnewm,1,nlstate,1,nlstate);
4159:
4160: }
4161:
4162: /************ Variance of one-step probabilities ******************/
4163: 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[])
4164: {
1.164 brouard 4165: int i, j=0, k1, l1, tj;
1.126 brouard 4166: int k2, l2, j1, z1;
1.164 brouard 4167: int k=0, l;
1.145 brouard 4168: int first=1, first1, first2;
1.126 brouard 4169: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4170: double **dnewm,**doldm;
4171: double *xp;
4172: double *gp, *gm;
4173: double **gradg, **trgradg;
4174: double **mu;
1.164 brouard 4175: double age, cov[NCOVMAX+1];
1.126 brouard 4176: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4177: int theta;
4178: char fileresprob[FILENAMELENGTH];
4179: char fileresprobcov[FILENAMELENGTH];
4180: char fileresprobcor[FILENAMELENGTH];
4181: double ***varpij;
4182:
4183: strcpy(fileresprob,"prob");
4184: strcat(fileresprob,fileres);
4185: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4186: printf("Problem with resultfile: %s\n", fileresprob);
4187: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4188: }
4189: strcpy(fileresprobcov,"probcov");
4190: strcat(fileresprobcov,fileres);
4191: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4192: printf("Problem with resultfile: %s\n", fileresprobcov);
4193: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4194: }
4195: strcpy(fileresprobcor,"probcor");
4196: strcat(fileresprobcor,fileres);
4197: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4198: printf("Problem with resultfile: %s\n", fileresprobcor);
4199: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4200: }
4201: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4202: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4203: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4204: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4205: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4206: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4207: pstamp(ficresprob);
4208: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4209: fprintf(ficresprob,"# Age");
4210: pstamp(ficresprobcov);
4211: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4212: fprintf(ficresprobcov,"# Age");
4213: pstamp(ficresprobcor);
4214: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4215: fprintf(ficresprobcor,"# Age");
4216:
4217:
4218: for(i=1; i<=nlstate;i++)
4219: for(j=1; j<=(nlstate+ndeath);j++){
4220: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4221: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4222: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4223: }
4224: /* fprintf(ficresprob,"\n");
4225: fprintf(ficresprobcov,"\n");
4226: fprintf(ficresprobcor,"\n");
4227: */
1.131 brouard 4228: xp=vector(1,npar);
1.126 brouard 4229: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4230: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4231: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4232: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4233: first=1;
4234: fprintf(ficgp,"\n# Routine varprob");
4235: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4236: fprintf(fichtm,"\n");
4237:
1.197 brouard 4238: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4></br>this page is important in order to visualize confidence intervals and especially correlation between disability and recovery</li>\n",optionfilehtmcov);
4239: 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);
4240: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126 brouard 4241: and drawn. It helps understanding how is the covariance between two incidences.\
4242: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4243: 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. \
4244: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4245: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4246: standard deviations wide on each axis. <br>\
4247: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4248: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4249: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4250:
4251: cov[1]=1;
1.145 brouard 4252: /* tj=cptcoveff; */
4253: tj = (int) pow(2,cptcoveff);
1.126 brouard 4254: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4255: j1=0;
1.145 brouard 4256: for(j1=1; j1<=tj;j1++){
4257: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4258: /*j1++;*/
1.126 brouard 4259: if (cptcovn>0) {
4260: fprintf(ficresprob, "\n#********** Variable ");
1.198 ! brouard 4261: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4262: fprintf(ficresprob, "**********\n#\n");
4263: fprintf(ficresprobcov, "\n#********** Variable ");
1.198 ! brouard 4264: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4265: fprintf(ficresprobcov, "**********\n#\n");
4266:
4267: fprintf(ficgp, "\n#********** Variable ");
1.198 ! brouard 4268: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4269: fprintf(ficgp, "**********\n#\n");
4270:
4271:
4272: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
1.198 ! brouard 4273: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4274: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4275:
4276: fprintf(ficresprobcor, "\n#********** Variable ");
1.198 ! brouard 4277: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4278: fprintf(ficresprobcor, "**********\n#");
4279: }
4280:
1.145 brouard 4281: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4282: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4283: gp=vector(1,(nlstate)*(nlstate+ndeath));
4284: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4285: for (age=bage; age<=fage; age ++){
4286: cov[2]=age;
1.187 brouard 4287: if(nagesqr==1)
4288: cov[3]= age*age;
1.126 brouard 4289: for (k=1; k<=cptcovn;k++) {
1.198 ! brouard 4290: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];/* j1 1 2 3 4
1.145 brouard 4291: * 1 1 1 1 1
4292: * 2 2 1 1 1
4293: * 3 1 2 1 1
4294: */
4295: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4296: }
1.186 brouard 4297: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198 ! brouard 4298: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.126 brouard 4299: for (k=1; k<=cptcovprod;k++)
1.198 ! brouard 4300: 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 4301:
4302:
4303: for(theta=1; theta <=npar; theta++){
4304: for(i=1; i<=npar; i++)
4305: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4306:
4307: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4308:
4309: k=0;
4310: for(i=1; i<= (nlstate); i++){
4311: for(j=1; j<=(nlstate+ndeath);j++){
4312: k=k+1;
4313: gp[k]=pmmij[i][j];
4314: }
4315: }
4316:
4317: for(i=1; i<=npar; i++)
4318: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4319:
4320: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4321: k=0;
4322: for(i=1; i<=(nlstate); i++){
4323: for(j=1; j<=(nlstate+ndeath);j++){
4324: k=k+1;
4325: gm[k]=pmmij[i][j];
4326: }
4327: }
4328:
4329: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4330: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4331: }
4332:
4333: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4334: for(theta=1; theta <=npar; theta++)
4335: trgradg[j][theta]=gradg[theta][j];
4336:
4337: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4338: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4339:
4340: pmij(pmmij,cov,ncovmodel,x,nlstate);
4341:
4342: k=0;
4343: for(i=1; i<=(nlstate); i++){
4344: for(j=1; j<=(nlstate+ndeath);j++){
4345: k=k+1;
4346: mu[k][(int) age]=pmmij[i][j];
4347: }
4348: }
4349: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4350: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4351: varpij[i][j][(int)age] = doldm[i][j];
4352:
4353: /*printf("\n%d ",(int)age);
4354: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4355: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4356: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4357: }*/
4358:
4359: fprintf(ficresprob,"\n%d ",(int)age);
4360: fprintf(ficresprobcov,"\n%d ",(int)age);
4361: fprintf(ficresprobcor,"\n%d ",(int)age);
4362:
4363: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4364: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4365: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4366: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4367: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4368: }
4369: i=0;
4370: for (k=1; k<=(nlstate);k++){
4371: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4372: i++;
1.126 brouard 4373: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4374: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4375: for (j=1; j<=i;j++){
1.145 brouard 4376: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4377: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4378: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4379: }
4380: }
4381: }/* end of loop for state */
4382: } /* end of loop for age */
1.145 brouard 4383: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4384: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4385: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4386: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4387:
1.126 brouard 4388: /* Confidence intervalle of pij */
4389: /*
1.131 brouard 4390: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4391: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4392: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4393: 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);
4394: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4395: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4396: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4397: */
4398:
4399: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4400: first1=1;first2=2;
1.126 brouard 4401: for (k2=1; k2<=(nlstate);k2++){
4402: for (l2=1; l2<=(nlstate+ndeath);l2++){
4403: if(l2==k2) continue;
4404: j=(k2-1)*(nlstate+ndeath)+l2;
4405: for (k1=1; k1<=(nlstate);k1++){
4406: for (l1=1; l1<=(nlstate+ndeath);l1++){
4407: if(l1==k1) continue;
4408: i=(k1-1)*(nlstate+ndeath)+l1;
4409: if(i<=j) continue;
4410: for (age=bage; age<=fage; age ++){
4411: if ((int)age %5==0){
4412: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4413: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4414: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4415: mu1=mu[i][(int) age]/stepm*YEARM ;
4416: mu2=mu[j][(int) age]/stepm*YEARM;
4417: c12=cv12/sqrt(v1*v2);
4418: /* Computing eigen value of matrix of covariance */
4419: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4420: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4421: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4422: if(first2==1){
4423: first1=0;
4424: 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);
4425: }
4426: 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);
4427: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4428: /* lc2=fabs(lc2); */
1.135 brouard 4429: }
4430:
1.126 brouard 4431: /* Eigen vectors */
4432: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4433: /*v21=sqrt(1.-v11*v11); *//* error */
4434: v21=(lc1-v1)/cv12*v11;
4435: v12=-v21;
4436: v22=v11;
4437: tnalp=v21/v11;
4438: if(first1==1){
4439: first1=0;
4440: 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);
4441: }
4442: 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);
4443: /*printf(fignu*/
4444: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4445: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4446: if(first==1){
4447: first=0;
4448: fprintf(ficgp,"\nset parametric;unset label");
4449: 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.145 brouard 4450: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4451: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4452: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4453: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4454: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4455: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4456: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4457: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4458: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4459: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4460: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4461: 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",\
4462: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4463: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4464: }else{
4465: first=0;
4466: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4467: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4468: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4469: 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",\
4470: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4471: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4472: }/* if first */
4473: } /* age mod 5 */
4474: } /* end loop age */
4475: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4476: first=1;
4477: } /*l12 */
4478: } /* k12 */
4479: } /*l1 */
4480: }/* k1 */
1.169 brouard 4481: /* } */ /* loop covariates */
1.126 brouard 4482: }
4483: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4484: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4485: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4486: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4487: free_vector(xp,1,npar);
4488: fclose(ficresprob);
4489: fclose(ficresprobcov);
4490: fclose(ficresprobcor);
4491: fflush(ficgp);
4492: fflush(fichtmcov);
4493: }
4494:
4495:
4496: /******************* Printing html file ***********/
4497: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4498: int lastpass, int stepm, int weightopt, char model[],\
4499: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4500: int popforecast, int estepm ,\
4501: double jprev1, double mprev1,double anprev1, \
4502: double jprev2, double mprev2,double anprev2){
4503: int jj1, k1, i1, cpt;
4504:
4505: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4506: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4507: </ul>");
4508: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4509: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4510: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4511: fprintf(fichtm,"\
4512: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4513: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4514: fprintf(fichtm,"\
4515: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4516: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4517: fprintf(fichtm,"\
1.128 brouard 4518: - (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 4519: <a href=\"%s\">%s</a> <br>\n",
4520: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4521: fprintf(fichtm,"\
4522: - Population projections by age and states: \
4523: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4524:
4525: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4526:
1.145 brouard 4527: m=pow(2,cptcoveff);
1.126 brouard 4528: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4529:
4530: jj1=0;
4531: for(k1=1; k1<=m;k1++){
1.192 brouard 4532: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4533: jj1++;
4534: if (cptcovn > 0) {
4535: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4536: for (cpt=1; cpt<=cptcoveff;cpt++){
1.198 ! brouard 4537: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
! 4538: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192 brouard 4539: }
1.126 brouard 4540: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4541: }
4542: /* Pij */
1.145 brouard 4543: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
4544: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4545: /* Quasi-incidences */
4546: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4547: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
4548: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4549: /* Period (stable) prevalence in each health state */
1.154 brouard 4550: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4551: fprintf(fichtm,"<br>- 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.png\">%s%d_%d.png</a><br> \
4552: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126 brouard 4553: }
4554: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4555: 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) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
4556: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
1.126 brouard 4557: }
1.192 brouard 4558: /* } /\* end i1 *\/ */
1.126 brouard 4559: }/* End k1 */
4560: fprintf(fichtm,"</ul>");
4561:
4562: fprintf(fichtm,"\
4563: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4564: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197 brouard 4565: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
4566: But because parameters are usually highly correlated (a higher incidence of disability \
4567: and a higher incidence of recovery can give very close observed transition) it might \
4568: be very useful to look not only at linear confidence intervals estimated from the \
4569: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4570: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4571: covariance matrix of the one-step probabilities. \
4572: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126 brouard 4573:
1.193 brouard 4574: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126 brouard 4575: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4576: fprintf(fichtm,"\
4577: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4578: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4579:
4580: fprintf(fichtm,"\
4581: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4582: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4583: fprintf(fichtm,"\
4584: - 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): \
4585: <a href=\"%s\">%s</a> <br>\n</li>",
4586: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4587: fprintf(fichtm,"\
4588: - (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): \
4589: <a href=\"%s\">%s</a> <br>\n</li>",
4590: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4591: fprintf(fichtm,"\
1.128 brouard 4592: - 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.126 brouard 4593: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4594: fprintf(fichtm,"\
1.128 brouard 4595: - 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",
4596: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4597: fprintf(fichtm,"\
4598: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4599: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4600:
4601: /* if(popforecast==1) fprintf(fichtm,"\n */
4602: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4603: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4604: /* <br>",fileres,fileres,fileres,fileres); */
4605: /* else */
4606: /* 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); */
4607: fflush(fichtm);
4608: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4609:
1.145 brouard 4610: m=pow(2,cptcoveff);
1.126 brouard 4611: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4612:
4613: jj1=0;
4614: for(k1=1; k1<=m;k1++){
1.192 brouard 4615: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4616: jj1++;
4617: if (cptcovn > 0) {
4618: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4619: for (cpt=1; cpt<=cptcoveff;cpt++)
1.198 ! brouard 4620: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126 brouard 4621: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4622: }
4623: for(cpt=1; cpt<=nlstate;cpt++) {
4624: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4625: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4626: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4627: }
4628: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4629: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4630: true period expectancies (those weighted with period prevalences are also\
4631: drawn in addition to the population based expectancies computed using\
4632: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4633: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192 brouard 4634: /* } /\* end i1 *\/ */
1.126 brouard 4635: }/* End k1 */
4636: fprintf(fichtm,"</ul>");
4637: fflush(fichtm);
4638: }
4639:
4640: /******************* Gnuplot file **************/
4641: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4642:
4643: char dirfileres[132],optfileres[132];
1.164 brouard 4644: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4645: int ng=0;
1.126 brouard 4646: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4647: /* printf("Problem with file %s",optionfilegnuplot); */
4648: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4649: /* } */
4650:
4651: /*#ifdef windows */
4652: fprintf(ficgp,"cd \"%s\" \n",pathc);
4653: /*#endif */
4654: m=pow(2,cptcoveff);
4655:
4656: strcpy(dirfileres,optionfilefiname);
4657: strcpy(optfileres,"vpl");
4658: /* 1eme*/
1.153 brouard 4659: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4660: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4661: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4662: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4663: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4664: fprintf(ficgp,"set xlabel \"Age\" \n\
4665: set ylabel \"Probability\" \n\
1.145 brouard 4666: set ter png small size 320, 240\n\
1.170 brouard 4667: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4668:
4669: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4670: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4671: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4672: }
1.170 brouard 4673: fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4674: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4675: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4676: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4677: }
1.170 brouard 4678: fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4679: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4680: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4681: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4682: }
1.145 brouard 4683: fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
1.126 brouard 4684: }
4685: }
4686: /*2 eme*/
1.153 brouard 4687: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4688: for (k1=1; k1<= m ; k1 ++) {
4689: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4690: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4691:
4692: for (i=1; i<= nlstate+1 ; i ++) {
4693: k=2*i;
1.170 brouard 4694: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4695: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4696: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4697: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4698: }
4699: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4700: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4701: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4702: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4703: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4704: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4705: }
1.145 brouard 4706: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4707: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4708: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4709: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4710: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4711: }
1.145 brouard 4712: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4713: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4714: }
4715: }
4716:
4717: /*3eme*/
4718:
4719: for (k1=1; k1<= m ; k1 ++) {
4720: for (cpt=1; cpt<= nlstate ; cpt ++) {
4721: /* k=2+nlstate*(2*cpt-2); */
4722: k=2+(nlstate+1)*(cpt-1);
4723: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4724: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4725: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
4726: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4727: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4728: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4729: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4730: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4731: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4732:
4733: */
4734: for (i=1; i< nlstate ; i ++) {
4735: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
4736: /* 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);*/
4737:
4738: }
4739: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4740: }
4741: }
4742:
4743: /* CV preval stable (period) */
1.153 brouard 4744: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4745: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4746: k=3;
1.153 brouard 4747: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4748: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4749: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4750: set ter png small size 320, 240\n\
1.126 brouard 4751: unset log y\n\
1.153 brouard 4752: plot [%.f:%.f] ", ageminpar, agemaxpar);
4753: for (i=1; i<= nlstate ; i ++){
4754: if(i==1)
4755: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4756: else
4757: fprintf(ficgp,", '' ");
1.154 brouard 4758: l=(nlstate+ndeath)*(i-1)+1;
4759: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4760: for (j=1; j<= (nlstate-1) ; j ++)
4761: fprintf(ficgp,"+$%d",k+l+j);
4762: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4763: } /* nlstate */
4764: fprintf(ficgp,"\n");
4765: } /* end cpt state*/
4766: } /* end covariate */
1.126 brouard 4767:
4768: /* proba elementaires */
1.187 brouard 4769: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 4770: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 4771: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 4772: for(k=1; k <=(nlstate+ndeath); k++){
4773: if (k != i) {
1.187 brouard 4774: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 4775: for(j=1; j <=ncovmodel; j++){
1.187 brouard 4776: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 4777: jk++;
4778: }
1.187 brouard 4779: fprintf(ficgp,"\n");
1.126 brouard 4780: }
4781: }
4782: }
1.187 brouard 4783: fprintf(ficgp,"##############\n#\n");
4784:
1.145 brouard 4785: /*goto avoid;*/
1.187 brouard 4786: fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
4787: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4788: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4789: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4790: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4791: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4792: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4793: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4794: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4795: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4796: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4797: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4798: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4799: fprintf(ficgp,"#\n");
1.126 brouard 4800: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187 brouard 4801: fprintf(ficgp,"# ng=%d\n",ng);
4802: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 4803: for(jk=1; jk <=m; jk++) {
1.187 brouard 4804: fprintf(ficgp,"# jk=%d\n",jk);
1.145 brouard 4805: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4806: if (ng==2)
4807: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4808: else
4809: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4810: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4811: i=1;
4812: for(k2=1; k2<=nlstate; k2++) {
4813: k3=i;
4814: for(k=1; k<=(nlstate+ndeath); k++) {
4815: if (k != k2){
4816: if(ng==2)
1.187 brouard 4817: if(nagesqr==0)
4818: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4819: else /* nagesqr =1 */
4820: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126 brouard 4821: else
1.187 brouard 4822: if(nagesqr==0)
4823: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4824: else /* nagesqr =1 */
4825: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141 brouard 4826: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 4827: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197 brouard 4828: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
4829: if(ij <=cptcovage) { /* Bug valgrind */
4830: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.198 ! brouard 4831: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]);
1.197 brouard 4832: ij++;
4833: }
1.186 brouard 4834: }
4835: else
1.198 ! brouard 4836: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 4837: }
4838: fprintf(ficgp,")/(1");
4839:
1.187 brouard 4840: for(k1=1; k1 <=nlstate; k1++){
4841: if(nagesqr==0)
4842: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4843: else /* nagesqr =1 */
4844: 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);
4845:
1.126 brouard 4846: ij=1;
1.187 brouard 4847: for(j=3; j <=ncovmodel-nagesqr; j++){
1.197 brouard 4848: if(ij <=cptcovage) { /* Bug valgrind */
4849: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.198 ! brouard 4850: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]);
1.197 brouard 4851: ij++;
4852: }
1.186 brouard 4853: }
4854: else
1.198 ! brouard 4855: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 4856: }
4857: fprintf(ficgp,")");
4858: }
4859: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4860: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4861: i=i+ncovmodel;
4862: }
4863: } /* end k */
4864: } /* end k2 */
4865: } /* end jk */
4866: } /* end ng */
1.164 brouard 4867: /* avoid: */
1.126 brouard 4868: fflush(ficgp);
4869: } /* end gnuplot */
4870:
4871:
4872: /*************** Moving average **************/
4873: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4874:
4875: int i, cpt, cptcod;
4876: int modcovmax =1;
4877: int mobilavrange, mob;
4878: double age;
4879:
4880: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4881: a covariate has 2 modalities */
4882: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4883:
4884: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4885: if(mobilav==1) mobilavrange=5; /* default */
4886: else mobilavrange=mobilav;
4887: for (age=bage; age<=fage; age++)
4888: for (i=1; i<=nlstate;i++)
4889: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4890: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4891: /* We keep the original values on the extreme ages bage, fage and for
4892: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4893: we use a 5 terms etc. until the borders are no more concerned.
4894: */
4895: for (mob=3;mob <=mobilavrange;mob=mob+2){
4896: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4897: for (i=1; i<=nlstate;i++){
4898: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4899: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4900: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4901: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4902: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4903: }
4904: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4905: }
4906: }
4907: }/* end age */
4908: }/* end mob */
4909: }else return -1;
4910: return 0;
4911: }/* End movingaverage */
4912:
4913:
4914: /************** Forecasting ******************/
1.169 brouard 4915: 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 4916: /* proj1, year, month, day of starting projection
4917: agemin, agemax range of age
4918: dateprev1 dateprev2 range of dates during which prevalence is computed
4919: anproj2 year of en of projection (same day and month as proj1).
4920: */
1.164 brouard 4921: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4922: double agec; /* generic age */
4923: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4924: double *popeffectif,*popcount;
4925: double ***p3mat;
4926: double ***mobaverage;
4927: char fileresf[FILENAMELENGTH];
4928:
4929: agelim=AGESUP;
4930: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4931:
4932: strcpy(fileresf,"f");
4933: strcat(fileresf,fileres);
4934: if((ficresf=fopen(fileresf,"w"))==NULL) {
4935: printf("Problem with forecast resultfile: %s\n", fileresf);
4936: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4937: }
4938: printf("Computing forecasting: result on file '%s' \n", fileresf);
4939: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4940:
4941: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4942:
4943: if (mobilav!=0) {
4944: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4945: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4946: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4947: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4948: }
4949: }
4950:
4951: stepsize=(int) (stepm+YEARM-1)/YEARM;
4952: if (stepm<=12) stepsize=1;
4953: if(estepm < stepm){
4954: printf ("Problem %d lower than %d\n",estepm, stepm);
4955: }
4956: else hstepm=estepm;
4957:
4958: hstepm=hstepm/stepm;
4959: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4960: fractional in yp1 */
4961: anprojmean=yp;
4962: yp2=modf((yp1*12),&yp);
4963: mprojmean=yp;
4964: yp1=modf((yp2*30.5),&yp);
4965: jprojmean=yp;
4966: if(jprojmean==0) jprojmean=1;
4967: if(mprojmean==0) jprojmean=1;
4968:
4969: i1=cptcoveff;
4970: if (cptcovn < 1){i1=1;}
4971:
4972: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4973:
4974: fprintf(ficresf,"#****** Routine prevforecast **\n");
4975:
4976: /* if (h==(int)(YEARM*yearp)){ */
4977: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4978: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4979: k=k+1;
4980: fprintf(ficresf,"\n#******");
4981: for(j=1;j<=cptcoveff;j++) {
1.198 ! brouard 4982: 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 4983: }
4984: fprintf(ficresf,"******\n");
4985: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4986: for(j=1; j<=nlstate+ndeath;j++){
4987: for(i=1; i<=nlstate;i++)
4988: fprintf(ficresf," p%d%d",i,j);
4989: fprintf(ficresf," p.%d",j);
4990: }
4991: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4992: fprintf(ficresf,"\n");
4993: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4994:
4995: for (agec=fage; agec>=(ageminpar-1); agec--){
4996: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4997: nhstepm = nhstepm/hstepm;
4998: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4999: oldm=oldms;savm=savms;
5000: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5001:
5002: for (h=0; h<=nhstepm; h++){
5003: if (h*hstepm/YEARM*stepm ==yearp) {
5004: fprintf(ficresf,"\n");
5005: for(j=1;j<=cptcoveff;j++)
1.198 ! brouard 5006: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5007: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5008: }
5009: for(j=1; j<=nlstate+ndeath;j++) {
5010: ppij=0.;
5011: for(i=1; i<=nlstate;i++) {
5012: if (mobilav==1)
5013: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5014: else {
5015: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5016: }
5017: if (h*hstepm/YEARM*stepm== yearp) {
5018: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5019: }
5020: } /* end i */
5021: if (h*hstepm/YEARM*stepm==yearp) {
5022: fprintf(ficresf," %.3f", ppij);
5023: }
5024: }/* end j */
5025: } /* end h */
5026: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5027: } /* end agec */
5028: } /* end yearp */
5029: } /* end cptcod */
5030: } /* end cptcov */
5031:
5032: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5033:
5034: fclose(ficresf);
5035: }
5036:
5037: /************** Forecasting *****not tested NB*************/
1.169 brouard 5038: 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 5039:
5040: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5041: int *popage;
5042: double calagedatem, agelim, kk1, kk2;
5043: double *popeffectif,*popcount;
5044: double ***p3mat,***tabpop,***tabpopprev;
5045: double ***mobaverage;
5046: char filerespop[FILENAMELENGTH];
5047:
5048: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5049: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5050: agelim=AGESUP;
5051: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5052:
5053: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5054:
5055:
5056: strcpy(filerespop,"pop");
5057: strcat(filerespop,fileres);
5058: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5059: printf("Problem with forecast resultfile: %s\n", filerespop);
5060: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5061: }
5062: printf("Computing forecasting: result on file '%s' \n", filerespop);
5063: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5064:
5065: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5066:
5067: if (mobilav!=0) {
5068: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5069: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5070: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5071: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5072: }
5073: }
5074:
5075: stepsize=(int) (stepm+YEARM-1)/YEARM;
5076: if (stepm<=12) stepsize=1;
5077:
5078: agelim=AGESUP;
5079:
5080: hstepm=1;
5081: hstepm=hstepm/stepm;
5082:
5083: if (popforecast==1) {
5084: if((ficpop=fopen(popfile,"r"))==NULL) {
5085: printf("Problem with population file : %s\n",popfile);exit(0);
5086: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5087: }
5088: popage=ivector(0,AGESUP);
5089: popeffectif=vector(0,AGESUP);
5090: popcount=vector(0,AGESUP);
5091:
5092: i=1;
5093: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5094:
5095: imx=i;
5096: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5097: }
5098:
5099: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5100: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5101: k=k+1;
5102: fprintf(ficrespop,"\n#******");
5103: for(j=1;j<=cptcoveff;j++) {
1.198 ! brouard 5104: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5105: }
5106: fprintf(ficrespop,"******\n");
5107: fprintf(ficrespop,"# Age");
5108: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5109: if (popforecast==1) fprintf(ficrespop," [Population]");
5110:
5111: for (cpt=0; cpt<=0;cpt++) {
5112: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5113:
5114: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5115: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5116: nhstepm = nhstepm/hstepm;
5117:
5118: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5119: oldm=oldms;savm=savms;
5120: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5121:
5122: for (h=0; h<=nhstepm; h++){
5123: if (h==(int) (calagedatem+YEARM*cpt)) {
5124: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5125: }
5126: for(j=1; j<=nlstate+ndeath;j++) {
5127: kk1=0.;kk2=0;
5128: for(i=1; i<=nlstate;i++) {
5129: if (mobilav==1)
5130: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5131: else {
5132: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5133: }
5134: }
5135: if (h==(int)(calagedatem+12*cpt)){
5136: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5137: /*fprintf(ficrespop," %.3f", kk1);
5138: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5139: }
5140: }
5141: for(i=1; i<=nlstate;i++){
5142: kk1=0.;
5143: for(j=1; j<=nlstate;j++){
5144: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5145: }
5146: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5147: }
5148:
5149: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5150: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5151: }
5152: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5153: }
5154: }
5155:
5156: /******/
5157:
5158: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5159: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5160: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5161: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5162: nhstepm = nhstepm/hstepm;
5163:
5164: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5165: oldm=oldms;savm=savms;
5166: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5167: for (h=0; h<=nhstepm; h++){
5168: if (h==(int) (calagedatem+YEARM*cpt)) {
5169: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5170: }
5171: for(j=1; j<=nlstate+ndeath;j++) {
5172: kk1=0.;kk2=0;
5173: for(i=1; i<=nlstate;i++) {
5174: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5175: }
5176: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5177: }
5178: }
5179: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5180: }
5181: }
5182: }
5183: }
5184:
5185: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5186:
5187: if (popforecast==1) {
5188: free_ivector(popage,0,AGESUP);
5189: free_vector(popeffectif,0,AGESUP);
5190: free_vector(popcount,0,AGESUP);
5191: }
5192: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5193: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5194: fclose(ficrespop);
5195: } /* End of popforecast */
5196:
5197: int fileappend(FILE *fichier, char *optionfich)
5198: {
5199: if((fichier=fopen(optionfich,"a"))==NULL) {
5200: printf("Problem with file: %s\n", optionfich);
5201: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5202: return (0);
5203: }
5204: fflush(fichier);
5205: return (1);
5206: }
5207:
5208:
5209: /**************** function prwizard **********************/
5210: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5211: {
5212:
5213: /* Wizard to print covariance matrix template */
5214:
1.164 brouard 5215: char ca[32], cb[32];
5216: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5217: int numlinepar;
5218:
5219: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5220: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5221: for(i=1; i <=nlstate; i++){
5222: jj=0;
5223: for(j=1; j <=nlstate+ndeath; j++){
5224: if(j==i) continue;
5225: jj++;
5226: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5227: printf("%1d%1d",i,j);
5228: fprintf(ficparo,"%1d%1d",i,j);
5229: for(k=1; k<=ncovmodel;k++){
5230: /* printf(" %lf",param[i][j][k]); */
5231: /* fprintf(ficparo," %lf",param[i][j][k]); */
5232: printf(" 0.");
5233: fprintf(ficparo," 0.");
5234: }
5235: printf("\n");
5236: fprintf(ficparo,"\n");
5237: }
5238: }
5239: printf("# Scales (for hessian or gradient estimation)\n");
5240: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5241: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5242: for(i=1; i <=nlstate; i++){
5243: jj=0;
5244: for(j=1; j <=nlstate+ndeath; j++){
5245: if(j==i) continue;
5246: jj++;
5247: fprintf(ficparo,"%1d%1d",i,j);
5248: printf("%1d%1d",i,j);
5249: fflush(stdout);
5250: for(k=1; k<=ncovmodel;k++){
5251: /* printf(" %le",delti3[i][j][k]); */
5252: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5253: printf(" 0.");
5254: fprintf(ficparo," 0.");
5255: }
5256: numlinepar++;
5257: printf("\n");
5258: fprintf(ficparo,"\n");
5259: }
5260: }
5261: printf("# Covariance matrix\n");
5262: /* # 121 Var(a12)\n\ */
5263: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5264: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5265: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5266: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5267: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5268: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5269: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5270: fflush(stdout);
5271: fprintf(ficparo,"# Covariance matrix\n");
5272: /* # 121 Var(a12)\n\ */
5273: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5274: /* # ...\n\ */
5275: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5276:
5277: for(itimes=1;itimes<=2;itimes++){
5278: jj=0;
5279: for(i=1; i <=nlstate; i++){
5280: for(j=1; j <=nlstate+ndeath; j++){
5281: if(j==i) continue;
5282: for(k=1; k<=ncovmodel;k++){
5283: jj++;
5284: ca[0]= k+'a'-1;ca[1]='\0';
5285: if(itimes==1){
5286: printf("#%1d%1d%d",i,j,k);
5287: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5288: }else{
5289: printf("%1d%1d%d",i,j,k);
5290: fprintf(ficparo,"%1d%1d%d",i,j,k);
5291: /* printf(" %.5le",matcov[i][j]); */
5292: }
5293: ll=0;
5294: for(li=1;li <=nlstate; li++){
5295: for(lj=1;lj <=nlstate+ndeath; lj++){
5296: if(lj==li) continue;
5297: for(lk=1;lk<=ncovmodel;lk++){
5298: ll++;
5299: if(ll<=jj){
5300: cb[0]= lk +'a'-1;cb[1]='\0';
5301: if(ll<jj){
5302: if(itimes==1){
5303: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5304: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5305: }else{
5306: printf(" 0.");
5307: fprintf(ficparo," 0.");
5308: }
5309: }else{
5310: if(itimes==1){
5311: printf(" Var(%s%1d%1d)",ca,i,j);
5312: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5313: }else{
5314: printf(" 0.");
5315: fprintf(ficparo," 0.");
5316: }
5317: }
5318: }
5319: } /* end lk */
5320: } /* end lj */
5321: } /* end li */
5322: printf("\n");
5323: fprintf(ficparo,"\n");
5324: numlinepar++;
5325: } /* end k*/
5326: } /*end j */
5327: } /* end i */
5328: } /* end itimes */
5329:
5330: } /* end of prwizard */
5331: /******************* Gompertz Likelihood ******************************/
5332: double gompertz(double x[])
5333: {
5334: double A,B,L=0.0,sump=0.,num=0.;
5335: int i,n=0; /* n is the size of the sample */
5336:
5337: for (i=0;i<=imx-1 ; i++) {
5338: sump=sump+weight[i];
5339: /* sump=sump+1;*/
5340: num=num+1;
5341: }
5342:
5343:
5344: /* for (i=0; i<=imx; i++)
5345: 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]);*/
5346:
5347: for (i=1;i<=imx ; i++)
5348: {
5349: if (cens[i] == 1 && wav[i]>1)
5350: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5351:
5352: if (cens[i] == 0 && wav[i]>1)
5353: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5354: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5355:
5356: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5357: if (wav[i] > 1 ) { /* ??? */
5358: L=L+A*weight[i];
5359: /* 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]);*/
5360: }
5361: }
5362:
5363: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5364:
5365: return -2*L*num/sump;
5366: }
5367:
1.136 brouard 5368: #ifdef GSL
5369: /******************* Gompertz_f Likelihood ******************************/
5370: double gompertz_f(const gsl_vector *v, void *params)
5371: {
5372: double A,B,LL=0.0,sump=0.,num=0.;
5373: double *x= (double *) v->data;
5374: int i,n=0; /* n is the size of the sample */
5375:
5376: for (i=0;i<=imx-1 ; i++) {
5377: sump=sump+weight[i];
5378: /* sump=sump+1;*/
5379: num=num+1;
5380: }
5381:
5382:
5383: /* for (i=0; i<=imx; i++)
5384: 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]);*/
5385: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5386: for (i=1;i<=imx ; i++)
5387: {
5388: if (cens[i] == 1 && wav[i]>1)
5389: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5390:
5391: if (cens[i] == 0 && wav[i]>1)
5392: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5393: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5394:
5395: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5396: if (wav[i] > 1 ) { /* ??? */
5397: LL=LL+A*weight[i];
5398: /* 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]);*/
5399: }
5400: }
5401:
5402: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5403: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5404:
5405: return -2*LL*num/sump;
5406: }
5407: #endif
5408:
1.126 brouard 5409: /******************* Printing html file ***********/
5410: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5411: int lastpass, int stepm, int weightopt, char model[],\
5412: int imx, double p[],double **matcov,double agemortsup){
5413: int i,k;
5414:
5415: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5416: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5417: for (i=1;i<=2;i++)
5418: 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]));
5419: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5420: fprintf(fichtm,"</ul>");
5421:
5422: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5423:
5424: 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>");
5425:
5426: for (k=agegomp;k<(agemortsup-2);k++)
5427: 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]);
5428:
5429:
5430: fflush(fichtm);
5431: }
5432:
5433: /******************* Gnuplot file **************/
5434: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5435:
5436: char dirfileres[132],optfileres[132];
1.164 brouard 5437:
1.126 brouard 5438: int ng;
5439:
5440:
5441: /*#ifdef windows */
5442: fprintf(ficgp,"cd \"%s\" \n",pathc);
5443: /*#endif */
5444:
5445:
5446: strcpy(dirfileres,optionfilefiname);
5447: strcpy(optfileres,"vpl");
5448: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5449: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5450: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5451: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5452: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5453:
5454: }
5455:
1.136 brouard 5456: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5457: {
1.126 brouard 5458:
1.136 brouard 5459: /*-------- data file ----------*/
5460: FILE *fic;
5461: char dummy[]=" ";
1.164 brouard 5462: int i=0, j=0, n=0;
1.136 brouard 5463: int linei, month, year,iout;
5464: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5465: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5466: char *stratrunc;
5467: int lstra;
1.126 brouard 5468:
5469:
1.136 brouard 5470: if((fic=fopen(datafile,"r"))==NULL) {
1.195 brouard 5471: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5472: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136 brouard 5473: }
1.126 brouard 5474:
1.136 brouard 5475: i=1;
5476: linei=0;
5477: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5478: linei=linei+1;
5479: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5480: if(line[j] == '\t')
5481: line[j] = ' ';
5482: }
5483: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5484: ;
5485: };
5486: line[j+1]=0; /* Trims blanks at end of line */
5487: if(line[0]=='#'){
5488: fprintf(ficlog,"Comment line\n%s\n",line);
5489: printf("Comment line\n%s\n",line);
5490: continue;
5491: }
5492: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5493: strcpy(line, linetmp);
1.136 brouard 5494:
1.126 brouard 5495:
1.136 brouard 5496: for (j=maxwav;j>=1;j--){
1.137 brouard 5497: cutv(stra, strb, line, ' ');
1.136 brouard 5498: if(strb[0]=='.') { /* Missing status */
5499: lval=-1;
5500: }else{
5501: errno=0;
5502: lval=strtol(strb,&endptr,10);
5503: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5504: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5505: 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);
5506: 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 5507: return 1;
5508: }
5509: }
5510: s[j][i]=lval;
5511:
5512: strcpy(line,stra);
5513: cutv(stra, strb,line,' ');
1.169 brouard 5514: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5515: }
1.169 brouard 5516: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5517: month=99;
5518: year=9999;
5519: }else{
1.141 brouard 5520: 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);
5521: 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 5522: return 1;
5523: }
5524: anint[j][i]= (double) year;
5525: mint[j][i]= (double)month;
5526: strcpy(line,stra);
5527: } /* ENd Waves */
5528:
5529: cutv(stra, strb,line,' ');
1.169 brouard 5530: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5531: }
1.169 brouard 5532: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5533: month=99;
5534: year=9999;
5535: }else{
1.141 brouard 5536: 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);
5537: 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 5538: return 1;
5539: }
5540: andc[i]=(double) year;
5541: moisdc[i]=(double) month;
5542: strcpy(line,stra);
5543:
5544: cutv(stra, strb,line,' ');
1.169 brouard 5545: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5546: }
1.169 brouard 5547: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5548: month=99;
5549: year=9999;
5550: }else{
1.141 brouard 5551: 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);
5552: 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 5553: return 1;
5554: }
5555: if (year==9999) {
1.141 brouard 5556: 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);
5557: 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 5558: return 1;
1.126 brouard 5559:
1.136 brouard 5560: }
5561: annais[i]=(double)(year);
5562: moisnais[i]=(double)(month);
5563: strcpy(line,stra);
5564:
5565: cutv(stra, strb,line,' ');
5566: errno=0;
5567: dval=strtod(strb,&endptr);
5568: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5569: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5570: 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 5571: fflush(ficlog);
5572: return 1;
5573: }
5574: weight[i]=dval;
5575: strcpy(line,stra);
5576:
5577: for (j=ncovcol;j>=1;j--){
5578: cutv(stra, strb,line,' ');
5579: if(strb[0]=='.') { /* Missing status */
5580: lval=-1;
5581: }else{
5582: errno=0;
5583: lval=strtol(strb,&endptr,10);
5584: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5585: 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);
5586: 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 5587: return 1;
5588: }
5589: }
5590: if(lval <-1 || lval >1){
1.141 brouard 5591: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5592: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5593: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5594: For example, for multinomial values like 1, 2 and 3,\n \
5595: build V1=0 V2=0 for the reference value (1),\n \
5596: V1=1 V2=0 for (2) \n \
5597: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5598: output of IMaCh is often meaningless.\n \
5599: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5600: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5601: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5602: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5603: For example, for multinomial values like 1, 2 and 3,\n \
5604: build V1=0 V2=0 for the reference value (1),\n \
5605: V1=1 V2=0 for (2) \n \
5606: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5607: output of IMaCh is often meaningless.\n \
5608: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5609: return 1;
5610: }
5611: covar[j][i]=(double)(lval);
5612: strcpy(line,stra);
5613: }
5614: lstra=strlen(stra);
5615:
5616: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5617: stratrunc = &(stra[lstra-9]);
5618: num[i]=atol(stratrunc);
5619: }
5620: else
5621: num[i]=atol(stra);
5622: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5623: 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;}*/
5624:
5625: i=i+1;
5626: } /* End loop reading data */
1.126 brouard 5627:
1.136 brouard 5628: *imax=i-1; /* Number of individuals */
5629: fclose(fic);
5630:
5631: return (0);
1.164 brouard 5632: /* endread: */
1.136 brouard 5633: printf("Exiting readdata: ");
5634: fclose(fic);
5635: return (1);
1.126 brouard 5636:
5637:
5638:
1.136 brouard 5639: }
1.145 brouard 5640: void removespace(char *str) {
5641: char *p1 = str, *p2 = str;
5642: do
5643: while (*p2 == ' ')
5644: p2++;
1.169 brouard 5645: while (*p1++ == *p2++);
1.145 brouard 5646: }
5647:
5648: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5649: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5650: * - nagesqr = 1 if age*age in the model, otherwise 0.
5651: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5652: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5653: * - cptcovage number of covariates with age*products =2
5654: * - cptcovs number of simple covariates
5655: * - 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
5656: * which is a new column after the 9 (ncovcol) variables.
5657: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5658: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5659: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5660: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5661: */
1.136 brouard 5662: {
1.145 brouard 5663: int i, j, k, ks;
1.164 brouard 5664: int j1, k1, k2;
1.136 brouard 5665: char modelsav[80];
1.145 brouard 5666: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 5667: char *strpt;
1.136 brouard 5668:
1.145 brouard 5669: /*removespace(model);*/
1.136 brouard 5670: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5671: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 5672: if (strstr(model,"AGE") !=0){
1.192 brouard 5673: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
5674: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 5675: return 1;
5676: }
1.141 brouard 5677: if (strstr(model,"v") !=0){
5678: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5679: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5680: return 1;
5681: }
1.187 brouard 5682: strcpy(modelsav,model);
5683: if ((strpt=strstr(model,"age*age")) !=0){
5684: printf(" strpt=%s, model=%s\n",strpt, model);
5685: if(strpt != model){
5686: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5687: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5688: corresponding column of parameters.\n",model);
5689: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5690: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5691: corresponding column of parameters.\n",model); fflush(ficlog);
5692: return 1;
5693: }
5694:
5695: nagesqr=1;
5696: if (strstr(model,"+age*age") !=0)
5697: substrchaine(modelsav, model, "+age*age");
5698: else if (strstr(model,"age*age+") !=0)
5699: substrchaine(modelsav, model, "age*age+");
5700: else
5701: substrchaine(modelsav, model, "age*age");
5702: }else
5703: nagesqr=0;
5704: if (strlen(modelsav) >1){
5705: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5706: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5707: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5708: cptcovt= j+1; /* Number of total covariates in the model, not including
5709: * cst, age and age*age
5710: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5711: /* including age products which are counted in cptcovage.
5712: * but the covariates which are products must be treated
5713: * separately: ncovn=4- 2=2 (V1+V3). */
5714: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5715: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5716:
5717:
5718: /* Design
5719: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5720: * < ncovcol=8 >
5721: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5722: * k= 1 2 3 4 5 6 7 8
5723: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5724: * covar[k,i], value of kth covariate if not including age for individual i:
5725: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5726: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5727: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5728: * Tage[++cptcovage]=k
5729: * if products, new covar are created after ncovcol with k1
5730: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5731: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5732: * 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
5733: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5734: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5735: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5736: * < ncovcol=8 >
5737: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5738: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5739: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5740: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5741: * p Tprod[1]@2={ 6, 5}
5742: *p Tvard[1][1]@4= {7, 8, 5, 6}
5743: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5744: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5745: *How to reorganize?
5746: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5747: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5748: * {2, 1, 4, 8, 5, 6, 3, 7}
5749: * Struct []
5750: */
1.145 brouard 5751:
1.187 brouard 5752: /* This loop fills the array Tvar from the string 'model'.*/
5753: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5754: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5755: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5756: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5757: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5758: /* k=1 Tvar[1]=2 (from V2) */
5759: /* k=5 Tvar[5] */
5760: /* for (k=1; k<=cptcovn;k++) { */
1.198 ! brouard 5761: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187 brouard 5762: /* } */
1.198 ! brouard 5763: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187 brouard 5764: /*
5765: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5766: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 5767: Tvar[k]=0;
1.187 brouard 5768: cptcovage=0;
5769: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5770: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5771: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5772: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5773: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5774: /*scanf("%d",i);*/
5775: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5776: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5777: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5778: /* covar is not filled and then is empty */
5779: cptcovprod--;
5780: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5781: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5782: cptcovage++; /* Sums the number of covariates which include age as a product */
5783: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5784: /*printf("stre=%s ", stre);*/
5785: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5786: cptcovprod--;
5787: cutl(stre,strb,strc,'V');
5788: Tvar[k]=atoi(stre);
5789: cptcovage++;
5790: Tage[cptcovage]=k;
5791: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5792: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5793: cptcovn++;
5794: cptcovprodnoage++;k1++;
5795: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5796: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5797: because this model-covariate is a construction we invent a new column
5798: ncovcol + k1
5799: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5800: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5801: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5802: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5803: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5804: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5805: k2=k2+2;
5806: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5807: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5808: for (i=1; i<=lastobs;i++){
5809: /* Computes the new covariate which is a product of
5810: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5811: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5812: }
5813: } /* End age is not in the model */
5814: } /* End if model includes a product */
5815: else { /* no more sum */
5816: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5817: /* scanf("%d",i);*/
5818: cutl(strd,strc,strb,'V');
5819: ks++; /**< Number of simple covariates */
1.145 brouard 5820: cptcovn++;
1.187 brouard 5821: Tvar[k]=atoi(strd);
5822: }
5823: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5824: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5825: scanf("%d",i);*/
5826: } /* end of loop + on total covariates */
5827: } /* end if strlen(modelsave == 0) age*age might exist */
5828: } /* end if strlen(model == 0) */
1.136 brouard 5829:
5830: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5831: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5832:
5833: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5834: printf("cptcovprod=%d ", cptcovprod);
5835: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5836:
5837: scanf("%d ",i);*/
5838:
5839:
1.137 brouard 5840: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5841: /*endread:*/
1.136 brouard 5842: printf("Exiting decodemodel: ");
5843: return (1);
5844: }
5845:
1.169 brouard 5846: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5847: {
5848: int i, m;
5849:
5850: for (i=1; i<=imx; i++) {
5851: for(m=2; (m<= maxwav); m++) {
5852: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5853: anint[m][i]=9999;
5854: s[m][i]=-1;
5855: }
5856: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5857: *nberr = *nberr + 1;
5858: 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);
5859: 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 5860: s[m][i]=-1;
5861: }
5862: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5863: (*nberr)++;
1.136 brouard 5864: 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]);
5865: 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]);
5866: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5867: }
5868: }
5869: }
5870:
5871: for (i=1; i<=imx; i++) {
5872: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5873: for(m=firstpass; (m<= lastpass); m++){
5874: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5875: if (s[m][i] >= nlstate+1) {
1.169 brouard 5876: if(agedc[i]>0){
5877: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5878: agev[m][i]=agedc[i];
5879: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5880: }else {
1.136 brouard 5881: if ((int)andc[i]!=9999){
5882: nbwarn++;
5883: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5884: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5885: agev[m][i]=-1;
5886: }
5887: }
1.169 brouard 5888: } /* agedc > 0 */
1.136 brouard 5889: }
5890: else if(s[m][i] !=9){ /* Standard case, age in fractional
5891: years but with the precision of a month */
5892: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5893: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5894: agev[m][i]=1;
5895: else if(agev[m][i] < *agemin){
5896: *agemin=agev[m][i];
5897: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5898: }
5899: else if(agev[m][i] >*agemax){
5900: *agemax=agev[m][i];
1.156 brouard 5901: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5902: }
5903: /*agev[m][i]=anint[m][i]-annais[i];*/
5904: /* agev[m][i] = age[i]+2*m;*/
5905: }
5906: else { /* =9 */
5907: agev[m][i]=1;
5908: s[m][i]=-1;
5909: }
5910: }
5911: else /*= 0 Unknown */
5912: agev[m][i]=1;
5913: }
5914:
5915: }
5916: for (i=1; i<=imx; i++) {
5917: for(m=firstpass; (m<=lastpass); m++){
5918: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5919: (*nberr)++;
1.136 brouard 5920: 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);
5921: 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);
5922: return 1;
5923: }
5924: }
5925: }
5926:
5927: /*for (i=1; i<=imx; i++){
5928: for (m=firstpass; (m<lastpass); m++){
5929: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5930: }
5931:
5932: }*/
5933:
5934:
1.139 brouard 5935: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5936: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5937:
5938: return (0);
1.164 brouard 5939: /* endread:*/
1.136 brouard 5940: printf("Exiting calandcheckages: ");
5941: return (1);
5942: }
5943:
1.172 brouard 5944: #if defined(_MSC_VER)
5945: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5946: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5947: //#include "stdafx.h"
5948: //#include <stdio.h>
5949: //#include <tchar.h>
5950: //#include <windows.h>
5951: //#include <iostream>
5952: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5953:
5954: LPFN_ISWOW64PROCESS fnIsWow64Process;
5955:
5956: BOOL IsWow64()
5957: {
5958: BOOL bIsWow64 = FALSE;
5959:
5960: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5961: // (HANDLE, PBOOL);
5962:
5963: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5964:
5965: HMODULE module = GetModuleHandle(_T("kernel32"));
5966: const char funcName[] = "IsWow64Process";
5967: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5968: GetProcAddress(module, funcName);
5969:
5970: if (NULL != fnIsWow64Process)
5971: {
5972: if (!fnIsWow64Process(GetCurrentProcess(),
5973: &bIsWow64))
5974: //throw std::exception("Unknown error");
5975: printf("Unknown error\n");
5976: }
5977: return bIsWow64 != FALSE;
5978: }
5979: #endif
1.177 brouard 5980:
1.191 brouard 5981: void syscompilerinfo(int logged)
1.167 brouard 5982: {
5983: /* #include "syscompilerinfo.h"*/
1.185 brouard 5984: /* command line Intel compiler 32bit windows, XP compatible:*/
5985: /* /GS /W3 /Gy
5986: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5987: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5988: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 5989: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5990: */
5991: /* 64 bits */
1.185 brouard 5992: /*
5993: /GS /W3 /Gy
5994: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5995: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5996: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5997: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5998: /* Optimization are useless and O3 is slower than O2 */
5999: /*
6000: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6001: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6002: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6003: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6004: */
1.186 brouard 6005: /* Link is */ /* /OUT:"visual studio
1.185 brouard 6006: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6007: /PDB:"visual studio
6008: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6009: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6010: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6011: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6012: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6013: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6014: uiAccess='false'"
6015: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6016: /NOLOGO /TLBID:1
6017: */
1.177 brouard 6018: #if defined __INTEL_COMPILER
1.178 brouard 6019: #if defined(__GNUC__)
6020: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6021: #endif
1.177 brouard 6022: #elif defined(__GNUC__)
1.179 brouard 6023: #ifndef __APPLE__
1.174 brouard 6024: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 6025: #endif
1.177 brouard 6026: struct utsname sysInfo;
1.178 brouard 6027: int cross = CROSS;
6028: if (cross){
6029: printf("Cross-");
1.191 brouard 6030: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6031: }
1.174 brouard 6032: #endif
6033:
1.171 brouard 6034: #include <stdint.h>
1.178 brouard 6035:
1.191 brouard 6036: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6037: #if defined(__clang__)
1.191 brouard 6038: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6039: #endif
6040: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6041: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6042: #endif
6043: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6044: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6045: #endif
6046: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6047: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6048: #endif
6049: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6050: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6051: #endif
6052: #if defined(_MSC_VER)
1.191 brouard 6053: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6054: #endif
6055: #if defined(__PGI)
1.191 brouard 6056: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6057: #endif
6058: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6059: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6060: #endif
1.191 brouard 6061: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6062:
1.167 brouard 6063: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6064: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6065: // Windows (x64 and x86)
1.191 brouard 6066: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6067: #elif __unix__ // all unices, not all compilers
6068: // Unix
1.191 brouard 6069: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6070: #elif __linux__
6071: // linux
1.191 brouard 6072: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6073: #elif __APPLE__
1.174 brouard 6074: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6075: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6076: #endif
6077:
6078: /* __MINGW32__ */
6079: /* __CYGWIN__ */
6080: /* __MINGW64__ */
6081: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6082: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6083: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6084: /* _WIN64 // Defined for applications for Win64. */
6085: /* _M_X64 // Defined for compilations that target x64 processors. */
6086: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6087:
1.167 brouard 6088: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6089: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6090: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6091: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6092: #else
1.191 brouard 6093: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6094: #endif
6095:
1.169 brouard 6096: #if defined(__GNUC__)
6097: # if defined(__GNUC_PATCHLEVEL__)
6098: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6099: + __GNUC_MINOR__ * 100 \
6100: + __GNUC_PATCHLEVEL__)
6101: # else
6102: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6103: + __GNUC_MINOR__ * 100)
6104: # endif
1.174 brouard 6105: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6106: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6107:
6108: if (uname(&sysInfo) != -1) {
6109: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6110: 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 6111: }
6112: else
6113: perror("uname() error");
1.179 brouard 6114: //#ifndef __INTEL_COMPILER
6115: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6116: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6117: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6118: #endif
1.169 brouard 6119: #endif
1.172 brouard 6120:
6121: // void main()
6122: // {
1.169 brouard 6123: #if defined(_MSC_VER)
1.174 brouard 6124: if (IsWow64()){
1.191 brouard 6125: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6126: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6127: }
6128: else{
1.191 brouard 6129: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6130: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6131: }
1.172 brouard 6132: // printf("\nPress Enter to continue...");
6133: // getchar();
6134: // }
6135:
1.169 brouard 6136: #endif
6137:
1.167 brouard 6138:
6139: }
1.136 brouard 6140:
1.180 brouard 6141: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6142: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6143: int i, j, k, i1 ;
6144: double ftolpl = 1.e-10;
6145: double age, agebase, agelim;
6146:
6147: strcpy(filerespl,"pl");
6148: strcat(filerespl,fileres);
6149: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6150: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6151: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6152: }
6153: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6154: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6155: pstamp(ficrespl);
6156: fprintf(ficrespl,"# Period (stable) prevalence \n");
6157: fprintf(ficrespl,"#Age ");
6158: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6159: fprintf(ficrespl,"\n");
6160:
6161: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6162:
6163: agebase=ageminpar;
6164: agelim=agemaxpar;
6165:
6166: i1=pow(2,cptcoveff);
6167: if (cptcovn < 1){i1=1;}
6168:
6169: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6170: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6171: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6172: k=k+1;
6173: /* to clean */
1.198 ! brouard 6174: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.180 brouard 6175: fprintf(ficrespl,"\n#******");
6176: printf("\n#******");
6177: fprintf(ficlog,"\n#******");
6178: for(j=1;j<=cptcoveff;j++) {
1.198 ! brouard 6179: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
! 6180: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
! 6181: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6182: }
6183: fprintf(ficrespl,"******\n");
6184: printf("******\n");
6185: fprintf(ficlog,"******\n");
6186:
6187: fprintf(ficrespl,"#Age ");
6188: for(j=1;j<=cptcoveff;j++) {
1.198 ! brouard 6189: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6190: }
6191: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6192: fprintf(ficrespl,"\n");
6193:
6194: for (age=agebase; age<=agelim; age++){
6195: /* for (age=agebase; age<=agebase; age++){ */
6196: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6197: fprintf(ficrespl,"%.0f ",age );
6198: for(j=1;j<=cptcoveff;j++)
1.198 ! brouard 6199: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6200: for(i=1; i<=nlstate;i++)
6201: fprintf(ficrespl," %.5f", prlim[i][i]);
6202: fprintf(ficrespl,"\n");
6203: } /* Age */
6204: /* was end of cptcod */
6205: } /* cptcov */
1.184 brouard 6206: return 0;
1.180 brouard 6207: }
6208:
6209: int hPijx(double *p, int bage, int fage){
6210: /*------------- h Pij x at various ages ------------*/
6211:
6212: int stepsize;
6213: int agelim;
6214: int hstepm;
6215: int nhstepm;
6216: int h, i, i1, j, k;
6217:
6218: double agedeb;
6219: double ***p3mat;
6220:
6221: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6222: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6223: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6224: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6225: }
6226: printf("Computing pij: result on file '%s' \n", filerespij);
6227: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6228:
6229: stepsize=(int) (stepm+YEARM-1)/YEARM;
6230: /*if (stepm<=24) stepsize=2;*/
6231:
6232: agelim=AGESUP;
6233: hstepm=stepsize*YEARM; /* Every year of age */
6234: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6235:
6236: /* hstepm=1; aff par mois*/
6237: pstamp(ficrespij);
6238: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6239: i1= pow(2,cptcoveff);
1.183 brouard 6240: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6241: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6242: /* k=k+1; */
6243: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6244: fprintf(ficrespij,"\n#****** ");
6245: for(j=1;j<=cptcoveff;j++)
1.198 ! brouard 6246: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183 brouard 6247: fprintf(ficrespij,"******\n");
6248:
6249: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6250: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6251: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6252:
6253: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6254:
1.183 brouard 6255: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6256: oldm=oldms;savm=savms;
6257: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6258: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6259: for(i=1; i<=nlstate;i++)
6260: for(j=1; j<=nlstate+ndeath;j++)
6261: fprintf(ficrespij," %1d-%1d",i,j);
6262: fprintf(ficrespij,"\n");
6263: for (h=0; h<=nhstepm; h++){
6264: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6265: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6266: for(i=1; i<=nlstate;i++)
6267: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6268: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6269: fprintf(ficrespij,"\n");
6270: }
1.183 brouard 6271: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6272: fprintf(ficrespij,"\n");
6273: }
1.180 brouard 6274: /*}*/
6275: }
1.184 brouard 6276: return 0;
1.180 brouard 6277: }
6278:
6279:
1.136 brouard 6280: /***********************************************/
6281: /**************** Main Program *****************/
6282: /***********************************************/
6283:
6284: int main(int argc, char *argv[])
6285: {
6286: #ifdef GSL
6287: const gsl_multimin_fminimizer_type *T;
6288: size_t iteri = 0, it;
6289: int rval = GSL_CONTINUE;
6290: int status = GSL_SUCCESS;
6291: double ssval;
6292: #endif
6293: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6294: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6295:
6296: int jj, ll, li, lj, lk;
1.136 brouard 6297: int numlinepar=0; /* Current linenumber of parameter file */
1.197 brouard 6298: int num_filled;
1.136 brouard 6299: int itimes;
6300: int NDIM=2;
6301: int vpopbased=0;
6302:
1.164 brouard 6303: char ca[32], cb[32];
1.136 brouard 6304: /* FILE *fichtm; *//* Html File */
6305: /* FILE *ficgp;*/ /*Gnuplot File */
6306: struct stat info;
1.191 brouard 6307: double agedeb=0.;
1.194 brouard 6308:
6309: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6310:
1.165 brouard 6311: double fret;
1.191 brouard 6312: double dum=0.; /* Dummy variable */
1.136 brouard 6313: double ***p3mat;
6314: double ***mobaverage;
1.164 brouard 6315:
6316: char line[MAXLINE];
1.197 brouard 6317: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6318:
6319: char model[MAXLINE], modeltemp[MAXLINE];
1.136 brouard 6320: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6321: char *tok, *val; /* pathtot */
1.136 brouard 6322: int firstobs=1, lastobs=10;
1.195 brouard 6323: int c, h , cpt, c2;
1.191 brouard 6324: int jl=0;
6325: int i1, j1, jk, stepsize=0;
1.194 brouard 6326: int count=0;
6327:
1.164 brouard 6328: int *tab;
1.136 brouard 6329: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6330: int mobilav=0,popforecast=0;
1.191 brouard 6331: int hstepm=0, nhstepm=0;
1.136 brouard 6332: int agemortsup;
6333: float sumlpop=0.;
6334: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6335: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6336:
1.191 brouard 6337: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6338: double ftolpl=FTOL;
6339: double **prlim;
6340: double ***param; /* Matrix of parameters */
6341: double *p;
6342: double **matcov; /* Matrix of covariance */
6343: double ***delti3; /* Scale */
6344: double *delti; /* Scale */
6345: double ***eij, ***vareij;
6346: double **varpl; /* Variances of prevalence limits by age */
6347: double *epj, vepp;
1.164 brouard 6348:
1.136 brouard 6349: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6350: double **ximort;
1.145 brouard 6351: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6352: int *dcwave;
6353:
1.164 brouard 6354: char z[1]="c";
1.136 brouard 6355:
6356: /*char *strt;*/
6357: char strtend[80];
1.126 brouard 6358:
1.164 brouard 6359:
1.126 brouard 6360: /* setlocale (LC_ALL, ""); */
6361: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6362: /* textdomain (PACKAGE); */
6363: /* setlocale (LC_CTYPE, ""); */
6364: /* setlocale (LC_MESSAGES, ""); */
6365:
6366: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6367: rstart_time = time(NULL);
6368: /* (void) gettimeofday(&start_time,&tzp);*/
6369: start_time = *localtime(&rstart_time);
1.126 brouard 6370: curr_time=start_time;
1.157 brouard 6371: /*tml = *localtime(&start_time.tm_sec);*/
6372: /* strcpy(strstart,asctime(&tml)); */
6373: strcpy(strstart,asctime(&start_time));
1.126 brouard 6374:
6375: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6376: /* tp.tm_sec = tp.tm_sec +86400; */
6377: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6378: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6379: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6380: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6381: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6382: /* strt=asctime(&tmg); */
6383: /* printf("Time(after) =%s",strstart); */
6384: /* (void) time (&time_value);
6385: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6386: * tm = *localtime(&time_value);
6387: * strstart=asctime(&tm);
6388: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6389: */
6390:
6391: nberr=0; /* Number of errors and warnings */
6392: nbwarn=0;
1.184 brouard 6393: #ifdef WIN32
6394: _getcwd(pathcd, size);
6395: #else
1.126 brouard 6396: getcwd(pathcd, size);
1.184 brouard 6397: #endif
1.191 brouard 6398: syscompilerinfo(0);
1.196 brouard 6399: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126 brouard 6400: if(argc <=1){
6401: printf("\nEnter the parameter file name: ");
6402: fgets(pathr,FILENAMELENGTH,stdin);
6403: i=strlen(pathr);
6404: if(pathr[i-1]=='\n')
6405: pathr[i-1]='\0';
1.156 brouard 6406: i=strlen(pathr);
6407: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6408: pathr[i-1]='\0';
1.126 brouard 6409: for (tok = pathr; tok != NULL; ){
6410: printf("Pathr |%s|\n",pathr);
6411: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6412: printf("val= |%s| pathr=%s\n",val,pathr);
6413: strcpy (pathtot, val);
6414: if(pathr[0] == '\0') break; /* Dirty */
6415: }
6416: }
6417: else{
6418: strcpy(pathtot,argv[1]);
6419: }
6420: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6421: /*cygwin_split_path(pathtot,path,optionfile);
6422: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6423: /* cutv(path,optionfile,pathtot,'\\');*/
6424:
6425: /* Split argv[0], imach program to get pathimach */
6426: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6427: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6428: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6429: /* strcpy(pathimach,argv[0]); */
6430: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6431: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6432: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6433: #ifdef WIN32
6434: _chdir(path); /* Can be a relative path */
6435: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6436: #else
1.126 brouard 6437: chdir(path); /* Can be a relative path */
1.184 brouard 6438: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6439: #endif
6440: printf("Current directory %s!\n",pathcd);
1.126 brouard 6441: strcpy(command,"mkdir ");
6442: strcat(command,optionfilefiname);
6443: if((outcmd=system(command)) != 0){
1.169 brouard 6444: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6445: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6446: /* fclose(ficlog); */
6447: /* exit(1); */
6448: }
6449: /* if((imk=mkdir(optionfilefiname))<0){ */
6450: /* perror("mkdir"); */
6451: /* } */
6452:
6453: /*-------- arguments in the command line --------*/
6454:
1.186 brouard 6455: /* Main Log file */
1.126 brouard 6456: strcat(filelog, optionfilefiname);
6457: strcat(filelog,".log"); /* */
6458: if((ficlog=fopen(filelog,"w"))==NULL) {
6459: printf("Problem with logfile %s\n",filelog);
6460: goto end;
6461: }
6462: fprintf(ficlog,"Log filename:%s\n",filelog);
1.197 brouard 6463: fprintf(ficlog,"Version %s %s",version,fullversion);
1.126 brouard 6464: fprintf(ficlog,"\nEnter the parameter file name: \n");
6465: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6466: path=%s \n\
6467: optionfile=%s\n\
6468: optionfilext=%s\n\
1.156 brouard 6469: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6470:
1.197 brouard 6471: syscompilerinfo(1);
1.167 brouard 6472:
1.126 brouard 6473: printf("Local time (at start):%s",strstart);
6474: fprintf(ficlog,"Local time (at start): %s",strstart);
6475: fflush(ficlog);
6476: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6477: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6478:
6479: /* */
6480: strcpy(fileres,"r");
6481: strcat(fileres, optionfilefiname);
6482: strcat(fileres,".txt"); /* Other files have txt extension */
6483:
1.186 brouard 6484: /* Main ---------arguments file --------*/
1.126 brouard 6485:
6486: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6487: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6488: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6489: fflush(ficlog);
1.149 brouard 6490: /* goto end; */
6491: exit(70);
1.126 brouard 6492: }
6493:
6494:
6495:
6496: strcpy(filereso,"o");
6497: strcat(filereso,fileres);
6498: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6499: printf("Problem with Output resultfile: %s\n", filereso);
6500: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6501: fflush(ficlog);
6502: goto end;
6503: }
6504:
6505: /* Reads comments: lines beginning with '#' */
6506: numlinepar=0;
1.197 brouard 6507:
6508: /* First parameter line */
6509: while(fgets(line, MAXLINE, ficpar)) {
6510: /* If line starts with a # it is a comment */
6511: if (line[0] == '#') {
6512: numlinepar++;
6513: fputs(line,stdout);
6514: fputs(line,ficparo);
6515: fputs(line,ficlog);
6516: continue;
6517: }else
6518: break;
6519: }
6520: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6521: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6522: if (num_filled != 5) {
6523: printf("Should be 5 parameters\n");
6524: }
1.126 brouard 6525: numlinepar++;
1.197 brouard 6526: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6527: }
6528: /* Second parameter line */
6529: while(fgets(line, MAXLINE, ficpar)) {
6530: /* If line starts with a # it is a comment */
6531: if (line[0] == '#') {
6532: numlinepar++;
6533: fputs(line,stdout);
6534: fputs(line,ficparo);
6535: fputs(line,ficlog);
6536: continue;
6537: }else
6538: break;
6539: }
6540: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6541: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
6542: if (num_filled != 8) {
6543: printf("Not 8\n");
6544: }
6545: 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 6546: }
6547:
1.197 brouard 6548: /* Third parameter line */
6549: while(fgets(line, MAXLINE, ficpar)) {
6550: /* If line starts with a # it is a comment */
6551: if (line[0] == '#') {
6552: numlinepar++;
6553: fputs(line,stdout);
6554: fputs(line,ficparo);
6555: fputs(line,ficlog);
6556: continue;
6557: }else
6558: break;
6559: }
6560: if((num_filled=sscanf(line,"model=1+age%[^.\n]\n", model)) !=EOF){
6561: if (num_filled != 1) {
6562: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6563: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6564: model[0]='\0';
6565: goto end;
6566: }
6567: else{
6568: if (model[0]=='+'){
6569: for(i=1; i<=strlen(model);i++)
6570: modeltemp[i-1]=model[i];
6571: }
6572: strcpy(model,modeltemp);
6573: }
6574: printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout);
6575: }
6576: /* 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); */
6577: /* numlinepar=numlinepar+3; /\* In general *\/ */
6578: /* 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.187 brouard 6579: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6580: model[strlen(model)-1]='\0';
1.197 brouard 6581: 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);
6582: 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 6583: fflush(ficlog);
1.190 brouard 6584: /* if(model[0]=='#'|| model[0]== '\0'){ */
6585: if(model[0]=='#'){
1.187 brouard 6586: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6587: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6588: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6589: if(mle != -1){
6590: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6591: exit(1);
6592: }
6593: }
1.126 brouard 6594: while((c=getc(ficpar))=='#' && c!= EOF){
6595: ungetc(c,ficpar);
6596: fgets(line, MAXLINE, ficpar);
6597: numlinepar++;
1.195 brouard 6598: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
6599: z[0]=line[1];
6600: }
6601: /* printf("****line [1] = %c \n",line[1]); */
1.141 brouard 6602: fputs(line, stdout);
6603: //puts(line);
1.126 brouard 6604: fputs(line,ficparo);
6605: fputs(line,ficlog);
6606: }
6607: ungetc(c,ficpar);
6608:
6609:
1.145 brouard 6610: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6611: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6612: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6613: v1+v2*age+v2*v3 makes cptcovn = 3
6614: */
6615: if (strlen(model)>1)
1.187 brouard 6616: 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 6617: else
1.187 brouard 6618: ncovmodel=2; /* Constant and age */
1.133 brouard 6619: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6620: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6621: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6622: 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);
6623: 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);
6624: fflush(stdout);
6625: fclose (ficlog);
6626: goto end;
6627: }
1.126 brouard 6628: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6629: delti=delti3[1][1];
6630: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6631: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6632: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 6633: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6634: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6635: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6636: fclose (ficparo);
6637: fclose (ficlog);
6638: goto end;
6639: exit(0);
6640: }
1.186 brouard 6641: else if(mle==-3) { /* Main Wizard */
1.126 brouard 6642: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 6643: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6644: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6645: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6646: matcov=matrix(1,npar,1,npar);
6647: }
6648: else{
1.145 brouard 6649: /* Read guessed parameters */
1.126 brouard 6650: /* Reads comments: lines beginning with '#' */
6651: while((c=getc(ficpar))=='#' && c!= EOF){
6652: ungetc(c,ficpar);
6653: fgets(line, MAXLINE, ficpar);
6654: numlinepar++;
1.141 brouard 6655: fputs(line,stdout);
1.126 brouard 6656: fputs(line,ficparo);
6657: fputs(line,ficlog);
6658: }
6659: ungetc(c,ficpar);
6660:
6661: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6662: for(i=1; i <=nlstate; i++){
6663: j=0;
6664: for(jj=1; jj <=nlstate+ndeath; jj++){
6665: if(jj==i) continue;
6666: j++;
6667: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 6668: if ((i1 != i) || (j1 != jj)){
1.126 brouard 6669: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6670: It might be a problem of design; if ncovcol and the model are correct\n \
6671: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6672: exit(1);
6673: }
6674: fprintf(ficparo,"%1d%1d",i1,j1);
6675: if(mle==1)
1.193 brouard 6676: printf("%1d%1d",i,jj);
6677: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 6678: for(k=1; k<=ncovmodel;k++){
6679: fscanf(ficpar," %lf",¶m[i][j][k]);
6680: if(mle==1){
6681: printf(" %lf",param[i][j][k]);
6682: fprintf(ficlog," %lf",param[i][j][k]);
6683: }
6684: else
6685: fprintf(ficlog," %lf",param[i][j][k]);
6686: fprintf(ficparo," %lf",param[i][j][k]);
6687: }
6688: fscanf(ficpar,"\n");
6689: numlinepar++;
6690: if(mle==1)
6691: printf("\n");
6692: fprintf(ficlog,"\n");
6693: fprintf(ficparo,"\n");
6694: }
6695: }
6696: fflush(ficlog);
6697:
1.145 brouard 6698: /* Reads scales values */
1.126 brouard 6699: p=param[1][1];
6700:
6701: /* Reads comments: lines beginning with '#' */
6702: while((c=getc(ficpar))=='#' && c!= EOF){
6703: ungetc(c,ficpar);
6704: fgets(line, MAXLINE, ficpar);
6705: numlinepar++;
1.141 brouard 6706: fputs(line,stdout);
1.126 brouard 6707: fputs(line,ficparo);
6708: fputs(line,ficlog);
6709: }
6710: ungetc(c,ficpar);
6711:
6712: for(i=1; i <=nlstate; i++){
6713: for(j=1; j <=nlstate+ndeath-1; j++){
6714: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6715: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6716: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6717: exit(1);
6718: }
6719: printf("%1d%1d",i,j);
6720: fprintf(ficparo,"%1d%1d",i1,j1);
6721: fprintf(ficlog,"%1d%1d",i1,j1);
6722: for(k=1; k<=ncovmodel;k++){
6723: fscanf(ficpar,"%le",&delti3[i][j][k]);
6724: printf(" %le",delti3[i][j][k]);
6725: fprintf(ficparo," %le",delti3[i][j][k]);
6726: fprintf(ficlog," %le",delti3[i][j][k]);
6727: }
6728: fscanf(ficpar,"\n");
6729: numlinepar++;
6730: printf("\n");
6731: fprintf(ficparo,"\n");
6732: fprintf(ficlog,"\n");
6733: }
6734: }
6735: fflush(ficlog);
6736:
1.145 brouard 6737: /* Reads covariance matrix */
1.126 brouard 6738: delti=delti3[1][1];
6739:
6740:
6741: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6742:
6743: /* Reads comments: lines beginning with '#' */
6744: while((c=getc(ficpar))=='#' && c!= EOF){
6745: ungetc(c,ficpar);
6746: fgets(line, MAXLINE, ficpar);
6747: numlinepar++;
1.141 brouard 6748: fputs(line,stdout);
1.126 brouard 6749: fputs(line,ficparo);
6750: fputs(line,ficlog);
6751: }
6752: ungetc(c,ficpar);
6753:
6754: matcov=matrix(1,npar,1,npar);
1.131 brouard 6755: for(i=1; i <=npar; i++)
6756: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6757:
1.194 brouard 6758: /* Scans npar lines */
1.126 brouard 6759: for(i=1; i <=npar; i++){
1.194 brouard 6760: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
6761: if(count != 3){
6762: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
6763: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
6764: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
6765: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
6766: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
6767: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
6768: exit(1);
6769: }else
1.126 brouard 6770: if(mle==1)
1.194 brouard 6771: printf("%1d%1d%1d",i1,j1,jk);
6772: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
6773: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 6774: for(j=1; j <=i; j++){
6775: fscanf(ficpar," %le",&matcov[i][j]);
6776: if(mle==1){
6777: printf(" %.5le",matcov[i][j]);
6778: }
6779: fprintf(ficlog," %.5le",matcov[i][j]);
6780: fprintf(ficparo," %.5le",matcov[i][j]);
6781: }
6782: fscanf(ficpar,"\n");
6783: numlinepar++;
6784: if(mle==1)
6785: printf("\n");
6786: fprintf(ficlog,"\n");
6787: fprintf(ficparo,"\n");
6788: }
1.194 brouard 6789: /* End of read covariance matrix npar lines */
1.126 brouard 6790: for(i=1; i <=npar; i++)
6791: for(j=i+1;j<=npar;j++)
6792: matcov[i][j]=matcov[j][i];
6793:
6794: if(mle==1)
6795: printf("\n");
6796: fprintf(ficlog,"\n");
6797:
6798: fflush(ficlog);
6799:
6800: /*-------- Rewriting parameter file ----------*/
6801: strcpy(rfileres,"r"); /* "Rparameterfile */
6802: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6803: strcat(rfileres,"."); /* */
6804: strcat(rfileres,optionfilext); /* Other files have txt extension */
6805: if((ficres =fopen(rfileres,"w"))==NULL) {
6806: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6807: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6808: }
6809: fprintf(ficres,"#%s\n",version);
6810: } /* End of mle != -3 */
6811:
1.186 brouard 6812: /* Main data
6813: */
1.126 brouard 6814: n= lastobs;
6815: num=lvector(1,n);
6816: moisnais=vector(1,n);
6817: annais=vector(1,n);
6818: moisdc=vector(1,n);
6819: andc=vector(1,n);
6820: agedc=vector(1,n);
6821: cod=ivector(1,n);
6822: weight=vector(1,n);
6823: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6824: mint=matrix(1,maxwav,1,n);
6825: anint=matrix(1,maxwav,1,n);
1.131 brouard 6826: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6827: tab=ivector(1,NCOVMAX);
1.144 brouard 6828: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 6829: 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 6830:
1.136 brouard 6831: /* Reads data from file datafile */
6832: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6833: goto end;
6834:
6835: /* Calculation of the number of parameters from char model */
1.137 brouard 6836: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6837: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6838: k=3 V4 Tvar[k=3]= 4 (from V4)
6839: k=2 V1 Tvar[k=2]= 1 (from V1)
6840: k=1 Tvar[1]=2 (from V2)
6841: */
6842: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6843: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6844: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6845: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6846: */
6847: /* For model-covariate k tells which data-covariate to use but
6848: because this model-covariate is a construction we invent a new column
6849: ncovcol + k1
6850: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6851: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6852: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6853: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6854: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6855: */
1.145 brouard 6856: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6857: 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 6858: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6859: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6860: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6861: 4 covariates (3 plus signs)
6862: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6863: */
1.136 brouard 6864:
1.186 brouard 6865: /* Main decodemodel */
6866:
1.187 brouard 6867:
1.136 brouard 6868: if(decodemodel(model, lastobs) == 1)
6869: goto end;
6870:
1.137 brouard 6871: if((double)(lastobs-imx)/(double)imx > 1.10){
6872: nbwarn++;
6873: 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);
6874: 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);
6875: }
1.136 brouard 6876: /* if(mle==1){*/
1.137 brouard 6877: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6878: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6879: }
6880:
6881: /*-calculation of age at interview from date of interview and age at death -*/
6882: agev=matrix(1,maxwav,1,imx);
6883:
6884: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6885: goto end;
6886:
1.126 brouard 6887:
1.136 brouard 6888: agegomp=(int)agemin;
6889: free_vector(moisnais,1,n);
6890: free_vector(annais,1,n);
1.126 brouard 6891: /* free_matrix(mint,1,maxwav,1,n);
6892: free_matrix(anint,1,maxwav,1,n);*/
6893: free_vector(moisdc,1,n);
6894: free_vector(andc,1,n);
1.145 brouard 6895: /* */
6896:
1.126 brouard 6897: wav=ivector(1,imx);
6898: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6899: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6900: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6901:
6902: /* Concatenates waves */
6903: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6904: /* */
6905:
1.126 brouard 6906: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6907:
6908: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6909: ncodemax[1]=1;
1.145 brouard 6910: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 6911: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 6912: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 6913: /* Nbcode gives the value of the lth modality of jth covariate, in
6914: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6915: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 6916:
6917: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198 ! brouard 6918: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186 brouard 6919: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 6920: h=0;
6921:
6922:
6923: /*if (cptcovn > 0) */
1.126 brouard 6924:
1.145 brouard 6925:
1.126 brouard 6926: m=pow(2,cptcoveff);
6927:
1.144 brouard 6928: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 6929: * For k=4 covariates, h goes from 1 to 2**k
6930: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6931: * h\k 1 2 3 4
1.143 brouard 6932: *______________________________
6933: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6934: * 2 2 1 1 1
6935: * 3 i=2 1 2 1 1
6936: * 4 2 2 1 1
6937: * 5 i=3 1 i=2 1 2 1
6938: * 6 2 1 2 1
6939: * 7 i=4 1 2 2 1
6940: * 8 2 2 2 1
1.197 brouard 6941: * 9 i=5 1 i=3 1 i=2 1 2
6942: * 10 2 1 1 2
6943: * 11 i=6 1 2 1 2
6944: * 12 2 2 1 2
6945: * 13 i=7 1 i=4 1 2 2
6946: * 14 2 1 2 2
6947: * 15 i=8 1 2 2 2
6948: * 16 2 2 2 2
1.143 brouard 6949: */
1.197 brouard 6950: for(h=1; h <=100 ;h++){
6951: /* printf("h=%2d ", h); */
6952: for(k=1; k <=10; k++){
6953: /* printf("k=%d %d ",k,codtabm(h,k)); */
6954: codtab[h][k]=codtabm(h,k);
6955: }
6956: /* printf("\n"); */
6957: }
6958: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
6959: /* 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 *\/ */
6960: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
6961: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
6962: /* h++; */
6963: /* if (h>m) */
6964: /* h=1; */
6965: /* codtab[h][k]=j; */
6966: /* /\* codtab[12][3]=1; *\/ */
6967: /* /\*codtab[h][Tvar[k]]=j;*\/ */
6968: /* /\* 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]]); *\/ */
6969: /* } */
6970: /* } */
6971: /* } */
6972: /* } */
1.126 brouard 6973: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6974: codtab[1][2]=1;codtab[2][2]=2; */
1.197 brouard 6975: /* for(i=1; i <=m ;i++){ */
6976: /* for(k=1; k <=cptcovn; k++){ */
6977: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
6978: /* } */
6979: /* printf("\n"); */
6980: /* } */
6981: /* scanf("%d",i);*/
1.145 brouard 6982:
6983: free_ivector(Ndum,-1,NCOVMAX);
6984:
6985:
1.126 brouard 6986:
1.186 brouard 6987: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 6988: strcpy(optionfilegnuplot,optionfilefiname);
6989: if(mle==-3)
6990: strcat(optionfilegnuplot,"-mort");
6991: strcat(optionfilegnuplot,".gp");
6992:
6993: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6994: printf("Problem with file %s",optionfilegnuplot);
6995: }
6996: else{
6997: fprintf(ficgp,"\n# %s\n", version);
6998: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6999: //fprintf(ficgp,"set missing 'NaNq'\n");
7000: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 7001: }
7002: /* fclose(ficgp);*/
1.186 brouard 7003:
7004:
7005: /* Initialisation of --------- index.htm --------*/
1.126 brouard 7006:
7007: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7008: if(mle==-3)
7009: strcat(optionfilehtm,"-mort");
7010: strcat(optionfilehtm,".htm");
7011: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 7012: printf("Problem with %s \n",optionfilehtm);
7013: exit(0);
1.126 brouard 7014: }
7015:
7016: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7017: strcat(optionfilehtmcov,"-cov.htm");
7018: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7019: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7020: }
7021: else{
7022: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7023: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7024: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
7025: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7026: }
7027:
7028: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7029: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7030: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
7031: \n\
7032: <hr size=\"2\" color=\"#EC5E5E\">\
7033: <ul><li><h4>Parameter files</h4>\n\
7034: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7035: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7036: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7037: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7038: - Date and time at start: %s</ul>\n",\
7039: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7040: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7041: fileres,fileres,\
7042: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7043: fflush(fichtm);
7044:
7045: strcpy(pathr,path);
7046: strcat(pathr,optionfilefiname);
1.184 brouard 7047: #ifdef WIN32
7048: _chdir(optionfilefiname); /* Move to directory named optionfile */
7049: #else
1.126 brouard 7050: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 7051: #endif
7052:
1.126 brouard 7053:
7054: /* Calculates basic frequencies. Computes observed prevalence at single age
7055: and prints on file fileres'p'. */
7056: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7057:
7058: fprintf(fichtm,"\n");
7059: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7060: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7061: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7062: imx,agemin,agemax,jmin,jmax,jmean);
7063: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7064: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7065: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7066: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7067: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7068:
7069:
7070: /* For Powell, parameters are in a vector p[] starting at p[1]
7071: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7072: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7073:
7074: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 7075: /* For mortality only */
1.126 brouard 7076: if (mle==-3){
1.136 brouard 7077: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 7078: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 7079: cens=ivector(1,n);
7080: ageexmed=vector(1,n);
7081: agecens=vector(1,n);
7082: dcwave=ivector(1,n);
7083:
7084: for (i=1; i<=imx; i++){
7085: dcwave[i]=-1;
7086: for (m=firstpass; m<=lastpass; m++)
7087: if (s[m][i]>nlstate) {
7088: dcwave[i]=m;
7089: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7090: break;
7091: }
7092: }
7093:
7094: for (i=1; i<=imx; i++) {
7095: if (wav[i]>0){
7096: ageexmed[i]=agev[mw[1][i]][i];
7097: j=wav[i];
7098: agecens[i]=1.;
7099:
7100: if (ageexmed[i]> 1 && wav[i] > 0){
7101: agecens[i]=agev[mw[j][i]][i];
7102: cens[i]= 1;
7103: }else if (ageexmed[i]< 1)
7104: cens[i]= -1;
7105: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7106: cens[i]=0 ;
7107: }
7108: else cens[i]=-1;
7109: }
7110:
7111: for (i=1;i<=NDIM;i++) {
7112: for (j=1;j<=NDIM;j++)
7113: ximort[i][j]=(i == j ? 1.0 : 0.0);
7114: }
7115:
1.145 brouard 7116: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7117: /*printf("%lf %lf", p[1], p[2]);*/
7118:
7119:
1.136 brouard 7120: #ifdef GSL
7121: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7122: #else
1.126 brouard 7123: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7124: #endif
1.126 brouard 7125: strcpy(filerespow,"pow-mort");
7126: strcat(filerespow,fileres);
7127: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7128: printf("Problem with resultfile: %s\n", filerespow);
7129: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7130: }
1.136 brouard 7131: #ifdef GSL
7132: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7133: #else
1.126 brouard 7134: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7135: #endif
1.126 brouard 7136: /* for (i=1;i<=nlstate;i++)
7137: for(j=1;j<=nlstate+ndeath;j++)
7138: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7139: */
7140: fprintf(ficrespow,"\n");
1.136 brouard 7141: #ifdef GSL
7142: /* gsl starts here */
7143: T = gsl_multimin_fminimizer_nmsimplex;
7144: gsl_multimin_fminimizer *sfm = NULL;
7145: gsl_vector *ss, *x;
7146: gsl_multimin_function minex_func;
7147:
7148: /* Initial vertex size vector */
7149: ss = gsl_vector_alloc (NDIM);
7150:
7151: if (ss == NULL){
7152: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7153: }
7154: /* Set all step sizes to 1 */
7155: gsl_vector_set_all (ss, 0.001);
7156:
7157: /* Starting point */
1.126 brouard 7158:
1.136 brouard 7159: x = gsl_vector_alloc (NDIM);
7160:
7161: if (x == NULL){
7162: gsl_vector_free(ss);
7163: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7164: }
7165:
7166: /* Initialize method and iterate */
7167: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7168: /* gsl_vector_set(x, 0, 0.0268); */
7169: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7170: gsl_vector_set(x, 0, p[1]);
7171: gsl_vector_set(x, 1, p[2]);
7172:
7173: minex_func.f = &gompertz_f;
7174: minex_func.n = NDIM;
7175: minex_func.params = (void *)&p; /* ??? */
7176:
7177: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7178: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7179:
7180: printf("Iterations beginning .....\n\n");
7181: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7182:
7183: iteri=0;
7184: while (rval == GSL_CONTINUE){
7185: iteri++;
7186: status = gsl_multimin_fminimizer_iterate(sfm);
7187:
7188: if (status) printf("error: %s\n", gsl_strerror (status));
7189: fflush(0);
7190:
7191: if (status)
7192: break;
7193:
7194: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7195: ssval = gsl_multimin_fminimizer_size (sfm);
7196:
7197: if (rval == GSL_SUCCESS)
7198: printf ("converged to a local maximum at\n");
7199:
7200: printf("%5d ", iteri);
7201: for (it = 0; it < NDIM; it++){
7202: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7203: }
7204: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7205: }
7206:
7207: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7208:
7209: gsl_vector_free(x); /* initial values */
7210: gsl_vector_free(ss); /* inital step size */
7211: for (it=0; it<NDIM; it++){
7212: p[it+1]=gsl_vector_get(sfm->x,it);
7213: fprintf(ficrespow," %.12lf", p[it]);
7214: }
7215: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7216: #endif
7217: #ifdef POWELL
7218: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7219: #endif
1.126 brouard 7220: fclose(ficrespow);
7221:
7222: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7223:
7224: for(i=1; i <=NDIM; i++)
7225: for(j=i+1;j<=NDIM;j++)
7226: matcov[i][j]=matcov[j][i];
7227:
7228: printf("\nCovariance matrix\n ");
7229: for(i=1; i <=NDIM; i++) {
7230: for(j=1;j<=NDIM;j++){
7231: printf("%f ",matcov[i][j]);
7232: }
7233: printf("\n ");
7234: }
7235:
7236: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7237: for (i=1;i<=NDIM;i++) {
1.126 brouard 7238: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7239: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7240: }
1.126 brouard 7241: lsurv=vector(1,AGESUP);
7242: lpop=vector(1,AGESUP);
7243: tpop=vector(1,AGESUP);
7244: lsurv[agegomp]=100000;
7245:
7246: for (k=agegomp;k<=AGESUP;k++) {
7247: agemortsup=k;
7248: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7249: }
7250:
7251: for (k=agegomp;k<agemortsup;k++)
7252: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7253:
7254: for (k=agegomp;k<agemortsup;k++){
7255: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7256: sumlpop=sumlpop+lpop[k];
7257: }
7258:
7259: tpop[agegomp]=sumlpop;
7260: for (k=agegomp;k<(agemortsup-3);k++){
7261: /* tpop[k+1]=2;*/
7262: tpop[k+1]=tpop[k]-lpop[k];
7263: }
7264:
7265:
7266: printf("\nAge lx qx dx Lx Tx e(x)\n");
7267: for (k=agegomp;k<(agemortsup-2);k++)
7268: 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]);
7269:
7270:
7271: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7272: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7273: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7274: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7275: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7276: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7277: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7278: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7279: }else
7280: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7281: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7282: stepm, weightopt,\
7283: model,imx,p,matcov,agemortsup);
7284:
7285: free_vector(lsurv,1,AGESUP);
7286: free_vector(lpop,1,AGESUP);
7287: free_vector(tpop,1,AGESUP);
1.136 brouard 7288: #ifdef GSL
7289: free_ivector(cens,1,n);
7290: free_vector(agecens,1,n);
7291: free_ivector(dcwave,1,n);
7292: free_matrix(ximort,1,NDIM,1,NDIM);
7293: #endif
1.186 brouard 7294: } /* Endof if mle==-3 mortality only */
7295: /* Standard maximisation */
1.126 brouard 7296: else{ /* For mle >=1 */
1.132 brouard 7297: globpr=0;/* debug */
1.186 brouard 7298: /* Computes likelihood for initial parameters */
1.132 brouard 7299: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7300: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7301: for (k=1; k<=npar;k++)
7302: printf(" %d %8.5f",k,p[k]);
7303: printf("\n");
1.186 brouard 7304: globpr=1; /* again, to print the contributions */
1.126 brouard 7305: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7306: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7307: for (k=1; k<=npar;k++)
7308: printf(" %d %8.5f",k,p[k]);
7309: printf("\n");
1.186 brouard 7310: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126 brouard 7311: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7312: }
7313:
7314: /*--------- results files --------------*/
1.192 brouard 7315: 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 7316:
7317:
7318: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7319: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7320: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7321: for(i=1,jk=1; i <=nlstate; i++){
7322: for(k=1; k <=(nlstate+ndeath); k++){
7323: if (k != i) {
7324: printf("%d%d ",i,k);
7325: fprintf(ficlog,"%d%d ",i,k);
7326: fprintf(ficres,"%1d%1d ",i,k);
7327: for(j=1; j <=ncovmodel; j++){
1.190 brouard 7328: printf("%12.7f ",p[jk]);
7329: fprintf(ficlog,"%12.7f ",p[jk]);
7330: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 7331: jk++;
7332: }
7333: printf("\n");
7334: fprintf(ficlog,"\n");
7335: fprintf(ficres,"\n");
7336: }
7337: }
7338: }
7339: if(mle!=0){
7340: /* Computing hessian and covariance matrix */
7341: ftolhess=ftol; /* Usually correct */
7342: hesscov(matcov, p, npar, delti, ftolhess, func);
7343: }
1.197 brouard 7344: 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");
7345: 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");
1.193 brouard 7346: for(i=1,jk=1; i <=nlstate; i++){
7347: for(k=1; k <=(nlstate+ndeath); k++){
7348: if (k != i) {
7349: printf("%d%d ",i,k);
7350: fprintf(ficlog,"%d%d ",i,k);
7351: for(j=1; j <=ncovmodel; j++){
1.197 brouard 7352: 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]));
7353: 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]));
1.193 brouard 7354: jk++;
7355: }
7356: printf("\n");
7357: fprintf(ficlog,"\n");
7358: }
7359: }
7360: }
7361:
1.126 brouard 7362: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7363: printf("# Scales (for hessian or gradient estimation)\n");
7364: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7365: for(i=1,jk=1; i <=nlstate; i++){
7366: for(j=1; j <=nlstate+ndeath; j++){
7367: if (j!=i) {
7368: fprintf(ficres,"%1d%1d",i,j);
7369: printf("%1d%1d",i,j);
7370: fprintf(ficlog,"%1d%1d",i,j);
7371: for(k=1; k<=ncovmodel;k++){
7372: printf(" %.5e",delti[jk]);
7373: fprintf(ficlog," %.5e",delti[jk]);
7374: fprintf(ficres," %.5e",delti[jk]);
7375: jk++;
7376: }
7377: printf("\n");
7378: fprintf(ficlog,"\n");
7379: fprintf(ficres,"\n");
7380: }
7381: }
7382: }
7383:
7384: 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");
7385: if(mle>=1)
7386: 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");
7387: 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");
7388: /* # 121 Var(a12)\n\ */
7389: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7390: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7391: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7392: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7393: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7394: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7395: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7396:
7397:
7398: /* Just to have a covariance matrix which will be more understandable
7399: even is we still don't want to manage dictionary of variables
7400: */
7401: for(itimes=1;itimes<=2;itimes++){
7402: jj=0;
7403: for(i=1; i <=nlstate; i++){
7404: for(j=1; j <=nlstate+ndeath; j++){
7405: if(j==i) continue;
7406: for(k=1; k<=ncovmodel;k++){
7407: jj++;
7408: ca[0]= k+'a'-1;ca[1]='\0';
7409: if(itimes==1){
7410: if(mle>=1)
7411: printf("#%1d%1d%d",i,j,k);
7412: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7413: fprintf(ficres,"#%1d%1d%d",i,j,k);
7414: }else{
7415: if(mle>=1)
7416: printf("%1d%1d%d",i,j,k);
7417: fprintf(ficlog,"%1d%1d%d",i,j,k);
7418: fprintf(ficres,"%1d%1d%d",i,j,k);
7419: }
7420: ll=0;
7421: for(li=1;li <=nlstate; li++){
7422: for(lj=1;lj <=nlstate+ndeath; lj++){
7423: if(lj==li) continue;
7424: for(lk=1;lk<=ncovmodel;lk++){
7425: ll++;
7426: if(ll<=jj){
7427: cb[0]= lk +'a'-1;cb[1]='\0';
7428: if(ll<jj){
7429: if(itimes==1){
7430: if(mle>=1)
7431: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7432: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7433: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7434: }else{
7435: if(mle>=1)
7436: printf(" %.5e",matcov[jj][ll]);
7437: fprintf(ficlog," %.5e",matcov[jj][ll]);
7438: fprintf(ficres," %.5e",matcov[jj][ll]);
7439: }
7440: }else{
7441: if(itimes==1){
7442: if(mle>=1)
7443: printf(" Var(%s%1d%1d)",ca,i,j);
7444: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7445: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7446: }else{
7447: if(mle>=1)
7448: printf(" %.5e",matcov[jj][ll]);
7449: fprintf(ficlog," %.5e",matcov[jj][ll]);
7450: fprintf(ficres," %.5e",matcov[jj][ll]);
7451: }
7452: }
7453: }
7454: } /* end lk */
7455: } /* end lj */
7456: } /* end li */
7457: if(mle>=1)
7458: printf("\n");
7459: fprintf(ficlog,"\n");
7460: fprintf(ficres,"\n");
7461: numlinepar++;
7462: } /* end k*/
7463: } /*end j */
7464: } /* end i */
7465: } /* end itimes */
7466:
7467: fflush(ficlog);
7468: fflush(ficres);
7469:
7470: while((c=getc(ficpar))=='#' && c!= EOF){
7471: ungetc(c,ficpar);
7472: fgets(line, MAXLINE, ficpar);
1.141 brouard 7473: fputs(line,stdout);
1.126 brouard 7474: fputs(line,ficparo);
7475: }
7476: ungetc(c,ficpar);
7477:
7478: estepm=0;
7479: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7480: if (estepm==0 || estepm < stepm) estepm=stepm;
7481: if (fage <= 2) {
7482: bage = ageminpar;
7483: fage = agemaxpar;
7484: }
7485:
7486: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7487: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7488: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7489:
7490: /* Other stuffs, more or less useful */
1.126 brouard 7491: while((c=getc(ficpar))=='#' && c!= EOF){
7492: ungetc(c,ficpar);
7493: fgets(line, MAXLINE, ficpar);
1.141 brouard 7494: fputs(line,stdout);
1.126 brouard 7495: fputs(line,ficparo);
7496: }
7497: ungetc(c,ficpar);
7498:
7499: 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);
7500: 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);
7501: 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);
7502: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7503: 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);
7504:
7505: while((c=getc(ficpar))=='#' && c!= EOF){
7506: ungetc(c,ficpar);
7507: fgets(line, MAXLINE, ficpar);
1.141 brouard 7508: fputs(line,stdout);
1.126 brouard 7509: fputs(line,ficparo);
7510: }
7511: ungetc(c,ficpar);
7512:
7513:
7514: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7515: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7516:
7517: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 7518: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 7519: fprintf(ficparo,"pop_based=%d\n",popbased);
7520: fprintf(ficres,"pop_based=%d\n",popbased);
7521:
7522: while((c=getc(ficpar))=='#' && c!= EOF){
7523: ungetc(c,ficpar);
7524: fgets(line, MAXLINE, ficpar);
1.141 brouard 7525: fputs(line,stdout);
1.126 brouard 7526: fputs(line,ficparo);
7527: }
7528: ungetc(c,ficpar);
7529:
7530: 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);
7531: 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);
7532: 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);
7533: 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);
7534: 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);
7535: /* day and month of proj2 are not used but only year anproj2.*/
7536:
7537:
7538:
1.145 brouard 7539: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7540: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7541:
7542: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7543: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
7544: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7545: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7546: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7547: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7548: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7549: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7550: }else
7551: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7552:
7553: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7554: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7555: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7556:
7557: /*------------ free_vector -------------*/
7558: /* chdir(path); */
7559:
7560: free_ivector(wav,1,imx);
7561: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7562: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7563: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7564: free_lvector(num,1,n);
7565: free_vector(agedc,1,n);
7566: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7567: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7568: fclose(ficparo);
7569: fclose(ficres);
7570:
7571:
1.186 brouard 7572: /* Other results (useful)*/
7573:
7574:
1.126 brouard 7575: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7576: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7577: prlim=matrix(1,nlstate,1,nlstate);
7578: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7579: fclose(ficrespl);
7580:
1.145 brouard 7581: #ifdef FREEEXIT2
7582: #include "freeexit2.h"
7583: #endif
7584:
1.126 brouard 7585: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7586: /*#include "hpijx.h"*/
7587: hPijx(p, bage, fage);
1.145 brouard 7588: fclose(ficrespij);
1.126 brouard 7589:
1.145 brouard 7590: /*-------------- Variance of one-step probabilities---*/
7591: k=1;
1.126 brouard 7592: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7593:
7594:
7595: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7596: for(i=1;i<=AGESUP;i++)
7597: for(j=1;j<=NCOVMAX;j++)
7598: for(k=1;k<=NCOVMAX;k++)
7599: probs[i][j][k]=0.;
7600:
7601: /*---------- Forecasting ------------------*/
7602: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7603: if(prevfcast==1){
7604: /* if(stepm ==1){*/
7605: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7606: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7607: /* } */
7608: /* else{ */
7609: /* erreur=108; */
7610: /* 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); */
7611: /* 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); */
7612: /* } */
7613: }
1.186 brouard 7614:
7615: /* ------ Other prevalence ratios------------ */
1.126 brouard 7616:
1.127 brouard 7617: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7618:
7619: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7620: /* 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",\
7621: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7622: */
1.126 brouard 7623:
1.127 brouard 7624: if (mobilav!=0) {
7625: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7626: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7627: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7628: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7629: }
1.126 brouard 7630: }
7631:
7632:
1.127 brouard 7633: /*---------- Health expectancies, no variances ------------*/
7634:
1.126 brouard 7635: strcpy(filerese,"e");
7636: strcat(filerese,fileres);
7637: if((ficreseij=fopen(filerese,"w"))==NULL) {
7638: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7639: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7640: }
7641: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7642: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7643: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7644: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7645:
7646: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7647: fprintf(ficreseij,"\n#****** ");
7648: for(j=1;j<=cptcoveff;j++) {
7649: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7650: }
7651: fprintf(ficreseij,"******\n");
7652:
7653: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7654: oldm=oldms;savm=savms;
7655: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7656:
7657: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7658: /*}*/
1.127 brouard 7659: }
7660: fclose(ficreseij);
7661:
7662:
7663: /*---------- Health expectancies and variances ------------*/
7664:
7665:
7666: strcpy(filerest,"t");
7667: strcat(filerest,fileres);
7668: if((ficrest=fopen(filerest,"w"))==NULL) {
7669: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7670: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7671: }
7672: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7673: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7674:
1.126 brouard 7675:
7676: strcpy(fileresstde,"stde");
7677: strcat(fileresstde,fileres);
7678: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7679: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7680: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7681: }
7682: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7683: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7684:
7685: strcpy(filerescve,"cve");
7686: strcat(filerescve,fileres);
7687: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7688: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7689: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7690: }
7691: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7692: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7693:
7694: strcpy(fileresv,"v");
7695: strcat(fileresv,fileres);
7696: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7697: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7698: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7699: }
7700: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7701: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7702:
1.145 brouard 7703: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7704: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7705:
7706: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7707: fprintf(ficrest,"\n#****** ");
1.126 brouard 7708: for(j=1;j<=cptcoveff;j++)
7709: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7710: fprintf(ficrest,"******\n");
7711:
7712: fprintf(ficresstdeij,"\n#****** ");
7713: fprintf(ficrescveij,"\n#****** ");
7714: for(j=1;j<=cptcoveff;j++) {
7715: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7716: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7717: }
7718: fprintf(ficresstdeij,"******\n");
7719: fprintf(ficrescveij,"******\n");
7720:
7721: fprintf(ficresvij,"\n#****** ");
7722: for(j=1;j<=cptcoveff;j++)
7723: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7724: fprintf(ficresvij,"******\n");
7725:
7726: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7727: oldm=oldms;savm=savms;
1.127 brouard 7728: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7729: /*
7730: */
7731: /* goto endfree; */
1.126 brouard 7732:
7733: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7734: pstamp(ficrest);
1.145 brouard 7735:
7736:
1.128 brouard 7737: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7738: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7739: cptcod= 0; /* To be deleted */
7740: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145 brouard 7741: 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 7742: if(vpopbased==1)
7743: 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);
7744: else
7745: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7746: fprintf(ficrest,"# Age e.. (std) ");
7747: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7748: fprintf(ficrest,"\n");
1.126 brouard 7749:
1.128 brouard 7750: epj=vector(1,nlstate+1);
7751: for(age=bage; age <=fage ;age++){
7752: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7753: if (vpopbased==1) {
7754: if(mobilav ==0){
7755: for(i=1; i<=nlstate;i++)
7756: prlim[i][i]=probs[(int)age][i][k];
7757: }else{ /* mobilav */
7758: for(i=1; i<=nlstate;i++)
7759: prlim[i][i]=mobaverage[(int)age][i][k];
7760: }
1.126 brouard 7761: }
7762:
1.128 brouard 7763: fprintf(ficrest," %4.0f",age);
7764: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7765: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7766: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7767: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7768: }
7769: epj[nlstate+1] +=epj[j];
1.126 brouard 7770: }
7771:
1.128 brouard 7772: for(i=1, vepp=0.;i <=nlstate;i++)
7773: for(j=1;j <=nlstate;j++)
7774: vepp += vareij[i][j][(int)age];
7775: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7776: for(j=1;j <=nlstate;j++){
7777: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7778: }
7779: fprintf(ficrest,"\n");
1.126 brouard 7780: }
7781: }
7782: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7783: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7784: free_vector(epj,1,nlstate+1);
1.145 brouard 7785: /*}*/
1.126 brouard 7786: }
7787: free_vector(weight,1,n);
1.145 brouard 7788: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7789: free_imatrix(s,1,maxwav+1,1,n);
7790: free_matrix(anint,1,maxwav,1,n);
7791: free_matrix(mint,1,maxwav,1,n);
7792: free_ivector(cod,1,n);
7793: free_ivector(tab,1,NCOVMAX);
7794: fclose(ficresstdeij);
7795: fclose(ficrescveij);
7796: fclose(ficresvij);
7797: fclose(ficrest);
7798: fclose(ficpar);
7799:
7800: /*------- Variance of period (stable) prevalence------*/
7801:
7802: strcpy(fileresvpl,"vpl");
7803: strcat(fileresvpl,fileres);
7804: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7805: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7806: exit(0);
7807: }
7808: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7809:
1.145 brouard 7810: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7811: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7812:
7813: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7814: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7815: for(j=1;j<=cptcoveff;j++)
7816: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7817: fprintf(ficresvpl,"******\n");
7818:
7819: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7820: oldm=oldms;savm=savms;
7821: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7822: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7823: /*}*/
1.126 brouard 7824: }
7825:
7826: fclose(ficresvpl);
7827:
7828: /*---------- End : free ----------------*/
7829: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7830: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7831: } /* mle==-3 arrives here for freeing */
1.164 brouard 7832: /* endfree:*/
1.141 brouard 7833: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7834: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7835: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7836: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7837: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7838: free_matrix(covar,0,NCOVMAX,1,n);
7839: free_matrix(matcov,1,npar,1,npar);
7840: /*free_vector(delti,1,npar);*/
7841: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7842: free_matrix(agev,1,maxwav,1,imx);
7843: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7844:
1.145 brouard 7845: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 7846: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 7847: free_ivector(Tvar,1,NCOVMAX);
7848: free_ivector(Tprod,1,NCOVMAX);
7849: free_ivector(Tvaraff,1,NCOVMAX);
7850: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7851:
7852: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7853: free_imatrix(codtab,1,100,1,10);
7854: fflush(fichtm);
7855: fflush(ficgp);
7856:
7857:
7858: if((nberr >0) || (nbwarn>0)){
7859: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7860: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7861: }else{
7862: printf("End of Imach\n");
7863: fprintf(ficlog,"End of Imach\n");
7864: }
7865: printf("See log file on %s\n",filelog);
7866: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7867: /*(void) gettimeofday(&end_time,&tzp);*/
7868: rend_time = time(NULL);
7869: end_time = *localtime(&rend_time);
7870: /* tml = *localtime(&end_time.tm_sec); */
7871: strcpy(strtend,asctime(&end_time));
1.126 brouard 7872: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7873: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7874: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7875:
1.157 brouard 7876: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7877: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7878: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7879: /* printf("Total time was %d uSec.\n", total_usecs);*/
7880: /* if(fileappend(fichtm,optionfilehtm)){ */
7881: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7882: fclose(fichtm);
7883: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7884: fclose(fichtmcov);
7885: fclose(ficgp);
7886: fclose(ficlog);
7887: /*------ End -----------*/
7888:
7889:
7890: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 7891: #ifdef WIN32
7892: if (_chdir(pathcd) != 0)
7893: printf("Can't move to directory %s!\n",path);
7894: if(_getcwd(pathcd,MAXLINE) > 0)
7895: #else
1.126 brouard 7896: if(chdir(pathcd) != 0)
1.184 brouard 7897: printf("Can't move to directory %s!\n", path);
7898: if (getcwd(pathcd, MAXLINE) > 0)
7899: #endif
1.126 brouard 7900: printf("Current directory %s!\n",pathcd);
7901: /*strcat(plotcmd,CHARSEPARATOR);*/
7902: sprintf(plotcmd,"gnuplot");
1.157 brouard 7903: #ifdef _WIN32
1.126 brouard 7904: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7905: #endif
7906: if(!stat(plotcmd,&info)){
1.158 brouard 7907: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7908: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7909: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7910: }else
7911: strcpy(pplotcmd,plotcmd);
1.157 brouard 7912: #ifdef __unix
1.126 brouard 7913: strcpy(plotcmd,GNUPLOTPROGRAM);
7914: if(!stat(plotcmd,&info)){
1.158 brouard 7915: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7916: }else
7917: strcpy(pplotcmd,plotcmd);
7918: #endif
7919: }else
7920: strcpy(pplotcmd,plotcmd);
7921:
7922: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7923: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7924:
7925: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7926: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7927: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7928: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7929: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7930: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7931: }
1.158 brouard 7932: printf(" Successful, please wait...");
1.126 brouard 7933: while (z[0] != 'q') {
7934: /* chdir(path); */
1.154 brouard 7935: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7936: scanf("%s",z);
7937: /* if (z[0] == 'c') system("./imach"); */
7938: if (z[0] == 'e') {
1.158 brouard 7939: #ifdef __APPLE__
1.152 brouard 7940: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7941: #elif __linux
7942: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7943: #else
1.152 brouard 7944: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7945: #endif
7946: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7947: system(pplotcmd);
1.126 brouard 7948: }
7949: else if (z[0] == 'g') system(plotcmd);
7950: else if (z[0] == 'q') exit(0);
7951: }
7952: end:
7953: while (z[0] != 'q') {
1.195 brouard 7954: printf("\nType q for exiting: "); fflush(stdout);
1.126 brouard 7955: scanf("%s",z);
7956: }
7957: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>