Annotation of imach/src/imach.c, revision 1.192
1.192 ! brouard 1: /* $Id: imach.c,v 1.191 2015/07/14 10:00:33 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.192 ! brouard 4: Revision 1.191 2015/07/14 10:00:33 brouard
! 5: Summary: Some fixes
! 6:
1.191 brouard 7: Revision 1.190 2015/05/05 08:51:13 brouard
8: Summary: Adding digits in output parameters (7 digits instead of 6)
9:
10: Fix 1+age+.
11:
1.190 brouard 12: Revision 1.189 2015/04/30 14:45:16 brouard
13: Summary: 0.98q2
14:
1.189 brouard 15: Revision 1.188 2015/04/30 08:27:53 brouard
16: *** empty log message ***
17:
1.188 brouard 18: Revision 1.187 2015/04/29 09:11:15 brouard
19: *** empty log message ***
20:
1.187 brouard 21: Revision 1.186 2015/04/23 12:01:52 brouard
22: Summary: V1*age is working now, version 0.98q1
23:
24: Some codes had been disabled in order to simplify and Vn*age was
25: working in the optimization phase, ie, giving correct MLE parameters,
26: but, as usual, outputs were not correct and program core dumped.
27:
1.186 brouard 28: Revision 1.185 2015/03/11 13:26:42 brouard
29: Summary: Inclusion of compile and links command line for Intel Compiler
30:
1.185 brouard 31: Revision 1.184 2015/03/11 11:52:39 brouard
32: Summary: Back from Windows 8. Intel Compiler
33:
1.184 brouard 34: Revision 1.183 2015/03/10 20:34:32 brouard
35: Summary: 0.98q0, trying with directest, mnbrak fixed
36:
37: We use directest instead of original Powell test; probably no
38: incidence on the results, but better justifications;
39: We fixed Numerical Recipes mnbrak routine which was wrong and gave
40: wrong results.
41:
1.183 brouard 42: Revision 1.182 2015/02/12 08:19:57 brouard
43: Summary: Trying to keep directest which seems simpler and more general
44: Author: Nicolas Brouard
45:
1.182 brouard 46: Revision 1.181 2015/02/11 23:22:24 brouard
47: Summary: Comments on Powell added
48:
49: Author:
50:
1.181 brouard 51: Revision 1.180 2015/02/11 17:33:45 brouard
52: Summary: Finishing move from main to function (hpijx and prevalence_limit)
53:
1.180 brouard 54: Revision 1.179 2015/01/04 09:57:06 brouard
55: Summary: back to OS/X
56:
1.179 brouard 57: Revision 1.178 2015/01/04 09:35:48 brouard
58: *** empty log message ***
59:
1.178 brouard 60: Revision 1.177 2015/01/03 18:40:56 brouard
61: Summary: Still testing ilc32 on OSX
62:
1.177 brouard 63: Revision 1.176 2015/01/03 16:45:04 brouard
64: *** empty log message ***
65:
1.176 brouard 66: Revision 1.175 2015/01/03 16:33:42 brouard
67: *** empty log message ***
68:
1.175 brouard 69: Revision 1.174 2015/01/03 16:15:49 brouard
70: Summary: Still in cross-compilation
71:
1.174 brouard 72: Revision 1.173 2015/01/03 12:06:26 brouard
73: Summary: trying to detect cross-compilation
74:
1.173 brouard 75: Revision 1.172 2014/12/27 12:07:47 brouard
76: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
77:
1.172 brouard 78: Revision 1.171 2014/12/23 13:26:59 brouard
79: Summary: Back from Visual C
80:
81: Still problem with utsname.h on Windows
82:
1.171 brouard 83: Revision 1.170 2014/12/23 11:17:12 brouard
84: Summary: Cleaning some \%% back to %%
85:
86: The escape was mandatory for a specific compiler (which one?), but too many warnings.
87:
1.170 brouard 88: Revision 1.169 2014/12/22 23:08:31 brouard
89: Summary: 0.98p
90:
91: Outputs some informations on compiler used, OS etc. Testing on different platforms.
92:
1.169 brouard 93: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 94: Summary: update
1.169 brouard 95:
1.168 brouard 96: Revision 1.167 2014/12/22 13:50:56 brouard
97: Summary: Testing uname and compiler version and if compiled 32 or 64
98:
99: Testing on Linux 64
100:
1.167 brouard 101: Revision 1.166 2014/12/22 11:40:47 brouard
102: *** empty log message ***
103:
1.166 brouard 104: Revision 1.165 2014/12/16 11:20:36 brouard
105: Summary: After compiling on Visual C
106:
107: * imach.c (Module): Merging 1.61 to 1.162
108:
1.165 brouard 109: Revision 1.164 2014/12/16 10:52:11 brouard
110: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
111:
112: * imach.c (Module): Merging 1.61 to 1.162
113:
1.164 brouard 114: Revision 1.163 2014/12/16 10:30:11 brouard
115: * imach.c (Module): Merging 1.61 to 1.162
116:
1.163 brouard 117: Revision 1.162 2014/09/25 11:43:39 brouard
118: Summary: temporary backup 0.99!
119:
1.162 brouard 120: Revision 1.1 2014/09/16 11:06:58 brouard
121: Summary: With some code (wrong) for nlopt
122:
123: Author:
124:
125: Revision 1.161 2014/09/15 20:41:41 brouard
126: Summary: Problem with macro SQR on Intel compiler
127:
1.161 brouard 128: Revision 1.160 2014/09/02 09:24:05 brouard
129: *** empty log message ***
130:
1.160 brouard 131: Revision 1.159 2014/09/01 10:34:10 brouard
132: Summary: WIN32
133: Author: Brouard
134:
1.159 brouard 135: Revision 1.158 2014/08/27 17:11:51 brouard
136: *** empty log message ***
137:
1.158 brouard 138: Revision 1.157 2014/08/27 16:26:55 brouard
139: Summary: Preparing windows Visual studio version
140: Author: Brouard
141:
142: In order to compile on Visual studio, time.h is now correct and time_t
143: and tm struct should be used. difftime should be used but sometimes I
144: just make the differences in raw time format (time(&now).
145: Trying to suppress #ifdef LINUX
146: Add xdg-open for __linux in order to open default browser.
147:
1.157 brouard 148: Revision 1.156 2014/08/25 20:10:10 brouard
149: *** empty log message ***
150:
1.156 brouard 151: Revision 1.155 2014/08/25 18:32:34 brouard
152: Summary: New compile, minor changes
153: Author: Brouard
154:
1.155 brouard 155: Revision 1.154 2014/06/20 17:32:08 brouard
156: Summary: Outputs now all graphs of convergence to period prevalence
157:
1.154 brouard 158: Revision 1.153 2014/06/20 16:45:46 brouard
159: Summary: If 3 live state, convergence to period prevalence on same graph
160: Author: Brouard
161:
1.153 brouard 162: Revision 1.152 2014/06/18 17:54:09 brouard
163: Summary: open browser, use gnuplot on same dir than imach if not found in the path
164:
1.152 brouard 165: Revision 1.151 2014/06/18 16:43:30 brouard
166: *** empty log message ***
167:
1.151 brouard 168: Revision 1.150 2014/06/18 16:42:35 brouard
169: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
170: Author: brouard
171:
1.150 brouard 172: Revision 1.149 2014/06/18 15:51:14 brouard
173: Summary: Some fixes in parameter files errors
174: Author: Nicolas Brouard
175:
1.149 brouard 176: Revision 1.148 2014/06/17 17:38:48 brouard
177: Summary: Nothing new
178: Author: Brouard
179:
180: Just a new packaging for OS/X version 0.98nS
181:
1.148 brouard 182: Revision 1.147 2014/06/16 10:33:11 brouard
183: *** empty log message ***
184:
1.147 brouard 185: Revision 1.146 2014/06/16 10:20:28 brouard
186: Summary: Merge
187: Author: Brouard
188:
189: Merge, before building revised version.
190:
1.146 brouard 191: Revision 1.145 2014/06/10 21:23:15 brouard
192: Summary: Debugging with valgrind
193: Author: Nicolas Brouard
194:
195: Lot of changes in order to output the results with some covariates
196: After the Edimburgh REVES conference 2014, it seems mandatory to
197: improve the code.
198: No more memory valgrind error but a lot has to be done in order to
199: continue the work of splitting the code into subroutines.
200: Also, decodemodel has been improved. Tricode is still not
201: optimal. nbcode should be improved. Documentation has been added in
202: the source code.
203:
1.144 brouard 204: Revision 1.143 2014/01/26 09:45:38 brouard
205: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
206:
207: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
208: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
209:
1.143 brouard 210: Revision 1.142 2014/01/26 03:57:36 brouard
211: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
212:
213: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
214:
1.142 brouard 215: Revision 1.141 2014/01/26 02:42:01 brouard
216: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
217:
1.141 brouard 218: Revision 1.140 2011/09/02 10:37:54 brouard
219: Summary: times.h is ok with mingw32 now.
220:
1.140 brouard 221: Revision 1.139 2010/06/14 07:50:17 brouard
222: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
223: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
224:
1.139 brouard 225: Revision 1.138 2010/04/30 18:19:40 brouard
226: *** empty log message ***
227:
1.138 brouard 228: Revision 1.137 2010/04/29 18:11:38 brouard
229: (Module): Checking covariates for more complex models
230: than V1+V2. A lot of change to be done. Unstable.
231:
1.137 brouard 232: Revision 1.136 2010/04/26 20:30:53 brouard
233: (Module): merging some libgsl code. Fixing computation
234: of likelione (using inter/intrapolation if mle = 0) in order to
235: get same likelihood as if mle=1.
236: Some cleaning of code and comments added.
237:
1.136 brouard 238: Revision 1.135 2009/10/29 15:33:14 brouard
239: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
240:
1.135 brouard 241: Revision 1.134 2009/10/29 13:18:53 brouard
242: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
243:
1.134 brouard 244: Revision 1.133 2009/07/06 10:21:25 brouard
245: just nforces
246:
1.133 brouard 247: Revision 1.132 2009/07/06 08:22:05 brouard
248: Many tings
249:
1.132 brouard 250: Revision 1.131 2009/06/20 16:22:47 brouard
251: Some dimensions resccaled
252:
1.131 brouard 253: Revision 1.130 2009/05/26 06:44:34 brouard
254: (Module): Max Covariate is now set to 20 instead of 8. A
255: lot of cleaning with variables initialized to 0. Trying to make
256: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
257:
1.130 brouard 258: Revision 1.129 2007/08/31 13:49:27 lievre
259: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
260:
1.129 lievre 261: Revision 1.128 2006/06/30 13:02:05 brouard
262: (Module): Clarifications on computing e.j
263:
1.128 brouard 264: Revision 1.127 2006/04/28 18:11:50 brouard
265: (Module): Yes the sum of survivors was wrong since
266: imach-114 because nhstepm was no more computed in the age
267: loop. Now we define nhstepma in the age loop.
268: (Module): In order to speed up (in case of numerous covariates) we
269: compute health expectancies (without variances) in a first step
270: and then all the health expectancies with variances or standard
271: deviation (needs data from the Hessian matrices) which slows the
272: computation.
273: In the future we should be able to stop the program is only health
274: expectancies and graph are needed without standard deviations.
275:
1.127 brouard 276: Revision 1.126 2006/04/28 17:23:28 brouard
277: (Module): Yes the sum of survivors was wrong since
278: imach-114 because nhstepm was no more computed in the age
279: loop. Now we define nhstepma in the age loop.
280: Version 0.98h
281:
1.126 brouard 282: Revision 1.125 2006/04/04 15:20:31 lievre
283: Errors in calculation of health expectancies. Age was not initialized.
284: Forecasting file added.
285:
286: Revision 1.124 2006/03/22 17:13:53 lievre
287: Parameters are printed with %lf instead of %f (more numbers after the comma).
288: The log-likelihood is printed in the log file
289:
290: Revision 1.123 2006/03/20 10:52:43 brouard
291: * imach.c (Module): <title> changed, corresponds to .htm file
292: name. <head> headers where missing.
293:
294: * imach.c (Module): Weights can have a decimal point as for
295: English (a comma might work with a correct LC_NUMERIC environment,
296: otherwise the weight is truncated).
297: Modification of warning when the covariates values are not 0 or
298: 1.
299: Version 0.98g
300:
301: Revision 1.122 2006/03/20 09:45:41 brouard
302: (Module): Weights can have a decimal point as for
303: English (a comma might work with a correct LC_NUMERIC environment,
304: otherwise the weight is truncated).
305: Modification of warning when the covariates values are not 0 or
306: 1.
307: Version 0.98g
308:
309: Revision 1.121 2006/03/16 17:45:01 lievre
310: * imach.c (Module): Comments concerning covariates added
311:
312: * imach.c (Module): refinements in the computation of lli if
313: status=-2 in order to have more reliable computation if stepm is
314: not 1 month. Version 0.98f
315:
316: Revision 1.120 2006/03/16 15:10:38 lievre
317: (Module): refinements in the computation of lli if
318: status=-2 in order to have more reliable computation if stepm is
319: not 1 month. Version 0.98f
320:
321: Revision 1.119 2006/03/15 17:42:26 brouard
322: (Module): Bug if status = -2, the loglikelihood was
323: computed as likelihood omitting the logarithm. Version O.98e
324:
325: Revision 1.118 2006/03/14 18:20:07 brouard
326: (Module): varevsij Comments added explaining the second
327: table of variances if popbased=1 .
328: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
329: (Module): Function pstamp added
330: (Module): Version 0.98d
331:
332: Revision 1.117 2006/03/14 17:16:22 brouard
333: (Module): varevsij Comments added explaining the second
334: table of variances if popbased=1 .
335: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
336: (Module): Function pstamp added
337: (Module): Version 0.98d
338:
339: Revision 1.116 2006/03/06 10:29:27 brouard
340: (Module): Variance-covariance wrong links and
341: varian-covariance of ej. is needed (Saito).
342:
343: Revision 1.115 2006/02/27 12:17:45 brouard
344: (Module): One freematrix added in mlikeli! 0.98c
345:
346: Revision 1.114 2006/02/26 12:57:58 brouard
347: (Module): Some improvements in processing parameter
348: filename with strsep.
349:
350: Revision 1.113 2006/02/24 14:20:24 brouard
351: (Module): Memory leaks checks with valgrind and:
352: datafile was not closed, some imatrix were not freed and on matrix
353: allocation too.
354:
355: Revision 1.112 2006/01/30 09:55:26 brouard
356: (Module): Back to gnuplot.exe instead of wgnuplot.exe
357:
358: Revision 1.111 2006/01/25 20:38:18 brouard
359: (Module): Lots of cleaning and bugs added (Gompertz)
360: (Module): Comments can be added in data file. Missing date values
361: can be a simple dot '.'.
362:
363: Revision 1.110 2006/01/25 00:51:50 brouard
364: (Module): Lots of cleaning and bugs added (Gompertz)
365:
366: Revision 1.109 2006/01/24 19:37:15 brouard
367: (Module): Comments (lines starting with a #) are allowed in data.
368:
369: Revision 1.108 2006/01/19 18:05:42 lievre
370: Gnuplot problem appeared...
371: To be fixed
372:
373: Revision 1.107 2006/01/19 16:20:37 brouard
374: Test existence of gnuplot in imach path
375:
376: Revision 1.106 2006/01/19 13:24:36 brouard
377: Some cleaning and links added in html output
378:
379: Revision 1.105 2006/01/05 20:23:19 lievre
380: *** empty log message ***
381:
382: Revision 1.104 2005/09/30 16:11:43 lievre
383: (Module): sump fixed, loop imx fixed, and simplifications.
384: (Module): If the status is missing at the last wave but we know
385: that the person is alive, then we can code his/her status as -2
386: (instead of missing=-1 in earlier versions) and his/her
387: contributions to the likelihood is 1 - Prob of dying from last
388: health status (= 1-p13= p11+p12 in the easiest case of somebody in
389: the healthy state at last known wave). Version is 0.98
390:
391: Revision 1.103 2005/09/30 15:54:49 lievre
392: (Module): sump fixed, loop imx fixed, and simplifications.
393:
394: Revision 1.102 2004/09/15 17:31:30 brouard
395: Add the possibility to read data file including tab characters.
396:
397: Revision 1.101 2004/09/15 10:38:38 brouard
398: Fix on curr_time
399:
400: Revision 1.100 2004/07/12 18:29:06 brouard
401: Add version for Mac OS X. Just define UNIX in Makefile
402:
403: Revision 1.99 2004/06/05 08:57:40 brouard
404: *** empty log message ***
405:
406: Revision 1.98 2004/05/16 15:05:56 brouard
407: New version 0.97 . First attempt to estimate force of mortality
408: directly from the data i.e. without the need of knowing the health
409: state at each age, but using a Gompertz model: log u =a + b*age .
410: This is the basic analysis of mortality and should be done before any
411: other analysis, in order to test if the mortality estimated from the
412: cross-longitudinal survey is different from the mortality estimated
413: from other sources like vital statistic data.
414:
415: The same imach parameter file can be used but the option for mle should be -3.
416:
1.133 brouard 417: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 418: former routines in order to include the new code within the former code.
419:
420: The output is very simple: only an estimate of the intercept and of
421: the slope with 95% confident intervals.
422:
423: Current limitations:
424: A) Even if you enter covariates, i.e. with the
425: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
426: B) There is no computation of Life Expectancy nor Life Table.
427:
428: Revision 1.97 2004/02/20 13:25:42 lievre
429: Version 0.96d. Population forecasting command line is (temporarily)
430: suppressed.
431:
432: Revision 1.96 2003/07/15 15:38:55 brouard
433: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
434: rewritten within the same printf. Workaround: many printfs.
435:
436: Revision 1.95 2003/07/08 07:54:34 brouard
437: * imach.c (Repository):
438: (Repository): Using imachwizard code to output a more meaningful covariance
439: matrix (cov(a12,c31) instead of numbers.
440:
441: Revision 1.94 2003/06/27 13:00:02 brouard
442: Just cleaning
443:
444: Revision 1.93 2003/06/25 16:33:55 brouard
445: (Module): On windows (cygwin) function asctime_r doesn't
446: exist so I changed back to asctime which exists.
447: (Module): Version 0.96b
448:
449: Revision 1.92 2003/06/25 16:30:45 brouard
450: (Module): On windows (cygwin) function asctime_r doesn't
451: exist so I changed back to asctime which exists.
452:
453: Revision 1.91 2003/06/25 15:30:29 brouard
454: * imach.c (Repository): Duplicated warning errors corrected.
455: (Repository): Elapsed time after each iteration is now output. It
456: helps to forecast when convergence will be reached. Elapsed time
457: is stamped in powell. We created a new html file for the graphs
458: concerning matrix of covariance. It has extension -cov.htm.
459:
460: Revision 1.90 2003/06/24 12:34:15 brouard
461: (Module): Some bugs corrected for windows. Also, when
462: mle=-1 a template is output in file "or"mypar.txt with the design
463: of the covariance matrix to be input.
464:
465: Revision 1.89 2003/06/24 12:30:52 brouard
466: (Module): Some bugs corrected for windows. Also, when
467: mle=-1 a template is output in file "or"mypar.txt with the design
468: of the covariance matrix to be input.
469:
470: Revision 1.88 2003/06/23 17:54:56 brouard
471: * 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.
472:
473: Revision 1.87 2003/06/18 12:26:01 brouard
474: Version 0.96
475:
476: Revision 1.86 2003/06/17 20:04:08 brouard
477: (Module): Change position of html and gnuplot routines and added
478: routine fileappend.
479:
480: Revision 1.85 2003/06/17 13:12:43 brouard
481: * imach.c (Repository): Check when date of death was earlier that
482: current date of interview. It may happen when the death was just
483: prior to the death. In this case, dh was negative and likelihood
484: was wrong (infinity). We still send an "Error" but patch by
485: assuming that the date of death was just one stepm after the
486: interview.
487: (Repository): Because some people have very long ID (first column)
488: we changed int to long in num[] and we added a new lvector for
489: memory allocation. But we also truncated to 8 characters (left
490: truncation)
491: (Repository): No more line truncation errors.
492:
493: Revision 1.84 2003/06/13 21:44:43 brouard
494: * imach.c (Repository): Replace "freqsummary" at a correct
495: place. It differs from routine "prevalence" which may be called
496: many times. Probs is memory consuming and must be used with
497: parcimony.
498: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
499:
500: Revision 1.83 2003/06/10 13:39:11 lievre
501: *** empty log message ***
502:
503: Revision 1.82 2003/06/05 15:57:20 brouard
504: Add log in imach.c and fullversion number is now printed.
505:
506: */
507: /*
508: Interpolated Markov Chain
509:
510: Short summary of the programme:
511:
512: This program computes Healthy Life Expectancies from
513: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
514: first survey ("cross") where individuals from different ages are
515: interviewed on their health status or degree of disability (in the
516: case of a health survey which is our main interest) -2- at least a
517: second wave of interviews ("longitudinal") which measure each change
518: (if any) in individual health status. Health expectancies are
519: computed from the time spent in each health state according to a
520: model. More health states you consider, more time is necessary to reach the
521: Maximum Likelihood of the parameters involved in the model. The
522: simplest model is the multinomial logistic model where pij is the
523: probability to be observed in state j at the second wave
524: conditional to be observed in state i at the first wave. Therefore
525: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
526: 'age' is age and 'sex' is a covariate. If you want to have a more
527: complex model than "constant and age", you should modify the program
528: where the markup *Covariates have to be included here again* invites
529: you to do it. More covariates you add, slower the
530: convergence.
531:
532: The advantage of this computer programme, compared to a simple
533: multinomial logistic model, is clear when the delay between waves is not
534: identical for each individual. Also, if a individual missed an
535: intermediate interview, the information is lost, but taken into
536: account using an interpolation or extrapolation.
537:
538: hPijx is the probability to be observed in state i at age x+h
539: conditional to the observed state i at age x. The delay 'h' can be
540: split into an exact number (nh*stepm) of unobserved intermediate
541: states. This elementary transition (by month, quarter,
542: semester or year) is modelled as a multinomial logistic. The hPx
543: matrix is simply the matrix product of nh*stepm elementary matrices
544: and the contribution of each individual to the likelihood is simply
545: hPijx.
546:
547: Also this programme outputs the covariance matrix of the parameters but also
548: of the life expectancies. It also computes the period (stable) prevalence.
549:
1.133 brouard 550: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
551: Institut national d'études démographiques, Paris.
1.126 brouard 552: This software have been partly granted by Euro-REVES, a concerted action
553: from the European Union.
554: It is copyrighted identically to a GNU software product, ie programme and
555: software can be distributed freely for non commercial use. Latest version
556: can be accessed at http://euroreves.ined.fr/imach .
557:
558: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
559: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
560:
561: **********************************************************************/
562: /*
563: main
564: read parameterfile
565: read datafile
566: concatwav
567: freqsummary
568: if (mle >= 1)
569: mlikeli
570: print results files
571: if mle==1
572: computes hessian
573: read end of parameter file: agemin, agemax, bage, fage, estepm
574: begin-prev-date,...
575: open gnuplot file
576: open html file
1.145 brouard 577: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
578: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
579: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
580: freexexit2 possible for memory heap.
581:
582: h Pij x | pij_nom ficrestpij
583: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
584: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
585: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
586:
587: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
588: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
589: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
590: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
591: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
592:
1.126 brouard 593: forecasting if prevfcast==1 prevforecast call prevalence()
594: health expectancies
595: Variance-covariance of DFLE
596: prevalence()
597: movingaverage()
598: varevsij()
599: if popbased==1 varevsij(,popbased)
600: total life expectancies
601: Variance of period (stable) prevalence
602: end
603: */
604:
1.187 brouard 605: /* #define DEBUG */
606: /* #define DEBUGBRENT */
1.165 brouard 607: #define POWELL /* Instead of NLOPT */
1.192 ! brouard 608: #define POWELLF1F3 /* Skip test */
1.186 brouard 609: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
610: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 611:
612: #include <math.h>
613: #include <stdio.h>
614: #include <stdlib.h>
615: #include <string.h>
1.159 brouard 616:
617: #ifdef _WIN32
618: #include <io.h>
1.172 brouard 619: #include <windows.h>
620: #include <tchar.h>
1.159 brouard 621: #else
1.126 brouard 622: #include <unistd.h>
1.159 brouard 623: #endif
1.126 brouard 624:
625: #include <limits.h>
626: #include <sys/types.h>
1.171 brouard 627:
628: #if defined(__GNUC__)
629: #include <sys/utsname.h> /* Doesn't work on Windows */
630: #endif
631:
1.126 brouard 632: #include <sys/stat.h>
633: #include <errno.h>
1.159 brouard 634: /* extern int errno; */
1.126 brouard 635:
1.157 brouard 636: /* #ifdef LINUX */
637: /* #include <time.h> */
638: /* #include "timeval.h" */
639: /* #else */
640: /* #include <sys/time.h> */
641: /* #endif */
642:
1.126 brouard 643: #include <time.h>
644:
1.136 brouard 645: #ifdef GSL
646: #include <gsl/gsl_errno.h>
647: #include <gsl/gsl_multimin.h>
648: #endif
649:
1.167 brouard 650:
1.162 brouard 651: #ifdef NLOPT
652: #include <nlopt.h>
653: typedef struct {
654: double (* function)(double [] );
655: } myfunc_data ;
656: #endif
657:
1.126 brouard 658: /* #include <libintl.h> */
659: /* #define _(String) gettext (String) */
660:
1.141 brouard 661: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 662:
663: #define GNUPLOTPROGRAM "gnuplot"
664: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
665: #define FILENAMELENGTH 132
666:
667: #define GLOCK_ERROR_NOPATH -1 /* empty path */
668: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
669:
1.144 brouard 670: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
671: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 672:
673: #define NINTERVMAX 8
1.144 brouard 674: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
675: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
676: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 677: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 678: #define MAXN 20000
1.144 brouard 679: #define YEARM 12. /**< Number of months per year */
1.126 brouard 680: #define AGESUP 130
681: #define AGEBASE 40
1.164 brouard 682: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 683: #ifdef _WIN32
684: #define DIRSEPARATOR '\\'
685: #define CHARSEPARATOR "\\"
686: #define ODIRSEPARATOR '/'
687: #else
1.126 brouard 688: #define DIRSEPARATOR '/'
689: #define CHARSEPARATOR "/"
690: #define ODIRSEPARATOR '\\'
691: #endif
692:
1.192 ! brouard 693: /* $Id: imach.c,v 1.191 2015/07/14 10:00:33 brouard Exp $ */
1.126 brouard 694: /* $State: Exp $ */
695:
1.192 ! brouard 696: char version[]="Imach version 0.98q3, July 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
! 697: char fullversion[]="$Revision: 1.191 $ $Date: 2015/07/14 10:00:33 $";
1.126 brouard 698: char strstart[80];
699: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 700: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 701: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 702: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
703: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
704: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
705: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
706: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
707: int cptcovprodnoage=0; /**< Number of covariate products without age */
708: int cptcoveff=0; /* Total number of covariates to vary for printing results */
709: int cptcov=0; /* Working variable */
1.126 brouard 710: int npar=NPARMAX;
711: int nlstate=2; /* Number of live states */
712: int ndeath=1; /* Number of dead states */
1.130 brouard 713: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 714: int popbased=0;
715:
716: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 717: int maxwav=0; /* Maxim number of waves */
718: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
719: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
720: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 721: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 722: int mle=1, weightopt=0;
1.126 brouard 723: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
724: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
725: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
726: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 727: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 728: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 729: double **matprod2(); /* test */
1.126 brouard 730: double **oldm, **newm, **savm; /* Working pointers to matrices */
731: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 732: /*FILE *fic ; */ /* Used in readdata only */
733: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 734: FILE *ficlog, *ficrespow;
1.130 brouard 735: int globpr=0; /* Global variable for printing or not */
1.126 brouard 736: double fretone; /* Only one call to likelihood */
1.130 brouard 737: long ipmx=0; /* Number of contributions */
1.126 brouard 738: double sw; /* Sum of weights */
739: char filerespow[FILENAMELENGTH];
740: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
741: FILE *ficresilk;
742: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
743: FILE *ficresprobmorprev;
744: FILE *fichtm, *fichtmcov; /* Html File */
745: FILE *ficreseij;
746: char filerese[FILENAMELENGTH];
747: FILE *ficresstdeij;
748: char fileresstde[FILENAMELENGTH];
749: FILE *ficrescveij;
750: char filerescve[FILENAMELENGTH];
751: FILE *ficresvij;
752: char fileresv[FILENAMELENGTH];
753: FILE *ficresvpl;
754: char fileresvpl[FILENAMELENGTH];
755: char title[MAXLINE];
756: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
757: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
758: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
759: char command[FILENAMELENGTH];
760: int outcmd=0;
761:
762: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
763:
764: char filelog[FILENAMELENGTH]; /* Log file */
765: char filerest[FILENAMELENGTH];
766: char fileregp[FILENAMELENGTH];
767: char popfile[FILENAMELENGTH];
768:
769: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
770:
1.157 brouard 771: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
772: /* struct timezone tzp; */
773: /* extern int gettimeofday(); */
774: struct tm tml, *gmtime(), *localtime();
775:
776: extern time_t time();
777:
778: struct tm start_time, end_time, curr_time, last_time, forecast_time;
779: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
780: struct tm tm;
781:
1.126 brouard 782: char strcurr[80], strfor[80];
783:
784: char *endptr;
785: long lval;
786: double dval;
787:
788: #define NR_END 1
789: #define FREE_ARG char*
790: #define FTOL 1.0e-10
791:
792: #define NRANSI
793: #define ITMAX 200
794:
795: #define TOL 2.0e-4
796:
797: #define CGOLD 0.3819660
798: #define ZEPS 1.0e-10
799: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
800:
801: #define GOLD 1.618034
802: #define GLIMIT 100.0
803: #define TINY 1.0e-20
804:
805: static double maxarg1,maxarg2;
806: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
807: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
808:
809: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
810: #define rint(a) floor(a+0.5)
1.166 brouard 811: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 812: #define mytinydouble 1.0e-16
1.166 brouard 813: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
814: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
815: /* static double dsqrarg; */
816: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 817: static double sqrarg;
818: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
819: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
820: int agegomp= AGEGOMP;
821:
822: int imx;
823: int stepm=1;
824: /* Stepm, step in month: minimum step interpolation*/
825:
826: int estepm;
827: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
828:
829: int m,nb;
830: long *num;
1.192 ! brouard 831: int firstpass=0, lastpass=4,*cod, *Tage,*cens;
! 832: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
! 833: covariate for which somebody answered excluding
! 834: undefined. Usually 2: 0 and 1. */
! 835: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
! 836: covariate for which somebody answered including
! 837: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 838: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
839: double **pmmij, ***probs;
840: double *ageexmed,*agecens;
841: double dateintmean=0;
842:
843: double *weight;
844: int **s; /* Status */
1.141 brouard 845: double *agedc;
1.145 brouard 846: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 847: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 848: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 849: double idx;
850: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 851: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 852: int **codtab; /**< codtab=imatrix(1,100,1,10); */
853: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 854: double *lsurv, *lpop, *tpop;
855:
1.143 brouard 856: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
857: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 858:
859: /**************** split *************************/
860: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
861: {
862: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
863: the name of the file (name), its extension only (ext) and its first part of the name (finame)
864: */
865: char *ss; /* pointer */
1.186 brouard 866: int l1=0, l2=0; /* length counters */
1.126 brouard 867:
868: l1 = strlen(path ); /* length of path */
869: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
870: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
871: if ( ss == NULL ) { /* no directory, so determine current directory */
872: strcpy( name, path ); /* we got the fullname name because no directory */
873: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
874: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
875: /* get current working directory */
876: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 877: #ifdef WIN32
878: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
879: #else
880: if (getcwd(dirc, FILENAME_MAX) == NULL) {
881: #endif
1.126 brouard 882: return( GLOCK_ERROR_GETCWD );
883: }
884: /* got dirc from getcwd*/
885: printf(" DIRC = %s \n",dirc);
886: } else { /* strip direcotry from path */
887: ss++; /* after this, the filename */
888: l2 = strlen( ss ); /* length of filename */
889: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
890: strcpy( name, ss ); /* save file name */
891: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 892: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 893: printf(" DIRC2 = %s \n",dirc);
894: }
895: /* We add a separator at the end of dirc if not exists */
896: l1 = strlen( dirc ); /* length of directory */
897: if( dirc[l1-1] != DIRSEPARATOR ){
898: dirc[l1] = DIRSEPARATOR;
899: dirc[l1+1] = 0;
900: printf(" DIRC3 = %s \n",dirc);
901: }
902: ss = strrchr( name, '.' ); /* find last / */
903: if (ss >0){
904: ss++;
905: strcpy(ext,ss); /* save extension */
906: l1= strlen( name);
907: l2= strlen(ss)+1;
908: strncpy( finame, name, l1-l2);
909: finame[l1-l2]= 0;
910: }
911:
912: return( 0 ); /* we're done */
913: }
914:
915:
916: /******************************************/
917:
918: void replace_back_to_slash(char *s, char*t)
919: {
920: int i;
921: int lg=0;
922: i=0;
923: lg=strlen(t);
924: for(i=0; i<= lg; i++) {
925: (s[i] = t[i]);
926: if (t[i]== '\\') s[i]='/';
927: }
928: }
929:
1.132 brouard 930: char *trimbb(char *out, char *in)
1.137 brouard 931: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 932: char *s;
933: s=out;
934: while (*in != '\0'){
1.137 brouard 935: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 936: in++;
937: }
938: *out++ = *in++;
939: }
940: *out='\0';
941: return s;
942: }
943:
1.187 brouard 944: /* char *substrchaine(char *out, char *in, char *chain) */
945: /* { */
946: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
947: /* char *s, *t; */
948: /* t=in;s=out; */
949: /* while ((*in != *chain) && (*in != '\0')){ */
950: /* *out++ = *in++; */
951: /* } */
952:
953: /* /\* *in matches *chain *\/ */
954: /* while ((*in++ == *chain++) && (*in != '\0')){ */
955: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
956: /* } */
957: /* in--; chain--; */
958: /* while ( (*in != '\0')){ */
959: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
960: /* *out++ = *in++; */
961: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
962: /* } */
963: /* *out='\0'; */
964: /* out=s; */
965: /* return out; */
966: /* } */
967: char *substrchaine(char *out, char *in, char *chain)
968: {
969: /* Substract chain 'chain' from 'in', return and output 'out' */
970: /* in="V1+V1*age+age*age+V2", chain="age*age" */
971:
972: char *strloc;
973:
974: strcpy (out, in);
975: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
976: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
977: if(strloc != NULL){
978: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
979: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
980: /* strcpy (strloc, strloc +strlen(chain));*/
981: }
982: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
983: return out;
984: }
985:
986:
1.145 brouard 987: char *cutl(char *blocc, char *alocc, char *in, char occ)
988: {
1.187 brouard 989: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 990: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 991: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 992: If occ is not found blocc is null and alocc is equal to in. Returns blocc
993: */
1.160 brouard 994: char *s, *t;
1.145 brouard 995: t=in;s=in;
996: while ((*in != occ) && (*in != '\0')){
997: *alocc++ = *in++;
998: }
999: if( *in == occ){
1000: *(alocc)='\0';
1001: s=++in;
1002: }
1003:
1004: if (s == t) {/* occ not found */
1005: *(alocc-(in-s))='\0';
1006: in=s;
1007: }
1008: while ( *in != '\0'){
1009: *blocc++ = *in++;
1010: }
1011:
1012: *blocc='\0';
1013: return t;
1014: }
1.137 brouard 1015: char *cutv(char *blocc, char *alocc, char *in, char occ)
1016: {
1.187 brouard 1017: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1018: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1019: gives blocc="abcdef2ghi" and alocc="j".
1020: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1021: */
1022: char *s, *t;
1023: t=in;s=in;
1024: while (*in != '\0'){
1025: while( *in == occ){
1026: *blocc++ = *in++;
1027: s=in;
1028: }
1029: *blocc++ = *in++;
1030: }
1031: if (s == t) /* occ not found */
1032: *(blocc-(in-s))='\0';
1033: else
1034: *(blocc-(in-s)-1)='\0';
1035: in=s;
1036: while ( *in != '\0'){
1037: *alocc++ = *in++;
1038: }
1039:
1040: *alocc='\0';
1041: return s;
1042: }
1043:
1.126 brouard 1044: int nbocc(char *s, char occ)
1045: {
1046: int i,j=0;
1047: int lg=20;
1048: i=0;
1049: lg=strlen(s);
1050: for(i=0; i<= lg; i++) {
1051: if (s[i] == occ ) j++;
1052: }
1053: return j;
1054: }
1055:
1.137 brouard 1056: /* void cutv(char *u,char *v, char*t, char occ) */
1057: /* { */
1058: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1059: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1060: /* gives u="abcdef2ghi" and v="j" *\/ */
1061: /* int i,lg,j,p=0; */
1062: /* i=0; */
1063: /* lg=strlen(t); */
1064: /* for(j=0; j<=lg-1; j++) { */
1065: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1066: /* } */
1.126 brouard 1067:
1.137 brouard 1068: /* for(j=0; j<p; j++) { */
1069: /* (u[j] = t[j]); */
1070: /* } */
1071: /* u[p]='\0'; */
1.126 brouard 1072:
1.137 brouard 1073: /* for(j=0; j<= lg; j++) { */
1074: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1075: /* } */
1076: /* } */
1.126 brouard 1077:
1.160 brouard 1078: #ifdef _WIN32
1079: char * strsep(char **pp, const char *delim)
1080: {
1081: char *p, *q;
1082:
1083: if ((p = *pp) == NULL)
1084: return 0;
1085: if ((q = strpbrk (p, delim)) != NULL)
1086: {
1087: *pp = q + 1;
1088: *q = '\0';
1089: }
1090: else
1091: *pp = 0;
1092: return p;
1093: }
1094: #endif
1095:
1.126 brouard 1096: /********************** nrerror ********************/
1097:
1098: void nrerror(char error_text[])
1099: {
1100: fprintf(stderr,"ERREUR ...\n");
1101: fprintf(stderr,"%s\n",error_text);
1102: exit(EXIT_FAILURE);
1103: }
1104: /*********************** vector *******************/
1105: double *vector(int nl, int nh)
1106: {
1107: double *v;
1108: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1109: if (!v) nrerror("allocation failure in vector");
1110: return v-nl+NR_END;
1111: }
1112:
1113: /************************ free vector ******************/
1114: void free_vector(double*v, int nl, int nh)
1115: {
1116: free((FREE_ARG)(v+nl-NR_END));
1117: }
1118:
1119: /************************ivector *******************************/
1120: int *ivector(long nl,long nh)
1121: {
1122: int *v;
1123: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1124: if (!v) nrerror("allocation failure in ivector");
1125: return v-nl+NR_END;
1126: }
1127:
1128: /******************free ivector **************************/
1129: void free_ivector(int *v, long nl, long nh)
1130: {
1131: free((FREE_ARG)(v+nl-NR_END));
1132: }
1133:
1134: /************************lvector *******************************/
1135: long *lvector(long nl,long nh)
1136: {
1137: long *v;
1138: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1139: if (!v) nrerror("allocation failure in ivector");
1140: return v-nl+NR_END;
1141: }
1142:
1143: /******************free lvector **************************/
1144: void free_lvector(long *v, long nl, long nh)
1145: {
1146: free((FREE_ARG)(v+nl-NR_END));
1147: }
1148:
1149: /******************* imatrix *******************************/
1150: int **imatrix(long nrl, long nrh, long ncl, long nch)
1151: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1152: {
1153: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1154: int **m;
1155:
1156: /* allocate pointers to rows */
1157: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1158: if (!m) nrerror("allocation failure 1 in matrix()");
1159: m += NR_END;
1160: m -= nrl;
1161:
1162:
1163: /* allocate rows and set pointers to them */
1164: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1165: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1166: m[nrl] += NR_END;
1167: m[nrl] -= ncl;
1168:
1169: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1170:
1171: /* return pointer to array of pointers to rows */
1172: return m;
1173: }
1174:
1175: /****************** free_imatrix *************************/
1176: void free_imatrix(m,nrl,nrh,ncl,nch)
1177: int **m;
1178: long nch,ncl,nrh,nrl;
1179: /* free an int matrix allocated by imatrix() */
1180: {
1181: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1182: free((FREE_ARG) (m+nrl-NR_END));
1183: }
1184:
1185: /******************* matrix *******************************/
1186: double **matrix(long nrl, long nrh, long ncl, long nch)
1187: {
1188: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1189: double **m;
1190:
1191: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1192: if (!m) nrerror("allocation failure 1 in matrix()");
1193: m += NR_END;
1194: m -= nrl;
1195:
1196: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1197: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1198: m[nrl] += NR_END;
1199: m[nrl] -= ncl;
1200:
1201: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1202: return m;
1.145 brouard 1203: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1204: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1205: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1206: */
1207: }
1208:
1209: /*************************free matrix ************************/
1210: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1211: {
1212: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1213: free((FREE_ARG)(m+nrl-NR_END));
1214: }
1215:
1216: /******************* ma3x *******************************/
1217: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1218: {
1219: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1220: double ***m;
1221:
1222: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1223: if (!m) nrerror("allocation failure 1 in matrix()");
1224: m += NR_END;
1225: m -= nrl;
1226:
1227: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1228: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1229: m[nrl] += NR_END;
1230: m[nrl] -= ncl;
1231:
1232: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1233:
1234: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1235: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1236: m[nrl][ncl] += NR_END;
1237: m[nrl][ncl] -= nll;
1238: for (j=ncl+1; j<=nch; j++)
1239: m[nrl][j]=m[nrl][j-1]+nlay;
1240:
1241: for (i=nrl+1; i<=nrh; i++) {
1242: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1243: for (j=ncl+1; j<=nch; j++)
1244: m[i][j]=m[i][j-1]+nlay;
1245: }
1246: return m;
1247: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1248: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1249: */
1250: }
1251:
1252: /*************************free ma3x ************************/
1253: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1254: {
1255: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1256: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1257: free((FREE_ARG)(m+nrl-NR_END));
1258: }
1259:
1260: /*************** function subdirf ***********/
1261: char *subdirf(char fileres[])
1262: {
1263: /* Caution optionfilefiname is hidden */
1264: strcpy(tmpout,optionfilefiname);
1265: strcat(tmpout,"/"); /* Add to the right */
1266: strcat(tmpout,fileres);
1267: return tmpout;
1268: }
1269:
1270: /*************** function subdirf2 ***********/
1271: char *subdirf2(char fileres[], char *preop)
1272: {
1273:
1274: /* Caution optionfilefiname is hidden */
1275: strcpy(tmpout,optionfilefiname);
1276: strcat(tmpout,"/");
1277: strcat(tmpout,preop);
1278: strcat(tmpout,fileres);
1279: return tmpout;
1280: }
1281:
1282: /*************** function subdirf3 ***********/
1283: char *subdirf3(char fileres[], char *preop, char *preop2)
1284: {
1285:
1286: /* Caution optionfilefiname is hidden */
1287: strcpy(tmpout,optionfilefiname);
1288: strcat(tmpout,"/");
1289: strcat(tmpout,preop);
1290: strcat(tmpout,preop2);
1291: strcat(tmpout,fileres);
1292: return tmpout;
1293: }
1294:
1.162 brouard 1295: char *asc_diff_time(long time_sec, char ascdiff[])
1296: {
1297: long sec_left, days, hours, minutes;
1298: days = (time_sec) / (60*60*24);
1299: sec_left = (time_sec) % (60*60*24);
1300: hours = (sec_left) / (60*60) ;
1301: sec_left = (sec_left) %(60*60);
1302: minutes = (sec_left) /60;
1303: sec_left = (sec_left) % (60);
1304: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1305: return ascdiff;
1306: }
1307:
1.126 brouard 1308: /***************** f1dim *************************/
1309: extern int ncom;
1310: extern double *pcom,*xicom;
1311: extern double (*nrfunc)(double []);
1312:
1313: double f1dim(double x)
1314: {
1315: int j;
1316: double f;
1317: double *xt;
1318:
1319: xt=vector(1,ncom);
1320: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1321: f=(*nrfunc)(xt);
1322: free_vector(xt,1,ncom);
1323: return f;
1324: }
1325:
1326: /*****************brent *************************/
1327: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1328: {
1329: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1330: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1331: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1332: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1333: * returned function value.
1334: */
1.126 brouard 1335: int iter;
1336: double a,b,d,etemp;
1.159 brouard 1337: double fu=0,fv,fw,fx;
1.164 brouard 1338: double ftemp=0.;
1.126 brouard 1339: double p,q,r,tol1,tol2,u,v,w,x,xm;
1340: double e=0.0;
1341:
1342: a=(ax < cx ? ax : cx);
1343: b=(ax > cx ? ax : cx);
1344: x=w=v=bx;
1345: fw=fv=fx=(*f)(x);
1346: for (iter=1;iter<=ITMAX;iter++) {
1347: xm=0.5*(a+b);
1348: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1349: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1350: printf(".");fflush(stdout);
1351: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1352: #ifdef DEBUGBRENT
1.126 brouard 1353: 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);
1354: 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);
1355: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1356: #endif
1357: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1358: *xmin=x;
1359: return fx;
1360: }
1361: ftemp=fu;
1362: if (fabs(e) > tol1) {
1363: r=(x-w)*(fx-fv);
1364: q=(x-v)*(fx-fw);
1365: p=(x-v)*q-(x-w)*r;
1366: q=2.0*(q-r);
1367: if (q > 0.0) p = -p;
1368: q=fabs(q);
1369: etemp=e;
1370: e=d;
1371: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1372: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1373: else {
1374: d=p/q;
1375: u=x+d;
1376: if (u-a < tol2 || b-u < tol2)
1377: d=SIGN(tol1,xm-x);
1378: }
1379: } else {
1380: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1381: }
1382: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1383: fu=(*f)(u);
1384: if (fu <= fx) {
1385: if (u >= x) a=x; else b=x;
1386: SHFT(v,w,x,u)
1.183 brouard 1387: SHFT(fv,fw,fx,fu)
1388: } else {
1389: if (u < x) a=u; else b=u;
1390: if (fu <= fw || w == x) {
1391: v=w;
1392: w=u;
1393: fv=fw;
1394: fw=fu;
1395: } else if (fu <= fv || v == x || v == w) {
1396: v=u;
1397: fv=fu;
1398: }
1399: }
1.126 brouard 1400: }
1401: nrerror("Too many iterations in brent");
1402: *xmin=x;
1403: return fx;
1404: }
1405:
1406: /****************** mnbrak ***********************/
1407:
1408: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1409: double (*func)(double))
1.183 brouard 1410: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1411: the downhill direction (defined by the function as evaluated at the initial points) and returns
1412: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1413: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1414: */
1.126 brouard 1415: double ulim,u,r,q, dum;
1416: double fu;
1.187 brouard 1417:
1418: double scale=10.;
1419: int iterscale=0;
1420:
1421: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1422: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1423:
1424:
1425: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1426: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1427: /* *bx = *ax - (*ax - *bx)/scale; */
1428: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1429: /* } */
1430:
1.126 brouard 1431: if (*fb > *fa) {
1432: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1433: SHFT(dum,*fb,*fa,dum)
1434: }
1.126 brouard 1435: *cx=(*bx)+GOLD*(*bx-*ax);
1436: *fc=(*func)(*cx);
1.183 brouard 1437: #ifdef DEBUG
1438: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1439: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1440: #endif
1441: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1442: r=(*bx-*ax)*(*fb-*fc);
1443: q=(*bx-*cx)*(*fb-*fa);
1444: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1445: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1446: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1447: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1448: fu=(*func)(u);
1.163 brouard 1449: #ifdef DEBUG
1450: /* f(x)=A(x-u)**2+f(u) */
1451: double A, fparabu;
1452: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1453: fparabu= *fa - A*(*ax-u)*(*ax-u);
1454: 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);
1455: 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 1456: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1457: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1458: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1459: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1460: #endif
1.184 brouard 1461: #ifdef MNBRAKORIGINAL
1.183 brouard 1462: #else
1.191 brouard 1463: /* if (fu > *fc) { */
1464: /* #ifdef DEBUG */
1465: /* printf("mnbrak4 fu > fc \n"); */
1466: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1467: /* #endif */
1468: /* /\* 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 *\\/ *\/ */
1469: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1470: /* dum=u; /\* Shifting c and u *\/ */
1471: /* u = *cx; */
1472: /* *cx = dum; */
1473: /* dum = fu; */
1474: /* fu = *fc; */
1475: /* *fc =dum; */
1476: /* } else { /\* end *\/ */
1477: /* #ifdef DEBUG */
1478: /* printf("mnbrak3 fu < fc \n"); */
1479: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1480: /* #endif */
1481: /* dum=u; /\* Shifting c and u *\/ */
1482: /* u = *cx; */
1483: /* *cx = dum; */
1484: /* dum = fu; */
1485: /* fu = *fc; */
1486: /* *fc =dum; */
1487: /* } */
1.183 brouard 1488: #ifdef DEBUG
1.191 brouard 1489: printf("mnbrak34 fu < or >= fc \n");
1490: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1491: #endif
1.191 brouard 1492: dum=u; /* Shifting c and u */
1493: u = *cx;
1494: *cx = dum;
1495: dum = fu;
1496: fu = *fc;
1497: *fc =dum;
1.183 brouard 1498: #endif
1.162 brouard 1499: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1500: #ifdef DEBUG
1501: printf("mnbrak2 u after c but before ulim\n");
1502: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1503: #endif
1.126 brouard 1504: fu=(*func)(u);
1505: if (fu < *fc) {
1.183 brouard 1506: #ifdef DEBUG
1507: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1508: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1509: #endif
1.126 brouard 1510: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1511: SHFT(*fb,*fc,fu,(*func)(u))
1512: }
1.162 brouard 1513: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1514: #ifdef DEBUG
1515: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1516: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1517: #endif
1.126 brouard 1518: u=ulim;
1519: fu=(*func)(u);
1.183 brouard 1520: } else { /* u could be left to b (if r > q parabola has a maximum) */
1521: #ifdef DEBUG
1522: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1523: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1524: #endif
1.126 brouard 1525: u=(*cx)+GOLD*(*cx-*bx);
1526: fu=(*func)(u);
1.183 brouard 1527: } /* end tests */
1.126 brouard 1528: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1529: SHFT(*fa,*fb,*fc,fu)
1530: #ifdef DEBUG
1531: 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);
1532: 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);
1533: #endif
1534: } /* 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 1535: }
1536:
1537: /*************** linmin ************************/
1.162 brouard 1538: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1539: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1540: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1541: the value of func at the returned location p . This is actually all accomplished by calling the
1542: routines mnbrak and brent .*/
1.126 brouard 1543: int ncom;
1544: double *pcom,*xicom;
1545: double (*nrfunc)(double []);
1546:
1547: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1548: {
1549: double brent(double ax, double bx, double cx,
1550: double (*f)(double), double tol, double *xmin);
1551: double f1dim(double x);
1552: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1553: double *fc, double (*func)(double));
1554: int j;
1555: double xx,xmin,bx,ax;
1556: double fx,fb,fa;
1.187 brouard 1557:
1558: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126 brouard 1559:
1560: ncom=n;
1561: pcom=vector(1,n);
1562: xicom=vector(1,n);
1563: nrfunc=func;
1564: for (j=1;j<=n;j++) {
1565: pcom[j]=p[j];
1566: xicom[j]=xi[j];
1567: }
1.187 brouard 1568:
1.192 ! brouard 1569: /* axs=0.0; */
! 1570: /* xxss=1; /\* 1 and using scale *\/ */
1.187 brouard 1571: xxs=1;
1.192 ! brouard 1572: /* do{ */
1.187 brouard 1573: ax=0.;
1574: xx= xxs;
1575: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1576: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1577: /* 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)) */
1578: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1579: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1580: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1581: /* 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 1582: /* if (fx != fx){ */
! 1583: /* xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
! 1584: /* 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); */
! 1585: /* } */
! 1586: /* }while(fx != fx); */
1.187 brouard 1587:
1.191 brouard 1588: #ifdef DEBUGLINMIN
1589: 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);
1590: #endif
1.187 brouard 1591: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1592: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1593: /* fmin = f(p[j] + xmin * xi[j]) */
1594: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1595: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1596: #ifdef DEBUG
1597: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1598: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1599: #endif
1.191 brouard 1600: #ifdef DEBUGLINMIN
1601: printf("linmin end ");
1602: #endif
1.126 brouard 1603: for (j=1;j<=n;j++) {
1.188 brouard 1604: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187 brouard 1605: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189 brouard 1606: /* if(xxs <1.0) */
1607: /* 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 1608: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1609: }
1.189 brouard 1610: /* printf("\n"); */
1.191 brouard 1611: #ifdef DEBUGLINMIN
1612: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1613: for (j=1;j<=n;j++) {
1614: printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
1615: if(j % ncovmodel == 0)
1616: printf("\n");
1617: }
1618: #endif
1.126 brouard 1619: free_vector(xicom,1,n);
1620: free_vector(pcom,1,n);
1621: }
1622:
1623:
1624: /*************** powell ************************/
1.162 brouard 1625: /*
1626: Minimization of a function func of n variables. Input consists of an initial starting point
1627: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1628: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1629: such that failure to decrease by more than this amount on one iteration signals doneness. On
1630: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1631: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1632: */
1.126 brouard 1633: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1634: double (*func)(double []))
1635: {
1636: void linmin(double p[], double xi[], int n, double *fret,
1637: double (*func)(double []));
1638: int i,ibig,j;
1639: double del,t,*pt,*ptt,*xit;
1.181 brouard 1640: double directest;
1.126 brouard 1641: double fp,fptt;
1642: double *xits;
1643: int niterf, itmp;
1644:
1645: pt=vector(1,n);
1646: ptt=vector(1,n);
1647: xit=vector(1,n);
1648: xits=vector(1,n);
1649: *fret=(*func)(p);
1650: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1651: rcurr_time = time(NULL);
1.126 brouard 1652: for (*iter=1;;++(*iter)) {
1.187 brouard 1653: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1654: ibig=0;
1655: del=0.0;
1.157 brouard 1656: rlast_time=rcurr_time;
1657: /* (void) gettimeofday(&curr_time,&tzp); */
1658: rcurr_time = time(NULL);
1659: curr_time = *localtime(&rcurr_time);
1660: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1661: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1662: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 ! brouard 1663: for (i=1;i<=n;i++) {
1.126 brouard 1664: printf(" %d %.12f",i, p[i]);
1665: fprintf(ficlog," %d %.12lf",i, p[i]);
1666: fprintf(ficrespow," %.12lf", p[i]);
1667: }
1668: printf("\n");
1669: fprintf(ficlog,"\n");
1670: fprintf(ficrespow,"\n");fflush(ficrespow);
1671: if(*iter <=3){
1.157 brouard 1672: tml = *localtime(&rcurr_time);
1673: strcpy(strcurr,asctime(&tml));
1674: rforecast_time=rcurr_time;
1.126 brouard 1675: itmp = strlen(strcurr);
1676: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1677: strcurr[itmp-1]='\0';
1.162 brouard 1678: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1679: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1680: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1681: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1682: forecast_time = *localtime(&rforecast_time);
1683: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1684: itmp = strlen(strfor);
1685: if(strfor[itmp-1]=='\n')
1686: strfor[itmp-1]='\0';
1.157 brouard 1687: 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);
1688: 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 1689: }
1690: }
1.187 brouard 1691: for (i=1;i<=n;i++) { /* For each direction i */
1692: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1693: fptt=(*fret);
1694: #ifdef DEBUG
1.164 brouard 1695: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1696: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1697: #endif
1.187 brouard 1698: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1699: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1700: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1701: /* Outputs are fret(new point p) p is updated and xit rescaled */
1702: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1703: /* because that direction will be replaced unless the gain del is small */
1704: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1705: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1706: /* with the new direction. */
1.126 brouard 1707: del=fabs(fptt-(*fret));
1708: ibig=i;
1709: }
1710: #ifdef DEBUG
1711: printf("%d %.12e",i,(*fret));
1712: fprintf(ficlog,"%d %.12e",i,(*fret));
1713: for (j=1;j<=n;j++) {
1714: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1715: printf(" x(%d)=%.12e",j,xit[j]);
1716: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1717: }
1718: for(j=1;j<=n;j++) {
1.162 brouard 1719: printf(" p(%d)=%.12e",j,p[j]);
1720: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1721: }
1722: printf("\n");
1723: fprintf(ficlog,"\n");
1724: #endif
1.187 brouard 1725: } /* end loop on each direction i */
1726: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1727: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1728: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1729: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1730: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1731: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1732: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1733: /* decreased of more than 3.84 */
1734: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1735: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1736: /* By adding 10 parameters more the gain should be 18.31 */
1737:
1738: /* Starting the program with initial values given by a former maximization will simply change */
1739: /* the scales of the directions and the directions, because the are reset to canonical directions */
1740: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1741: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1742: #ifdef DEBUG
1743: int k[2],l;
1744: k[0]=1;
1745: k[1]=-1;
1746: printf("Max: %.12e",(*func)(p));
1747: fprintf(ficlog,"Max: %.12e",(*func)(p));
1748: for (j=1;j<=n;j++) {
1749: printf(" %.12e",p[j]);
1750: fprintf(ficlog," %.12e",p[j]);
1751: }
1752: printf("\n");
1753: fprintf(ficlog,"\n");
1754: for(l=0;l<=1;l++) {
1755: for (j=1;j<=n;j++) {
1756: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1757: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1758: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1759: }
1760: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1761: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1762: }
1763: #endif
1764:
1765:
1766: free_vector(xit,1,n);
1767: free_vector(xits,1,n);
1768: free_vector(ptt,1,n);
1769: free_vector(pt,1,n);
1770: return;
1.192 ! brouard 1771: } /* enough precision */
1.126 brouard 1772: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1773: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1774: ptt[j]=2.0*p[j]-pt[j];
1775: xit[j]=p[j]-pt[j];
1776: pt[j]=p[j];
1777: }
1.181 brouard 1778: fptt=(*func)(ptt); /* f_3 */
1.192 ! brouard 1779: #ifdef POWELLF1F3
! 1780: #else
1.161 brouard 1781: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 ! brouard 1782: #endif
1.162 brouard 1783: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1784: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1785: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1786: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1787: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1788: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1789: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1790: #ifdef NRCORIGINAL
1791: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1792: #else
1793: 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 1794: t= t- del*SQR(fp-fptt);
1.183 brouard 1795: #endif
1.182 brouard 1796: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1797: #ifdef DEBUG
1.181 brouard 1798: 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);
1799: 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 1800: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1801: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1802: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1803: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1804: 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);
1805: 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);
1806: #endif
1.183 brouard 1807: #ifdef POWELLORIGINAL
1808: if (t < 0.0) { /* Then we use it for new direction */
1809: #else
1.182 brouard 1810: if (directest*t < 0.0) { /* Contradiction between both tests */
1.192 ! brouard 1811: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
! 1812: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
! 1813: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
! 1814: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
! 1815: }
1.181 brouard 1816: if (directest < 0.0) { /* Then we use it for new direction */
1817: #endif
1.191 brouard 1818: #ifdef DEBUGLINMIN
1819: printf("Before linmin in direction P%d-P0\n",n);
1820: for (j=1;j<=n;j++) {
1821: printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1822: if(j % ncovmodel == 0)
1823: printf("\n");
1824: }
1825: #endif
1.187 brouard 1826: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1827: #ifdef DEBUGLINMIN
1828: for (j=1;j<=n;j++) {
1829: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1830: if(j % ncovmodel == 0)
1831: printf("\n");
1832: }
1833: #endif
1.126 brouard 1834: for (j=1;j<=n;j++) {
1.181 brouard 1835: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1836: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1837: }
1.181 brouard 1838: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1839: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1840:
1.126 brouard 1841: #ifdef DEBUG
1.164 brouard 1842: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1843: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1844: for(j=1;j<=n;j++){
1845: printf(" %.12e",xit[j]);
1846: fprintf(ficlog," %.12e",xit[j]);
1847: }
1848: printf("\n");
1849: fprintf(ficlog,"\n");
1850: #endif
1.192 ! brouard 1851: } /* end of t or directest negative */
! 1852: #ifdef POWELLF1F3
! 1853: #else
1.162 brouard 1854: } /* end if (fptt < fp) */
1.192 ! brouard 1855: #endif
! 1856: } /* loop iteration */
1.126 brouard 1857: }
1858:
1859: /**** Prevalence limit (stable or period prevalence) ****************/
1860:
1861: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1862: {
1863: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1864: matrix by transitions matrix until convergence is reached */
1.169 brouard 1865:
1.126 brouard 1866: int i, ii,j,k;
1867: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1868: /* double **matprod2(); */ /* test */
1.131 brouard 1869: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1870: double **newm;
1871: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1872:
1.126 brouard 1873: for (ii=1;ii<=nlstate+ndeath;ii++)
1874: for (j=1;j<=nlstate+ndeath;j++){
1875: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1876: }
1.169 brouard 1877:
1878: cov[1]=1.;
1879:
1880: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1881: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1882: newm=savm;
1883: /* Covariates have to be included here again */
1.138 brouard 1884: cov[2]=agefin;
1.187 brouard 1885: if(nagesqr==1)
1886: cov[3]= agefin*agefin;;
1.138 brouard 1887: for (k=1; k<=cptcovn;k++) {
1.187 brouard 1888: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1889: /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
1.138 brouard 1890: }
1.186 brouard 1891: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 1892: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186 brouard 1893: for (k=1; k<=cptcovprod;k++) /* Useless */
1.187 brouard 1894: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.138 brouard 1895:
1896: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1897: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1898: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1899: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1900: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1901: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1902:
1.126 brouard 1903: savm=oldm;
1904: oldm=newm;
1905: maxmax=0.;
1906: for(j=1;j<=nlstate;j++){
1907: min=1.;
1908: max=0.;
1909: for(i=1; i<=nlstate; i++) {
1910: sumnew=0;
1911: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1912: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1913: /*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 1914: max=FMAX(max,prlim[i][j]);
1915: min=FMIN(min,prlim[i][j]);
1916: }
1917: maxmin=max-min;
1918: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1919: } /* j loop */
1.126 brouard 1920: if(maxmax < ftolpl){
1921: return prlim;
1922: }
1.169 brouard 1923: } /* age loop */
1924: return prlim; /* should not reach here */
1.126 brouard 1925: }
1926:
1927: /*************** transition probabilities ***************/
1928:
1929: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1930: {
1.138 brouard 1931: /* According to parameters values stored in x and the covariate's values stored in cov,
1932: computes the probability to be observed in state j being in state i by appying the
1933: model to the ncovmodel covariates (including constant and age).
1934: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1935: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1936: ncth covariate in the global vector x is given by the formula:
1937: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1938: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1939: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1940: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1941: Outputs ps[i][j] the probability to be observed in j being in j according to
1942: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1943: */
1944: double s1, lnpijopii;
1.126 brouard 1945: /*double t34;*/
1.164 brouard 1946: int i,j, nc, ii, jj;
1.126 brouard 1947:
1948: for(i=1; i<= nlstate; i++){
1949: for(j=1; j<i;j++){
1.138 brouard 1950: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1951: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1952: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1953: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1954: }
1.138 brouard 1955: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1956: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1957: }
1958: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1959: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1960: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1961: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1962: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1963: }
1.138 brouard 1964: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1965: }
1966: }
1967:
1968: for(i=1; i<= nlstate; i++){
1969: s1=0;
1.131 brouard 1970: for(j=1; j<i; j++){
1.138 brouard 1971: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1972: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1973: }
1974: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1975: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1976: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1977: }
1.138 brouard 1978: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1979: ps[i][i]=1./(s1+1.);
1.138 brouard 1980: /* Computing other pijs */
1.126 brouard 1981: for(j=1; j<i; j++)
1982: ps[i][j]= exp(ps[i][j])*ps[i][i];
1983: for(j=i+1; j<=nlstate+ndeath; j++)
1984: ps[i][j]= exp(ps[i][j])*ps[i][i];
1985: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1986: } /* end i */
1987:
1988: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1989: for(jj=1; jj<= nlstate+ndeath; jj++){
1990: ps[ii][jj]=0;
1991: ps[ii][ii]=1;
1992: }
1993: }
1994:
1.145 brouard 1995:
1996: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1997: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1998: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1999: /* } */
2000: /* printf("\n "); */
2001: /* } */
2002: /* printf("\n ");printf("%lf ",cov[2]);*/
2003: /*
1.126 brouard 2004: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2005: goto end;*/
2006: return ps;
2007: }
2008:
2009: /**************** Product of 2 matrices ******************/
2010:
1.145 brouard 2011: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2012: {
2013: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2014: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2015: /* in, b, out are matrice of pointers which should have been initialized
2016: before: only the contents of out is modified. The function returns
2017: a pointer to pointers identical to out */
1.145 brouard 2018: int i, j, k;
1.126 brouard 2019: for(i=nrl; i<= nrh; i++)
1.145 brouard 2020: for(k=ncolol; k<=ncoloh; k++){
2021: out[i][k]=0.;
2022: for(j=ncl; j<=nch; j++)
2023: out[i][k] +=in[i][j]*b[j][k];
2024: }
1.126 brouard 2025: return out;
2026: }
2027:
2028:
2029: /************* Higher Matrix Product ***************/
2030:
2031: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2032: {
2033: /* Computes the transition matrix starting at age 'age' over
2034: 'nhstepm*hstepm*stepm' months (i.e. until
2035: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2036: nhstepm*hstepm matrices.
2037: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2038: (typically every 2 years instead of every month which is too big
2039: for the memory).
2040: Model is determined by parameters x and covariates have to be
2041: included manually here.
2042:
2043: */
2044:
2045: int i, j, d, h, k;
1.131 brouard 2046: double **out, cov[NCOVMAX+1];
1.126 brouard 2047: double **newm;
1.187 brouard 2048: double agexact;
1.126 brouard 2049:
2050: /* Hstepm could be zero and should return the unit matrix */
2051: for (i=1;i<=nlstate+ndeath;i++)
2052: for (j=1;j<=nlstate+ndeath;j++){
2053: oldm[i][j]=(i==j ? 1.0 : 0.0);
2054: po[i][j][0]=(i==j ? 1.0 : 0.0);
2055: }
2056: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2057: for(h=1; h <=nhstepm; h++){
2058: for(d=1; d <=hstepm; d++){
2059: newm=savm;
2060: /* Covariates have to be included here again */
2061: cov[1]=1.;
1.187 brouard 2062: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2063: cov[2]=agexact;
2064: if(nagesqr==1)
2065: cov[3]= agexact*agexact;
1.131 brouard 2066: for (k=1; k<=cptcovn;k++)
1.187 brouard 2067: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186 brouard 2068: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2069: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 2070: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145 brouard 2071: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187 brouard 2072: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126 brouard 2073:
2074:
2075: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2076: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2077: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2078: pmij(pmmij,cov,ncovmodel,x,nlstate));
2079: savm=oldm;
2080: oldm=newm;
2081: }
2082: for(i=1; i<=nlstate+ndeath; i++)
2083: for(j=1;j<=nlstate+ndeath;j++) {
2084: po[i][j][h]=newm[i][j];
1.128 brouard 2085: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2086: }
1.128 brouard 2087: /*printf("h=%d ",h);*/
1.126 brouard 2088: } /* end h */
1.128 brouard 2089: /* printf("\n H=%d \n",h); */
1.126 brouard 2090: return po;
2091: }
2092:
1.162 brouard 2093: #ifdef NLOPT
2094: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2095: double fret;
2096: double *xt;
2097: int j;
2098: myfunc_data *d2 = (myfunc_data *) pd;
2099: /* xt = (p1-1); */
2100: xt=vector(1,n);
2101: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2102:
2103: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2104: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2105: printf("Function = %.12lf ",fret);
2106: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2107: printf("\n");
2108: free_vector(xt,1,n);
2109: return fret;
2110: }
2111: #endif
1.126 brouard 2112:
2113: /*************** log-likelihood *************/
2114: double func( double *x)
2115: {
2116: int i, ii, j, k, mi, d, kk;
1.131 brouard 2117: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2118: double **out;
2119: double sw; /* Sum of weights */
2120: double lli; /* Individual log likelihood */
2121: int s1, s2;
2122: double bbh, survp;
2123: long ipmx;
1.187 brouard 2124: double agexact;
1.126 brouard 2125: /*extern weight */
2126: /* We are differentiating ll according to initial status */
2127: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2128: /*for(i=1;i<imx;i++)
2129: printf(" %d\n",s[4][i]);
2130: */
1.162 brouard 2131:
2132: ++countcallfunc;
2133:
1.126 brouard 2134: cov[1]=1.;
2135:
2136: for(k=1; k<=nlstate; k++) ll[k]=0.;
2137:
2138: if(mle==1){
2139: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2140: /* Computes the values of the ncovmodel covariates of the model
2141: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2142: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2143: to be observed in j being in i according to the model.
2144: */
1.145 brouard 2145: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2146: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2147: }
1.137 brouard 2148: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2149: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2150: has been calculated etc */
1.126 brouard 2151: for(mi=1; mi<= wav[i]-1; mi++){
2152: for (ii=1;ii<=nlstate+ndeath;ii++)
2153: for (j=1;j<=nlstate+ndeath;j++){
2154: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2155: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2156: }
2157: for(d=0; d<dh[mi][i]; d++){
2158: newm=savm;
1.187 brouard 2159: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2160: cov[2]=agexact;
2161: if(nagesqr==1)
2162: cov[3]= agexact*agexact;
1.126 brouard 2163: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2164: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2165: }
2166: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2167: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2168: savm=oldm;
2169: oldm=newm;
2170: } /* end mult */
2171:
2172: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2173: /* But now since version 0.9 we anticipate for bias at large stepm.
2174: * If stepm is larger than one month (smallest stepm) and if the exact delay
2175: * (in months) between two waves is not a multiple of stepm, we rounded to
2176: * the nearest (and in case of equal distance, to the lowest) interval but now
2177: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2178: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2179: * probability in order to take into account the bias as a fraction of the way
2180: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2181: * -stepm/2 to stepm/2 .
2182: * For stepm=1 the results are the same as for previous versions of Imach.
2183: * For stepm > 1 the results are less biased than in previous versions.
2184: */
2185: s1=s[mw[mi][i]][i];
2186: s2=s[mw[mi+1][i]][i];
2187: bbh=(double)bh[mi][i]/(double)stepm;
2188: /* bias bh is positive if real duration
2189: * is higher than the multiple of stepm and negative otherwise.
2190: */
2191: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2192: if( s2 > nlstate){
2193: /* i.e. if s2 is a death state and if the date of death is known
2194: then the contribution to the likelihood is the probability to
2195: die between last step unit time and current step unit time,
2196: which is also equal to probability to die before dh
2197: minus probability to die before dh-stepm .
2198: In version up to 0.92 likelihood was computed
2199: as if date of death was unknown. Death was treated as any other
2200: health state: the date of the interview describes the actual state
2201: and not the date of a change in health state. The former idea was
2202: to consider that at each interview the state was recorded
2203: (healthy, disable or death) and IMaCh was corrected; but when we
2204: introduced the exact date of death then we should have modified
2205: the contribution of an exact death to the likelihood. This new
2206: contribution is smaller and very dependent of the step unit
2207: stepm. It is no more the probability to die between last interview
2208: and month of death but the probability to survive from last
2209: interview up to one month before death multiplied by the
2210: probability to die within a month. Thanks to Chris
2211: Jackson for correcting this bug. Former versions increased
2212: mortality artificially. The bad side is that we add another loop
2213: which slows down the processing. The difference can be up to 10%
2214: lower mortality.
2215: */
1.183 brouard 2216: /* If, at the beginning of the maximization mostly, the
2217: cumulative probability or probability to be dead is
2218: constant (ie = 1) over time d, the difference is equal to
2219: 0. out[s1][3] = savm[s1][3]: probability, being at state
2220: s1 at precedent wave, to be dead a month before current
2221: wave is equal to probability, being at state s1 at
2222: precedent wave, to be dead at mont of the current
2223: wave. Then the observed probability (that this person died)
2224: is null according to current estimated parameter. In fact,
2225: it should be very low but not zero otherwise the log go to
2226: infinity.
2227: */
2228: /* #ifdef INFINITYORIGINAL */
2229: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2230: /* #else */
2231: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2232: /* lli=log(mytinydouble); */
2233: /* else */
2234: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2235: /* #endif */
2236: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2237:
2238: } else if (s2==-2) {
2239: for (j=1,survp=0. ; j<=nlstate; j++)
2240: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2241: /*survp += out[s1][j]; */
2242: lli= log(survp);
2243: }
2244:
2245: else if (s2==-4) {
2246: for (j=3,survp=0. ; j<=nlstate; j++)
2247: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2248: lli= log(survp);
2249: }
2250:
2251: else if (s2==-5) {
2252: for (j=1,survp=0. ; j<=2; j++)
2253: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2254: lli= log(survp);
2255: }
2256:
2257: else{
2258: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2259: /* 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 */
2260: }
2261: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2262: /*if(lli ==000.0)*/
2263: /*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); */
2264: ipmx +=1;
2265: sw += weight[i];
2266: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2267: /* if (lli < log(mytinydouble)){ */
2268: /* 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); */
2269: /* 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]); */
2270: /* } */
1.126 brouard 2271: } /* end of wave */
2272: } /* end of individual */
2273: } else if(mle==2){
2274: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2275: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2276: for(mi=1; mi<= wav[i]-1; mi++){
2277: for (ii=1;ii<=nlstate+ndeath;ii++)
2278: for (j=1;j<=nlstate+ndeath;j++){
2279: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2280: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2281: }
2282: for(d=0; d<=dh[mi][i]; d++){
2283: newm=savm;
1.187 brouard 2284: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2285: cov[2]=agexact;
2286: if(nagesqr==1)
2287: cov[3]= agexact*agexact;
1.126 brouard 2288: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2289: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2290: }
2291: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2292: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2293: savm=oldm;
2294: oldm=newm;
2295: } /* end mult */
2296:
2297: s1=s[mw[mi][i]][i];
2298: s2=s[mw[mi+1][i]][i];
2299: bbh=(double)bh[mi][i]/(double)stepm;
2300: 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 */
2301: ipmx +=1;
2302: sw += weight[i];
2303: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2304: } /* end of wave */
2305: } /* end of individual */
2306: } else if(mle==3){ /* exponential inter-extrapolation */
2307: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2308: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2309: for(mi=1; mi<= wav[i]-1; mi++){
2310: for (ii=1;ii<=nlstate+ndeath;ii++)
2311: for (j=1;j<=nlstate+ndeath;j++){
2312: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2313: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2314: }
2315: for(d=0; d<dh[mi][i]; d++){
2316: newm=savm;
1.187 brouard 2317: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2318: cov[2]=agexact;
2319: if(nagesqr==1)
2320: cov[3]= agexact*agexact;
1.126 brouard 2321: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2322: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2323: }
2324: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2325: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2326: savm=oldm;
2327: oldm=newm;
2328: } /* end mult */
2329:
2330: s1=s[mw[mi][i]][i];
2331: s2=s[mw[mi+1][i]][i];
2332: bbh=(double)bh[mi][i]/(double)stepm;
2333: 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 */
2334: ipmx +=1;
2335: sw += weight[i];
2336: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2337: } /* end of wave */
2338: } /* end of individual */
2339: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2340: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2341: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2342: for(mi=1; mi<= wav[i]-1; mi++){
2343: for (ii=1;ii<=nlstate+ndeath;ii++)
2344: for (j=1;j<=nlstate+ndeath;j++){
2345: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2346: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2347: }
2348: for(d=0; d<dh[mi][i]; d++){
2349: newm=savm;
1.187 brouard 2350: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2351: cov[2]=agexact;
2352: if(nagesqr==1)
2353: cov[3]= agexact*agexact;
1.126 brouard 2354: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2355: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2356: }
2357:
2358: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2359: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2360: savm=oldm;
2361: oldm=newm;
2362: } /* end mult */
2363:
2364: s1=s[mw[mi][i]][i];
2365: s2=s[mw[mi+1][i]][i];
2366: if( s2 > nlstate){
2367: lli=log(out[s1][s2] - savm[s1][s2]);
2368: }else{
2369: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2370: }
2371: ipmx +=1;
2372: sw += weight[i];
2373: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2374: /* 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]); */
2375: } /* end of wave */
2376: } /* end of individual */
2377: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2378: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2379: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2380: for(mi=1; mi<= wav[i]-1; mi++){
2381: for (ii=1;ii<=nlstate+ndeath;ii++)
2382: for (j=1;j<=nlstate+ndeath;j++){
2383: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2384: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2385: }
2386: for(d=0; d<dh[mi][i]; d++){
2387: newm=savm;
1.187 brouard 2388: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2389: cov[2]=agexact;
2390: if(nagesqr==1)
2391: cov[3]= agexact*agexact;
1.126 brouard 2392: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2393: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2394: }
2395:
2396: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2397: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2398: savm=oldm;
2399: oldm=newm;
2400: } /* end mult */
2401:
2402: s1=s[mw[mi][i]][i];
2403: s2=s[mw[mi+1][i]][i];
2404: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2405: ipmx +=1;
2406: sw += weight[i];
2407: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2408: /*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]);*/
2409: } /* end of wave */
2410: } /* end of individual */
2411: } /* End of if */
2412: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2413: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2414: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2415: return -l;
2416: }
2417:
2418: /*************** log-likelihood *************/
2419: double funcone( double *x)
2420: {
2421: /* Same as likeli but slower because of a lot of printf and if */
2422: int i, ii, j, k, mi, d, kk;
1.131 brouard 2423: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2424: double **out;
2425: double lli; /* Individual log likelihood */
2426: double llt;
2427: int s1, s2;
2428: double bbh, survp;
1.187 brouard 2429: double agexact;
1.126 brouard 2430: /*extern weight */
2431: /* We are differentiating ll according to initial status */
2432: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2433: /*for(i=1;i<imx;i++)
2434: printf(" %d\n",s[4][i]);
2435: */
2436: cov[1]=1.;
2437:
2438: for(k=1; k<=nlstate; k++) ll[k]=0.;
2439:
2440: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2441: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2442: for(mi=1; mi<= wav[i]-1; mi++){
2443: for (ii=1;ii<=nlstate+ndeath;ii++)
2444: for (j=1;j<=nlstate+ndeath;j++){
2445: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2446: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2447: }
2448: for(d=0; d<dh[mi][i]; d++){
2449: newm=savm;
1.187 brouard 2450: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2451: cov[2]=agexact;
2452: if(nagesqr==1)
2453: cov[3]= agexact*agexact;
1.126 brouard 2454: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2455: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2456: }
1.187 brouard 2457:
1.145 brouard 2458: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2459: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2460: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2461: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2462: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2463: savm=oldm;
2464: oldm=newm;
2465: } /* end mult */
2466:
2467: s1=s[mw[mi][i]][i];
2468: s2=s[mw[mi+1][i]][i];
2469: bbh=(double)bh[mi][i]/(double)stepm;
2470: /* bias is positive if real duration
2471: * is higher than the multiple of stepm and negative otherwise.
2472: */
2473: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2474: lli=log(out[s1][s2] - savm[s1][s2]);
2475: } else if (s2==-2) {
2476: for (j=1,survp=0. ; j<=nlstate; j++)
2477: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2478: lli= log(survp);
2479: }else if (mle==1){
2480: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2481: } else if(mle==2){
2482: 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 */
2483: } else if(mle==3){ /* exponential inter-extrapolation */
2484: 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 */
2485: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2486: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2487: } else{ /* mle=0 back to 1 */
2488: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2489: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2490: } /* End of if */
2491: ipmx +=1;
2492: sw += weight[i];
2493: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2494: /*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 2495: if(globpr){
1.141 brouard 2496: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2497: %11.6f %11.6f %11.6f ", \
2498: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2499: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2500: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2501: llt +=ll[k]*gipmx/gsw;
2502: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2503: }
2504: fprintf(ficresilk," %10.6f\n", -llt);
2505: }
2506: } /* end of wave */
2507: } /* end of individual */
2508: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2509: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2510: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2511: if(globpr==0){ /* First time we count the contributions and weights */
2512: gipmx=ipmx;
2513: gsw=sw;
2514: }
2515: return -l;
2516: }
2517:
2518:
2519: /*************** function likelione ***********/
2520: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2521: {
2522: /* This routine should help understanding what is done with
2523: the selection of individuals/waves and
2524: to check the exact contribution to the likelihood.
2525: Plotting could be done.
2526: */
2527: int k;
2528:
2529: if(*globpri !=0){ /* Just counts and sums, no printings */
2530: strcpy(fileresilk,"ilk");
2531: strcat(fileresilk,fileres);
2532: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2533: printf("Problem with resultfile: %s\n", fileresilk);
2534: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2535: }
2536: 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");
2537: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2538: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2539: for(k=1; k<=nlstate; k++)
2540: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2541: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2542: }
2543:
2544: *fretone=(*funcone)(p);
2545: if(*globpri !=0){
2546: fclose(ficresilk);
2547: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2548: fflush(fichtm);
2549: }
2550: return;
2551: }
2552:
2553:
2554: /*********** Maximum Likelihood Estimation ***************/
2555:
2556: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2557: {
1.165 brouard 2558: int i,j, iter=0;
1.126 brouard 2559: double **xi;
2560: double fret;
2561: double fretone; /* Only one call to likelihood */
2562: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2563:
2564: #ifdef NLOPT
2565: int creturn;
2566: nlopt_opt opt;
2567: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2568: double *lb;
2569: double minf; /* the minimum objective value, upon return */
2570: double * p1; /* Shifted parameters from 0 instead of 1 */
2571: myfunc_data dinst, *d = &dinst;
2572: #endif
2573:
2574:
1.126 brouard 2575: xi=matrix(1,npar,1,npar);
2576: for (i=1;i<=npar;i++)
2577: for (j=1;j<=npar;j++)
2578: xi[i][j]=(i==j ? 1.0 : 0.0);
2579: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2580: strcpy(filerespow,"pow");
2581: strcat(filerespow,fileres);
2582: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2583: printf("Problem with resultfile: %s\n", filerespow);
2584: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2585: }
2586: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2587: for (i=1;i<=nlstate;i++)
2588: for(j=1;j<=nlstate+ndeath;j++)
2589: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2590: fprintf(ficrespow,"\n");
1.162 brouard 2591: #ifdef POWELL
1.126 brouard 2592: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2593: #endif
1.126 brouard 2594:
1.162 brouard 2595: #ifdef NLOPT
2596: #ifdef NEWUOA
2597: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2598: #else
2599: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2600: #endif
2601: lb=vector(0,npar-1);
2602: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2603: nlopt_set_lower_bounds(opt, lb);
2604: nlopt_set_initial_step1(opt, 0.1);
2605:
2606: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2607: d->function = func;
2608: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2609: nlopt_set_min_objective(opt, myfunc, d);
2610: nlopt_set_xtol_rel(opt, ftol);
2611: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2612: printf("nlopt failed! %d\n",creturn);
2613: }
2614: else {
2615: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2616: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2617: iter=1; /* not equal */
2618: }
2619: nlopt_destroy(opt);
2620: #endif
1.126 brouard 2621: free_matrix(xi,1,npar,1,npar);
2622: fclose(ficrespow);
1.180 brouard 2623: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2624: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2625: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2626:
2627: }
2628:
2629: /**** Computes Hessian and covariance matrix ***/
2630: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2631: {
2632: double **a,**y,*x,pd;
2633: double **hess;
1.164 brouard 2634: int i, j;
1.126 brouard 2635: int *indx;
2636:
2637: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2638: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2639: void lubksb(double **a, int npar, int *indx, double b[]) ;
2640: void ludcmp(double **a, int npar, int *indx, double *d) ;
2641: double gompertz(double p[]);
2642: hess=matrix(1,npar,1,npar);
2643:
2644: printf("\nCalculation of the hessian matrix. Wait...\n");
2645: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2646: for (i=1;i<=npar;i++){
2647: printf("%d",i);fflush(stdout);
2648: fprintf(ficlog,"%d",i);fflush(ficlog);
2649:
2650: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2651:
2652: /* printf(" %f ",p[i]);
2653: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2654: }
2655:
2656: for (i=1;i<=npar;i++) {
2657: for (j=1;j<=npar;j++) {
2658: if (j>i) {
2659: printf(".%d%d",i,j);fflush(stdout);
2660: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2661: hess[i][j]=hessij(p,delti,i,j,func,npar);
2662:
2663: hess[j][i]=hess[i][j];
2664: /*printf(" %lf ",hess[i][j]);*/
2665: }
2666: }
2667: }
2668: printf("\n");
2669: fprintf(ficlog,"\n");
2670:
2671: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2672: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2673:
2674: a=matrix(1,npar,1,npar);
2675: y=matrix(1,npar,1,npar);
2676: x=vector(1,npar);
2677: indx=ivector(1,npar);
2678: for (i=1;i<=npar;i++)
2679: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2680: ludcmp(a,npar,indx,&pd);
2681:
2682: for (j=1;j<=npar;j++) {
2683: for (i=1;i<=npar;i++) x[i]=0;
2684: x[j]=1;
2685: lubksb(a,npar,indx,x);
2686: for (i=1;i<=npar;i++){
2687: matcov[i][j]=x[i];
2688: }
2689: }
2690:
2691: printf("\n#Hessian matrix#\n");
2692: fprintf(ficlog,"\n#Hessian matrix#\n");
2693: for (i=1;i<=npar;i++) {
2694: for (j=1;j<=npar;j++) {
2695: printf("%.3e ",hess[i][j]);
2696: fprintf(ficlog,"%.3e ",hess[i][j]);
2697: }
2698: printf("\n");
2699: fprintf(ficlog,"\n");
2700: }
2701:
2702: /* Recompute Inverse */
2703: for (i=1;i<=npar;i++)
2704: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2705: ludcmp(a,npar,indx,&pd);
2706:
2707: /* printf("\n#Hessian matrix recomputed#\n");
2708:
2709: for (j=1;j<=npar;j++) {
2710: for (i=1;i<=npar;i++) x[i]=0;
2711: x[j]=1;
2712: lubksb(a,npar,indx,x);
2713: for (i=1;i<=npar;i++){
2714: y[i][j]=x[i];
2715: printf("%.3e ",y[i][j]);
2716: fprintf(ficlog,"%.3e ",y[i][j]);
2717: }
2718: printf("\n");
2719: fprintf(ficlog,"\n");
2720: }
2721: */
2722:
2723: free_matrix(a,1,npar,1,npar);
2724: free_matrix(y,1,npar,1,npar);
2725: free_vector(x,1,npar);
2726: free_ivector(indx,1,npar);
2727: free_matrix(hess,1,npar,1,npar);
2728:
2729:
2730: }
2731:
2732: /*************** hessian matrix ****************/
2733: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2734: {
2735: int i;
2736: int l=1, lmax=20;
2737: double k1,k2;
1.132 brouard 2738: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2739: double res;
2740: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2741: double fx;
2742: int k=0,kmax=10;
2743: double l1;
2744:
2745: fx=func(x);
2746: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2747: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2748: l1=pow(10,l);
2749: delts=delt;
2750: for(k=1 ; k <kmax; k=k+1){
2751: delt = delta*(l1*k);
2752: p2[theta]=x[theta] +delt;
1.145 brouard 2753: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2754: p2[theta]=x[theta]-delt;
2755: k2=func(p2)-fx;
2756: /*res= (k1-2.0*fx+k2)/delt/delt; */
2757: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2758:
1.132 brouard 2759: #ifdef DEBUGHESS
1.126 brouard 2760: 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);
2761: 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);
2762: #endif
2763: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2764: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2765: k=kmax;
2766: }
2767: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2768: k=kmax; l=lmax*10;
1.126 brouard 2769: }
2770: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2771: delts=delt;
2772: }
2773: }
2774: }
2775: delti[theta]=delts;
2776: return res;
2777:
2778: }
2779:
2780: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2781: {
2782: int i;
1.164 brouard 2783: int l=1, lmax=20;
1.126 brouard 2784: double k1,k2,k3,k4,res,fx;
1.132 brouard 2785: double p2[MAXPARM+1];
1.126 brouard 2786: int k;
2787:
2788: fx=func(x);
2789: for (k=1; k<=2; k++) {
2790: for (i=1;i<=npar;i++) p2[i]=x[i];
2791: p2[thetai]=x[thetai]+delti[thetai]/k;
2792: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2793: k1=func(p2)-fx;
2794:
2795: p2[thetai]=x[thetai]+delti[thetai]/k;
2796: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2797: k2=func(p2)-fx;
2798:
2799: p2[thetai]=x[thetai]-delti[thetai]/k;
2800: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2801: k3=func(p2)-fx;
2802:
2803: p2[thetai]=x[thetai]-delti[thetai]/k;
2804: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2805: k4=func(p2)-fx;
2806: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2807: #ifdef DEBUG
2808: 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);
2809: 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);
2810: #endif
2811: }
2812: return res;
2813: }
2814:
2815: /************** Inverse of matrix **************/
2816: void ludcmp(double **a, int n, int *indx, double *d)
2817: {
2818: int i,imax,j,k;
2819: double big,dum,sum,temp;
2820: double *vv;
2821:
2822: vv=vector(1,n);
2823: *d=1.0;
2824: for (i=1;i<=n;i++) {
2825: big=0.0;
2826: for (j=1;j<=n;j++)
2827: if ((temp=fabs(a[i][j])) > big) big=temp;
2828: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2829: vv[i]=1.0/big;
2830: }
2831: for (j=1;j<=n;j++) {
2832: for (i=1;i<j;i++) {
2833: sum=a[i][j];
2834: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2835: a[i][j]=sum;
2836: }
2837: big=0.0;
2838: for (i=j;i<=n;i++) {
2839: sum=a[i][j];
2840: for (k=1;k<j;k++)
2841: sum -= a[i][k]*a[k][j];
2842: a[i][j]=sum;
2843: if ( (dum=vv[i]*fabs(sum)) >= big) {
2844: big=dum;
2845: imax=i;
2846: }
2847: }
2848: if (j != imax) {
2849: for (k=1;k<=n;k++) {
2850: dum=a[imax][k];
2851: a[imax][k]=a[j][k];
2852: a[j][k]=dum;
2853: }
2854: *d = -(*d);
2855: vv[imax]=vv[j];
2856: }
2857: indx[j]=imax;
2858: if (a[j][j] == 0.0) a[j][j]=TINY;
2859: if (j != n) {
2860: dum=1.0/(a[j][j]);
2861: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2862: }
2863: }
2864: free_vector(vv,1,n); /* Doesn't work */
2865: ;
2866: }
2867:
2868: void lubksb(double **a, int n, int *indx, double b[])
2869: {
2870: int i,ii=0,ip,j;
2871: double sum;
2872:
2873: for (i=1;i<=n;i++) {
2874: ip=indx[i];
2875: sum=b[ip];
2876: b[ip]=b[i];
2877: if (ii)
2878: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2879: else if (sum) ii=i;
2880: b[i]=sum;
2881: }
2882: for (i=n;i>=1;i--) {
2883: sum=b[i];
2884: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2885: b[i]=sum/a[i][i];
2886: }
2887: }
2888:
2889: void pstamp(FILE *fichier)
2890: {
2891: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2892: }
2893:
2894: /************ Frequencies ********************/
2895: 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[])
2896: { /* Some frequencies */
2897:
1.164 brouard 2898: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2899: int first;
2900: double ***freq; /* Frequencies */
2901: double *pp, **prop;
2902: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2903: char fileresp[FILENAMELENGTH];
2904:
2905: pp=vector(1,nlstate);
2906: prop=matrix(1,nlstate,iagemin,iagemax+3);
2907: strcpy(fileresp,"p");
2908: strcat(fileresp,fileres);
2909: if((ficresp=fopen(fileresp,"w"))==NULL) {
2910: printf("Problem with prevalence resultfile: %s\n", fileresp);
2911: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2912: exit(0);
2913: }
2914: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2915: j1=0;
2916:
2917: j=cptcoveff;
2918: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2919:
2920: first=1;
2921:
1.169 brouard 2922: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2923: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2924: /* j1++; */
1.145 brouard 2925: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2926: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2927: scanf("%d", i);*/
2928: for (i=-5; i<=nlstate+ndeath; i++)
2929: for (jk=-5; jk<=nlstate+ndeath; jk++)
2930: for(m=iagemin; m <= iagemax+3; m++)
2931: freq[i][jk][m]=0;
1.143 brouard 2932:
2933: for (i=1; i<=nlstate; i++)
2934: for(m=iagemin; m <= iagemax+3; m++)
2935: prop[i][m]=0;
1.126 brouard 2936:
2937: dateintsum=0;
2938: k2cpt=0;
2939: for (i=1; i<=imx; i++) {
2940: bool=1;
1.144 brouard 2941: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2942: for (z1=1; z1<=cptcoveff; z1++)
2943: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2944: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2945: bool=0;
1.145 brouard 2946: /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n",
2947: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2948: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2949: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2950: }
1.126 brouard 2951: }
1.144 brouard 2952:
1.126 brouard 2953: if (bool==1){
2954: for(m=firstpass; m<=lastpass; m++){
2955: k2=anint[m][i]+(mint[m][i]/12.);
2956: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2957: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2958: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2959: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2960: if (m<lastpass) {
2961: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2962: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2963: }
2964:
2965: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2966: dateintsum=dateintsum+k2;
2967: k2cpt++;
2968: }
2969: /*}*/
2970: }
2971: }
1.145 brouard 2972: } /* end i */
1.126 brouard 2973:
2974: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2975: pstamp(ficresp);
2976: if (cptcovn>0) {
2977: fprintf(ficresp, "\n#********** Variable ");
2978: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2979: fprintf(ficresp, "**********\n#");
1.143 brouard 2980: fprintf(ficlog, "\n#********** Variable ");
2981: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2982: fprintf(ficlog, "**********\n#");
1.126 brouard 2983: }
2984: for(i=1; i<=nlstate;i++)
2985: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2986: fprintf(ficresp, "\n");
2987:
2988: for(i=iagemin; i <= iagemax+3; i++){
2989: if(i==iagemax+3){
2990: fprintf(ficlog,"Total");
2991: }else{
2992: if(first==1){
2993: first=0;
2994: printf("See log file for details...\n");
2995: }
2996: fprintf(ficlog,"Age %d", i);
2997: }
2998: for(jk=1; jk <=nlstate ; jk++){
2999: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3000: pp[jk] += freq[jk][m][i];
3001: }
3002: for(jk=1; jk <=nlstate ; jk++){
3003: for(m=-1, pos=0; m <=0 ; m++)
3004: pos += freq[jk][m][i];
3005: if(pp[jk]>=1.e-10){
3006: if(first==1){
1.132 brouard 3007: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3008: }
3009: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3010: }else{
3011: if(first==1)
3012: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3013: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3014: }
3015: }
3016:
3017: for(jk=1; jk <=nlstate ; jk++){
3018: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3019: pp[jk] += freq[jk][m][i];
3020: }
3021: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3022: pos += pp[jk];
3023: posprop += prop[jk][i];
3024: }
3025: for(jk=1; jk <=nlstate ; jk++){
3026: if(pos>=1.e-5){
3027: if(first==1)
3028: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3029: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3030: }else{
3031: if(first==1)
3032: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3033: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3034: }
3035: if( i <= iagemax){
3036: if(pos>=1.e-5){
3037: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3038: /*probs[i][jk][j1]= pp[jk]/pos;*/
3039: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3040: }
3041: else
3042: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3043: }
3044: }
3045:
3046: for(jk=-1; jk <=nlstate+ndeath; jk++)
3047: for(m=-1; m <=nlstate+ndeath; m++)
3048: if(freq[jk][m][i] !=0 ) {
3049: if(first==1)
3050: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3051: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3052: }
3053: if(i <= iagemax)
3054: fprintf(ficresp,"\n");
3055: if(first==1)
3056: printf("Others in log...\n");
3057: fprintf(ficlog,"\n");
3058: }
1.145 brouard 3059: /*}*/
1.126 brouard 3060: }
3061: dateintmean=dateintsum/k2cpt;
3062:
3063: fclose(ficresp);
3064: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3065: free_vector(pp,1,nlstate);
3066: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3067: /* End of Freq */
3068: }
3069:
3070: /************ Prevalence ********************/
3071: 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)
3072: {
3073: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3074: in each health status at the date of interview (if between dateprev1 and dateprev2).
3075: We still use firstpass and lastpass as another selection.
3076: */
3077:
1.164 brouard 3078: int i, m, jk, j1, bool, z1,j;
3079:
3080: double **prop;
3081: double posprop;
1.126 brouard 3082: double y2; /* in fractional years */
3083: int iagemin, iagemax;
1.145 brouard 3084: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3085:
3086: iagemin= (int) agemin;
3087: iagemax= (int) agemax;
3088: /*pp=vector(1,nlstate);*/
3089: prop=matrix(1,nlstate,iagemin,iagemax+3);
3090: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3091: j1=0;
3092:
1.145 brouard 3093: /*j=cptcoveff;*/
1.126 brouard 3094: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3095:
1.145 brouard 3096: first=1;
3097: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3098: /*for(i1=1; i1<=ncodemax[k1];i1++){
3099: j1++;*/
1.126 brouard 3100:
3101: for (i=1; i<=nlstate; i++)
3102: for(m=iagemin; m <= iagemax+3; m++)
3103: prop[i][m]=0.0;
3104:
3105: for (i=1; i<=imx; i++) { /* Each individual */
3106: bool=1;
3107: if (cptcovn>0) {
3108: for (z1=1; z1<=cptcoveff; z1++)
3109: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
3110: bool=0;
3111: }
3112: if (bool==1) {
3113: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3114: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3115: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3116: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3117: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3118: 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);
3119: if (s[m][i]>0 && s[m][i]<=nlstate) {
3120: /*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]]);*/
3121: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3122: prop[s[m][i]][iagemax+3] += weight[i];
3123: }
3124: }
3125: } /* end selection of waves */
3126: }
3127: }
3128: for(i=iagemin; i <= iagemax+3; i++){
3129: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3130: posprop += prop[jk][i];
3131: }
1.145 brouard 3132:
1.126 brouard 3133: for(jk=1; jk <=nlstate ; jk++){
3134: if( i <= iagemax){
3135: if(posprop>=1.e-5){
3136: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3137: } else{
3138: if(first==1){
3139: first=0;
3140: 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]);
3141: }
3142: }
1.126 brouard 3143: }
3144: }/* end jk */
3145: }/* end i */
1.145 brouard 3146: /*} *//* end i1 */
3147: } /* end j1 */
1.126 brouard 3148:
3149: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3150: /*free_vector(pp,1,nlstate);*/
3151: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3152: } /* End of prevalence */
3153:
3154: /************* Waves Concatenation ***************/
3155:
3156: 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)
3157: {
3158: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3159: Death is a valid wave (if date is known).
3160: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3161: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3162: and mw[mi+1][i]. dh depends on stepm.
3163: */
3164:
3165: int i, mi, m;
3166: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3167: double sum=0., jmean=0.;*/
3168: int first;
3169: int j, k=0,jk, ju, jl;
3170: double sum=0.;
3171: first=0;
1.164 brouard 3172: jmin=100000;
1.126 brouard 3173: jmax=-1;
3174: jmean=0.;
3175: for(i=1; i<=imx; i++){
3176: mi=0;
3177: m=firstpass;
3178: while(s[m][i] <= nlstate){
3179: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3180: mw[++mi][i]=m;
3181: if(m >=lastpass)
3182: break;
3183: else
3184: m++;
3185: }/* end while */
3186: if (s[m][i] > nlstate){
3187: mi++; /* Death is another wave */
3188: /* if(mi==0) never been interviewed correctly before death */
3189: /* Only death is a correct wave */
3190: mw[mi][i]=m;
3191: }
3192:
3193: wav[i]=mi;
3194: if(mi==0){
3195: nbwarn++;
3196: if(first==0){
3197: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3198: first=1;
3199: }
3200: if(first==1){
3201: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3202: }
3203: } /* end mi==0 */
3204: } /* End individuals */
3205:
3206: for(i=1; i<=imx; i++){
3207: for(mi=1; mi<wav[i];mi++){
3208: if (stepm <=0)
3209: dh[mi][i]=1;
3210: else{
3211: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3212: if (agedc[i] < 2*AGESUP) {
3213: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3214: if(j==0) j=1; /* Survives at least one month after exam */
3215: else if(j<0){
3216: nberr++;
3217: 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]);
3218: j=1; /* Temporary Dangerous patch */
3219: 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);
3220: 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]);
3221: 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);
3222: }
3223: k=k+1;
3224: if (j >= jmax){
3225: jmax=j;
3226: ijmax=i;
3227: }
3228: if (j <= jmin){
3229: jmin=j;
3230: ijmin=i;
3231: }
3232: sum=sum+j;
3233: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3234: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3235: }
3236: }
3237: else{
3238: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3239: /* 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]); */
3240:
3241: k=k+1;
3242: if (j >= jmax) {
3243: jmax=j;
3244: ijmax=i;
3245: }
3246: else if (j <= jmin){
3247: jmin=j;
3248: ijmin=i;
3249: }
3250: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3251: /*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]);*/
3252: if(j<0){
3253: nberr++;
3254: 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]);
3255: 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]);
3256: }
3257: sum=sum+j;
3258: }
3259: jk= j/stepm;
3260: jl= j -jk*stepm;
3261: ju= j -(jk+1)*stepm;
3262: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3263: if(jl==0){
3264: dh[mi][i]=jk;
3265: bh[mi][i]=0;
3266: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3267: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3268: dh[mi][i]=jk+1;
3269: bh[mi][i]=ju;
3270: }
3271: }else{
3272: if(jl <= -ju){
3273: dh[mi][i]=jk;
3274: bh[mi][i]=jl; /* bias is positive if real duration
3275: * is higher than the multiple of stepm and negative otherwise.
3276: */
3277: }
3278: else{
3279: dh[mi][i]=jk+1;
3280: bh[mi][i]=ju;
3281: }
3282: if(dh[mi][i]==0){
3283: dh[mi][i]=1; /* At least one step */
3284: bh[mi][i]=ju; /* At least one step */
3285: /* 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);*/
3286: }
3287: } /* end if mle */
3288: }
3289: } /* end wave */
3290: }
3291: jmean=sum/k;
3292: 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 3293: 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 3294: }
3295:
3296: /*********** Tricode ****************************/
1.145 brouard 3297: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3298: {
1.144 brouard 3299: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3300: /* 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 3301: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3302: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3303: * nbcode[Tvar[j]][1]=
1.144 brouard 3304: */
1.130 brouard 3305:
1.145 brouard 3306: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3307: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3308: int cptcode=0; /* Modality max of covariates j */
3309: int modmincovj=0; /* Modality min of covariates j */
3310:
3311:
1.126 brouard 3312: cptcoveff=0;
3313:
1.144 brouard 3314: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3315:
1.145 brouard 3316: /* Loop on covariates without age and products */
1.186 brouard 3317: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 ! brouard 3318: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3319: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3320: modality of this covariate Vj*/
1.145 brouard 3321: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3322: * If product of Vn*Vm, still boolean *:
3323: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3324: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3325: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3326: modality of the nth covariate of individual i. */
1.145 brouard 3327: if (ij > modmaxcovj)
3328: modmaxcovj=ij;
3329: else if (ij < modmincovj)
3330: modmincovj=ij;
3331: if ((ij < -1) && (ij > NCOVMAX)){
3332: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3333: exit(1);
3334: }else
1.136 brouard 3335: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3336: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3337: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3338: /* getting the maximum value of the modality of the covariate
3339: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3340: female is 1, then modmaxcovj=1.*/
1.192 ! brouard 3341: } /* end for loop on individuals i */
1.145 brouard 3342: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 ! brouard 3343: 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 3344: cptcode=modmaxcovj;
1.137 brouard 3345: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3346: /*for (i=0; i<=cptcode; i++) {*/
1.192 ! brouard 3347: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
! 3348: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
! 3349: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
! 3350: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
! 3351: if( k != -1){
! 3352: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
! 3353: covariate for which somebody answered excluding
! 3354: undefined. Usually 2: 0 and 1. */
! 3355: }
! 3356: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
! 3357: covariate for which somebody answered including
! 3358: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3359: }
3360: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3361: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3362: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3363:
1.136 brouard 3364: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3365: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3366: 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 3367: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3368: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3369: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3370: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3371: nbcode[Tvar[j]][ij]=k;
3372: nbcode[Tvar[j]][1]=0;
3373: nbcode[Tvar[j]][2]=1;
3374: nbcode[Tvar[j]][3]=2;
3375: */
1.192 ! brouard 3376: ij=0; /* ij is similar to i but can jumps over null modalities */
! 3377: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 to 1*/
! 3378: if (Ndum[i] == 0) { /* If at least one individual responded to this modality k */
! 3379: break;
! 3380: }
! 3381: ij++;
! 3382: nbcode[Tvar[j]][ij]=i; /* stores the original modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
! 3383: cptcode = ij; /* New max modality for covar j */
! 3384: } /* end of loop on modality i=-1 to 1 or more */
! 3385:
! 3386: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
! 3387: /* /\*recode from 0 *\/ */
! 3388: /* k is a modality. If we have model=V1+V1*sex */
! 3389: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
! 3390: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
! 3391: /* } */
! 3392: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
! 3393: /* if (ij > ncodemax[j]) { */
! 3394: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
! 3395: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
! 3396: /* break; */
! 3397: /* } */
! 3398: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3399: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3400:
1.145 brouard 3401: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3402:
1.187 brouard 3403: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3404: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3405: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3406: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3407: }
1.126 brouard 3408:
1.192 ! brouard 3409: ij=0;
1.145 brouard 3410: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3411: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3412: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 ! brouard 3413: ij++;
1.145 brouard 3414: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3415: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 ! brouard 3416: }else{
! 3417: /* Tvaraff[ij]=0; */
! 3418: }
1.126 brouard 3419: }
1.192 ! brouard 3420: /* ij--; */
1.144 brouard 3421: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3422:
1.126 brouard 3423: }
3424:
1.145 brouard 3425:
1.126 brouard 3426: /*********** Health Expectancies ****************/
3427:
1.127 brouard 3428: 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 3429:
3430: {
3431: /* Health expectancies, no variances */
1.164 brouard 3432: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3433: int nhstepma, nstepma; /* Decreasing with age */
3434: double age, agelim, hf;
3435: double ***p3mat;
3436: double eip;
3437:
3438: pstamp(ficreseij);
3439: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3440: fprintf(ficreseij,"# Age");
3441: for(i=1; i<=nlstate;i++){
3442: for(j=1; j<=nlstate;j++){
3443: fprintf(ficreseij," e%1d%1d ",i,j);
3444: }
3445: fprintf(ficreseij," e%1d. ",i);
3446: }
3447: fprintf(ficreseij,"\n");
3448:
3449:
3450: if(estepm < stepm){
3451: printf ("Problem %d lower than %d\n",estepm, stepm);
3452: }
3453: else hstepm=estepm;
3454: /* We compute the life expectancy from trapezoids spaced every estepm months
3455: * This is mainly to measure the difference between two models: for example
3456: * if stepm=24 months pijx are given only every 2 years and by summing them
3457: * we are calculating an estimate of the Life Expectancy assuming a linear
3458: * progression in between and thus overestimating or underestimating according
3459: * to the curvature of the survival function. If, for the same date, we
3460: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3461: * to compare the new estimate of Life expectancy with the same linear
3462: * hypothesis. A more precise result, taking into account a more precise
3463: * curvature will be obtained if estepm is as small as stepm. */
3464:
3465: /* For example we decided to compute the life expectancy with the smallest unit */
3466: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3467: nhstepm is the number of hstepm from age to agelim
3468: nstepm is the number of stepm from age to agelin.
3469: Look at hpijx to understand the reason of that which relies in memory size
3470: and note for a fixed period like estepm months */
3471: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3472: survival function given by stepm (the optimization length). Unfortunately it
3473: means that if the survival funtion is printed only each two years of age and if
3474: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3475: results. So we changed our mind and took the option of the best precision.
3476: */
3477: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3478:
3479: agelim=AGESUP;
3480: /* If stepm=6 months */
3481: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3482: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3483:
3484: /* nhstepm age range expressed in number of stepm */
3485: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3486: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3487: /* if (stepm >= YEARM) hstepm=1;*/
3488: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3489: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3490:
3491: for (age=bage; age<=fage; age ++){
3492: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3493: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3494: /* if (stepm >= YEARM) hstepm=1;*/
3495: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3496:
3497: /* If stepm=6 months */
3498: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3499: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3500:
3501: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3502:
3503: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3504:
3505: printf("%d|",(int)age);fflush(stdout);
3506: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3507:
3508: /* Computing expectancies */
3509: for(i=1; i<=nlstate;i++)
3510: for(j=1; j<=nlstate;j++)
3511: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3512: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3513:
3514: /* 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]);*/
3515:
3516: }
3517:
3518: fprintf(ficreseij,"%3.0f",age );
3519: for(i=1; i<=nlstate;i++){
3520: eip=0;
3521: for(j=1; j<=nlstate;j++){
3522: eip +=eij[i][j][(int)age];
3523: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3524: }
3525: fprintf(ficreseij,"%9.4f", eip );
3526: }
3527: fprintf(ficreseij,"\n");
3528:
3529: }
3530: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3531: printf("\n");
3532: fprintf(ficlog,"\n");
3533:
3534: }
3535:
1.127 brouard 3536: 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 3537:
3538: {
3539: /* Covariances of health expectancies eij and of total life expectancies according
3540: to initial status i, ei. .
3541: */
3542: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3543: int nhstepma, nstepma; /* Decreasing with age */
3544: double age, agelim, hf;
3545: double ***p3matp, ***p3matm, ***varhe;
3546: double **dnewm,**doldm;
3547: double *xp, *xm;
3548: double **gp, **gm;
3549: double ***gradg, ***trgradg;
3550: int theta;
3551:
3552: double eip, vip;
3553:
3554: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3555: xp=vector(1,npar);
3556: xm=vector(1,npar);
3557: dnewm=matrix(1,nlstate*nlstate,1,npar);
3558: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3559:
3560: pstamp(ficresstdeij);
3561: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3562: fprintf(ficresstdeij,"# Age");
3563: for(i=1; i<=nlstate;i++){
3564: for(j=1; j<=nlstate;j++)
3565: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3566: fprintf(ficresstdeij," e%1d. ",i);
3567: }
3568: fprintf(ficresstdeij,"\n");
3569:
3570: pstamp(ficrescveij);
3571: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3572: fprintf(ficrescveij,"# Age");
3573: for(i=1; i<=nlstate;i++)
3574: for(j=1; j<=nlstate;j++){
3575: cptj= (j-1)*nlstate+i;
3576: for(i2=1; i2<=nlstate;i2++)
3577: for(j2=1; j2<=nlstate;j2++){
3578: cptj2= (j2-1)*nlstate+i2;
3579: if(cptj2 <= cptj)
3580: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3581: }
3582: }
3583: fprintf(ficrescveij,"\n");
3584:
3585: if(estepm < stepm){
3586: printf ("Problem %d lower than %d\n",estepm, stepm);
3587: }
3588: else hstepm=estepm;
3589: /* We compute the life expectancy from trapezoids spaced every estepm months
3590: * This is mainly to measure the difference between two models: for example
3591: * if stepm=24 months pijx are given only every 2 years and by summing them
3592: * we are calculating an estimate of the Life Expectancy assuming a linear
3593: * progression in between and thus overestimating or underestimating according
3594: * to the curvature of the survival function. If, for the same date, we
3595: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3596: * to compare the new estimate of Life expectancy with the same linear
3597: * hypothesis. A more precise result, taking into account a more precise
3598: * curvature will be obtained if estepm is as small as stepm. */
3599:
3600: /* For example we decided to compute the life expectancy with the smallest unit */
3601: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3602: nhstepm is the number of hstepm from age to agelim
3603: nstepm is the number of stepm from age to agelin.
3604: Look at hpijx to understand the reason of that which relies in memory size
3605: and note for a fixed period like estepm months */
3606: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3607: survival function given by stepm (the optimization length). Unfortunately it
3608: means that if the survival funtion is printed only each two years of age and if
3609: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3610: results. So we changed our mind and took the option of the best precision.
3611: */
3612: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3613:
3614: /* If stepm=6 months */
3615: /* nhstepm age range expressed in number of stepm */
3616: agelim=AGESUP;
3617: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3618: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3619: /* if (stepm >= YEARM) hstepm=1;*/
3620: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3621:
3622: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3623: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3624: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3625: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3626: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3627: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3628:
3629: for (age=bage; age<=fage; age ++){
3630: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3631: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3632: /* if (stepm >= YEARM) hstepm=1;*/
3633: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3634:
3635: /* If stepm=6 months */
3636: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3637: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3638:
3639: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3640:
3641: /* Computing Variances of health expectancies */
3642: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3643: decrease memory allocation */
3644: for(theta=1; theta <=npar; theta++){
3645: for(i=1; i<=npar; i++){
3646: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3647: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3648: }
3649: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3650: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3651:
3652: for(j=1; j<= nlstate; j++){
3653: for(i=1; i<=nlstate; i++){
3654: for(h=0; h<=nhstepm-1; h++){
3655: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3656: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3657: }
3658: }
3659: }
3660:
3661: for(ij=1; ij<= nlstate*nlstate; ij++)
3662: for(h=0; h<=nhstepm-1; h++){
3663: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3664: }
3665: }/* End theta */
3666:
3667:
3668: for(h=0; h<=nhstepm-1; h++)
3669: for(j=1; j<=nlstate*nlstate;j++)
3670: for(theta=1; theta <=npar; theta++)
3671: trgradg[h][j][theta]=gradg[h][theta][j];
3672:
3673:
3674: for(ij=1;ij<=nlstate*nlstate;ij++)
3675: for(ji=1;ji<=nlstate*nlstate;ji++)
3676: varhe[ij][ji][(int)age] =0.;
3677:
3678: printf("%d|",(int)age);fflush(stdout);
3679: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3680: for(h=0;h<=nhstepm-1;h++){
3681: for(k=0;k<=nhstepm-1;k++){
3682: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3683: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3684: for(ij=1;ij<=nlstate*nlstate;ij++)
3685: for(ji=1;ji<=nlstate*nlstate;ji++)
3686: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3687: }
3688: }
3689:
3690: /* Computing expectancies */
3691: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3692: for(i=1; i<=nlstate;i++)
3693: for(j=1; j<=nlstate;j++)
3694: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3695: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3696:
3697: /* 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]);*/
3698:
3699: }
3700:
3701: fprintf(ficresstdeij,"%3.0f",age );
3702: for(i=1; i<=nlstate;i++){
3703: eip=0.;
3704: vip=0.;
3705: for(j=1; j<=nlstate;j++){
3706: eip += eij[i][j][(int)age];
3707: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3708: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3709: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3710: }
3711: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3712: }
3713: fprintf(ficresstdeij,"\n");
3714:
3715: fprintf(ficrescveij,"%3.0f",age );
3716: for(i=1; i<=nlstate;i++)
3717: for(j=1; j<=nlstate;j++){
3718: cptj= (j-1)*nlstate+i;
3719: for(i2=1; i2<=nlstate;i2++)
3720: for(j2=1; j2<=nlstate;j2++){
3721: cptj2= (j2-1)*nlstate+i2;
3722: if(cptj2 <= cptj)
3723: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3724: }
3725: }
3726: fprintf(ficrescveij,"\n");
3727:
3728: }
3729: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3730: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3731: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3732: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3733: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3734: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3735: printf("\n");
3736: fprintf(ficlog,"\n");
3737:
3738: free_vector(xm,1,npar);
3739: free_vector(xp,1,npar);
3740: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3741: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3742: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3743: }
3744:
3745: /************ Variance ******************/
3746: 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[])
3747: {
3748: /* Variance of health expectancies */
3749: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3750: /* double **newm;*/
1.169 brouard 3751: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3752:
3753: int movingaverage();
1.126 brouard 3754: double **dnewm,**doldm;
3755: double **dnewmp,**doldmp;
3756: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3757: int k;
1.126 brouard 3758: double *xp;
3759: double **gp, **gm; /* for var eij */
3760: double ***gradg, ***trgradg; /*for var eij */
3761: double **gradgp, **trgradgp; /* for var p point j */
3762: double *gpp, *gmp; /* for var p point j */
3763: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3764: double ***p3mat;
3765: double age,agelim, hf;
3766: double ***mobaverage;
3767: int theta;
3768: char digit[4];
3769: char digitp[25];
3770:
3771: char fileresprobmorprev[FILENAMELENGTH];
3772:
3773: if(popbased==1){
3774: if(mobilav!=0)
3775: strcpy(digitp,"-populbased-mobilav-");
3776: else strcpy(digitp,"-populbased-nomobil-");
3777: }
3778: else
3779: strcpy(digitp,"-stablbased-");
3780:
3781: if (mobilav!=0) {
3782: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3783: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3784: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3785: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3786: }
3787: }
3788:
3789: strcpy(fileresprobmorprev,"prmorprev");
3790: sprintf(digit,"%-d",ij);
3791: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3792: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3793: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3794: strcat(fileresprobmorprev,fileres);
3795: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3796: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3797: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3798: }
3799: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3800:
3801: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3802: pstamp(ficresprobmorprev);
3803: 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);
3804: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3805: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3806: fprintf(ficresprobmorprev," p.%-d SE",j);
3807: for(i=1; i<=nlstate;i++)
3808: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3809: }
3810: fprintf(ficresprobmorprev,"\n");
3811: fprintf(ficgp,"\n# Routine varevsij");
3812: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3813: 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");
3814: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3815: /* } */
3816: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3817: pstamp(ficresvij);
3818: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3819: if(popbased==1)
1.128 brouard 3820: 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 3821: else
3822: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3823: fprintf(ficresvij,"# Age");
3824: for(i=1; i<=nlstate;i++)
3825: for(j=1; j<=nlstate;j++)
3826: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3827: fprintf(ficresvij,"\n");
3828:
3829: xp=vector(1,npar);
3830: dnewm=matrix(1,nlstate,1,npar);
3831: doldm=matrix(1,nlstate,1,nlstate);
3832: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3833: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3834:
3835: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3836: gpp=vector(nlstate+1,nlstate+ndeath);
3837: gmp=vector(nlstate+1,nlstate+ndeath);
3838: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3839:
3840: if(estepm < stepm){
3841: printf ("Problem %d lower than %d\n",estepm, stepm);
3842: }
3843: else hstepm=estepm;
3844: /* For example we decided to compute the life expectancy with the smallest unit */
3845: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3846: nhstepm is the number of hstepm from age to agelim
3847: nstepm is the number of stepm from age to agelin.
1.128 brouard 3848: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3849: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3850: survival function given by stepm (the optimization length). Unfortunately it
3851: means that if the survival funtion is printed every two years of age and if
3852: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3853: results. So we changed our mind and took the option of the best precision.
3854: */
3855: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3856: agelim = AGESUP;
3857: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3858: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3859: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3860: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3861: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3862: gp=matrix(0,nhstepm,1,nlstate);
3863: gm=matrix(0,nhstepm,1,nlstate);
3864:
3865:
3866: for(theta=1; theta <=npar; theta++){
3867: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3868: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3869: }
3870: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3871: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3872:
3873: if (popbased==1) {
3874: if(mobilav ==0){
3875: for(i=1; i<=nlstate;i++)
3876: prlim[i][i]=probs[(int)age][i][ij];
3877: }else{ /* mobilav */
3878: for(i=1; i<=nlstate;i++)
3879: prlim[i][i]=mobaverage[(int)age][i][ij];
3880: }
3881: }
3882:
3883: for(j=1; j<= nlstate; j++){
3884: for(h=0; h<=nhstepm; h++){
3885: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3886: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3887: }
3888: }
3889: /* This for computing probability of death (h=1 means
3890: computed over hstepm matrices product = hstepm*stepm months)
3891: as a weighted average of prlim.
3892: */
3893: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3894: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3895: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3896: }
3897: /* end probability of death */
3898:
3899: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3900: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3901: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3902: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3903:
3904: if (popbased==1) {
3905: if(mobilav ==0){
3906: for(i=1; i<=nlstate;i++)
3907: prlim[i][i]=probs[(int)age][i][ij];
3908: }else{ /* mobilav */
3909: for(i=1; i<=nlstate;i++)
3910: prlim[i][i]=mobaverage[(int)age][i][ij];
3911: }
3912: }
3913:
1.128 brouard 3914: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3915: for(h=0; h<=nhstepm; h++){
3916: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3917: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3918: }
3919: }
3920: /* This for computing probability of death (h=1 means
3921: computed over hstepm matrices product = hstepm*stepm months)
3922: as a weighted average of prlim.
3923: */
3924: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3925: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3926: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3927: }
3928: /* end probability of death */
3929:
3930: for(j=1; j<= nlstate; j++) /* vareij */
3931: for(h=0; h<=nhstepm; h++){
3932: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3933: }
3934:
3935: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3936: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3937: }
3938:
3939: } /* End theta */
3940:
3941: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3942:
3943: for(h=0; h<=nhstepm; h++) /* veij */
3944: for(j=1; j<=nlstate;j++)
3945: for(theta=1; theta <=npar; theta++)
3946: trgradg[h][j][theta]=gradg[h][theta][j];
3947:
3948: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3949: for(theta=1; theta <=npar; theta++)
3950: trgradgp[j][theta]=gradgp[theta][j];
3951:
3952:
3953: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3954: for(i=1;i<=nlstate;i++)
3955: for(j=1;j<=nlstate;j++)
3956: vareij[i][j][(int)age] =0.;
3957:
3958: for(h=0;h<=nhstepm;h++){
3959: for(k=0;k<=nhstepm;k++){
3960: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3961: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3962: for(i=1;i<=nlstate;i++)
3963: for(j=1;j<=nlstate;j++)
3964: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3965: }
3966: }
3967:
3968: /* pptj */
3969: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3970: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3971: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3972: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3973: varppt[j][i]=doldmp[j][i];
3974: /* end ppptj */
3975: /* x centered again */
3976: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3977: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3978:
3979: if (popbased==1) {
3980: if(mobilav ==0){
3981: for(i=1; i<=nlstate;i++)
3982: prlim[i][i]=probs[(int)age][i][ij];
3983: }else{ /* mobilav */
3984: for(i=1; i<=nlstate;i++)
3985: prlim[i][i]=mobaverage[(int)age][i][ij];
3986: }
3987: }
3988:
3989: /* This for computing probability of death (h=1 means
3990: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3991: as a weighted average of prlim.
3992: */
3993: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3994: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3995: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3996: }
3997: /* end probability of death */
3998:
3999: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4000: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4001: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4002: for(i=1; i<=nlstate;i++){
4003: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4004: }
4005: }
4006: fprintf(ficresprobmorprev,"\n");
4007:
4008: fprintf(ficresvij,"%.0f ",age );
4009: for(i=1; i<=nlstate;i++)
4010: for(j=1; j<=nlstate;j++){
4011: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4012: }
4013: fprintf(ficresvij,"\n");
4014: free_matrix(gp,0,nhstepm,1,nlstate);
4015: free_matrix(gm,0,nhstepm,1,nlstate);
4016: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4017: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4018: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4019: } /* End age */
4020: free_vector(gpp,nlstate+1,nlstate+ndeath);
4021: free_vector(gmp,nlstate+1,nlstate+ndeath);
4022: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4023: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 4024: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 4025: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4026: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 4027: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4028: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4029: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4030: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4031: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4032: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4033: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4034: 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);
4035: /* 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);
4036: */
4037: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
4038: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4039:
4040: free_vector(xp,1,npar);
4041: free_matrix(doldm,1,nlstate,1,nlstate);
4042: free_matrix(dnewm,1,nlstate,1,npar);
4043: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4044: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4045: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4046: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4047: fclose(ficresprobmorprev);
4048: fflush(ficgp);
4049: fflush(fichtm);
4050: } /* end varevsij */
4051:
4052: /************ Variance of prevlim ******************/
4053: 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[])
4054: {
4055: /* Variance of prevalence limit */
4056: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4057:
1.126 brouard 4058: double **dnewm,**doldm;
4059: int i, j, nhstepm, hstepm;
4060: double *xp;
4061: double *gp, *gm;
4062: double **gradg, **trgradg;
4063: double age,agelim;
4064: int theta;
4065:
4066: pstamp(ficresvpl);
4067: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4068: fprintf(ficresvpl,"# Age");
4069: for(i=1; i<=nlstate;i++)
4070: fprintf(ficresvpl," %1d-%1d",i,i);
4071: fprintf(ficresvpl,"\n");
4072:
4073: xp=vector(1,npar);
4074: dnewm=matrix(1,nlstate,1,npar);
4075: doldm=matrix(1,nlstate,1,nlstate);
4076:
4077: hstepm=1*YEARM; /* Every year of age */
4078: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4079: agelim = AGESUP;
4080: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4081: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4082: if (stepm >= YEARM) hstepm=1;
4083: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4084: gradg=matrix(1,npar,1,nlstate);
4085: gp=vector(1,nlstate);
4086: gm=vector(1,nlstate);
4087:
4088: for(theta=1; theta <=npar; theta++){
4089: for(i=1; i<=npar; i++){ /* Computes gradient */
4090: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4091: }
4092: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4093: for(i=1;i<=nlstate;i++)
4094: gp[i] = prlim[i][i];
4095:
4096: for(i=1; i<=npar; i++) /* Computes gradient */
4097: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4098: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4099: for(i=1;i<=nlstate;i++)
4100: gm[i] = prlim[i][i];
4101:
4102: for(i=1;i<=nlstate;i++)
4103: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4104: } /* End theta */
4105:
4106: trgradg =matrix(1,nlstate,1,npar);
4107:
4108: for(j=1; j<=nlstate;j++)
4109: for(theta=1; theta <=npar; theta++)
4110: trgradg[j][theta]=gradg[theta][j];
4111:
4112: for(i=1;i<=nlstate;i++)
4113: varpl[i][(int)age] =0.;
4114: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4115: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4116: for(i=1;i<=nlstate;i++)
4117: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4118:
4119: fprintf(ficresvpl,"%.0f ",age );
4120: for(i=1; i<=nlstate;i++)
4121: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4122: fprintf(ficresvpl,"\n");
4123: free_vector(gp,1,nlstate);
4124: free_vector(gm,1,nlstate);
4125: free_matrix(gradg,1,npar,1,nlstate);
4126: free_matrix(trgradg,1,nlstate,1,npar);
4127: } /* End age */
4128:
4129: free_vector(xp,1,npar);
4130: free_matrix(doldm,1,nlstate,1,npar);
4131: free_matrix(dnewm,1,nlstate,1,nlstate);
4132:
4133: }
4134:
4135: /************ Variance of one-step probabilities ******************/
4136: 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[])
4137: {
1.164 brouard 4138: int i, j=0, k1, l1, tj;
1.126 brouard 4139: int k2, l2, j1, z1;
1.164 brouard 4140: int k=0, l;
1.145 brouard 4141: int first=1, first1, first2;
1.126 brouard 4142: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4143: double **dnewm,**doldm;
4144: double *xp;
4145: double *gp, *gm;
4146: double **gradg, **trgradg;
4147: double **mu;
1.164 brouard 4148: double age, cov[NCOVMAX+1];
1.126 brouard 4149: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4150: int theta;
4151: char fileresprob[FILENAMELENGTH];
4152: char fileresprobcov[FILENAMELENGTH];
4153: char fileresprobcor[FILENAMELENGTH];
4154: double ***varpij;
4155:
4156: strcpy(fileresprob,"prob");
4157: strcat(fileresprob,fileres);
4158: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4159: printf("Problem with resultfile: %s\n", fileresprob);
4160: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4161: }
4162: strcpy(fileresprobcov,"probcov");
4163: strcat(fileresprobcov,fileres);
4164: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4165: printf("Problem with resultfile: %s\n", fileresprobcov);
4166: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4167: }
4168: strcpy(fileresprobcor,"probcor");
4169: strcat(fileresprobcor,fileres);
4170: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4171: printf("Problem with resultfile: %s\n", fileresprobcor);
4172: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4173: }
4174: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4175: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4176: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4177: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4178: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4179: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4180: pstamp(ficresprob);
4181: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4182: fprintf(ficresprob,"# Age");
4183: pstamp(ficresprobcov);
4184: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4185: fprintf(ficresprobcov,"# Age");
4186: pstamp(ficresprobcor);
4187: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4188: fprintf(ficresprobcor,"# Age");
4189:
4190:
4191: for(i=1; i<=nlstate;i++)
4192: for(j=1; j<=(nlstate+ndeath);j++){
4193: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4194: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4195: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4196: }
4197: /* fprintf(ficresprob,"\n");
4198: fprintf(ficresprobcov,"\n");
4199: fprintf(ficresprobcor,"\n");
4200: */
1.131 brouard 4201: xp=vector(1,npar);
1.126 brouard 4202: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4203: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4204: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4205: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4206: first=1;
4207: fprintf(ficgp,"\n# Routine varprob");
4208: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4209: fprintf(fichtm,"\n");
4210:
4211: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
4212: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
4213: file %s<br>\n",optionfilehtmcov);
4214: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
4215: and drawn. It helps understanding how is the covariance between two incidences.\
4216: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4217: 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. \
4218: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4219: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4220: standard deviations wide on each axis. <br>\
4221: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4222: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4223: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4224:
4225: cov[1]=1;
1.145 brouard 4226: /* tj=cptcoveff; */
4227: tj = (int) pow(2,cptcoveff);
1.126 brouard 4228: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4229: j1=0;
1.145 brouard 4230: for(j1=1; j1<=tj;j1++){
4231: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4232: /*j1++;*/
1.126 brouard 4233: if (cptcovn>0) {
4234: fprintf(ficresprob, "\n#********** Variable ");
4235: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4236: fprintf(ficresprob, "**********\n#\n");
4237: fprintf(ficresprobcov, "\n#********** Variable ");
4238: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4239: fprintf(ficresprobcov, "**********\n#\n");
4240:
4241: fprintf(ficgp, "\n#********** Variable ");
4242: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4243: fprintf(ficgp, "**********\n#\n");
4244:
4245:
4246: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4247: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4248: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4249:
4250: fprintf(ficresprobcor, "\n#********** Variable ");
4251: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4252: fprintf(ficresprobcor, "**********\n#");
4253: }
4254:
1.145 brouard 4255: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4256: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4257: gp=vector(1,(nlstate)*(nlstate+ndeath));
4258: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4259: for (age=bage; age<=fage; age ++){
4260: cov[2]=age;
1.187 brouard 4261: if(nagesqr==1)
4262: cov[3]= age*age;
1.126 brouard 4263: for (k=1; k<=cptcovn;k++) {
1.187 brouard 4264: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145 brouard 4265: * 1 1 1 1 1
4266: * 2 2 1 1 1
4267: * 3 1 2 1 1
4268: */
4269: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4270: }
1.186 brouard 4271: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4272: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126 brouard 4273: for (k=1; k<=cptcovprod;k++)
1.187 brouard 4274: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126 brouard 4275:
4276:
4277: for(theta=1; theta <=npar; theta++){
4278: for(i=1; i<=npar; i++)
4279: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4280:
4281: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4282:
4283: k=0;
4284: for(i=1; i<= (nlstate); i++){
4285: for(j=1; j<=(nlstate+ndeath);j++){
4286: k=k+1;
4287: gp[k]=pmmij[i][j];
4288: }
4289: }
4290:
4291: for(i=1; i<=npar; i++)
4292: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4293:
4294: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4295: k=0;
4296: for(i=1; i<=(nlstate); i++){
4297: for(j=1; j<=(nlstate+ndeath);j++){
4298: k=k+1;
4299: gm[k]=pmmij[i][j];
4300: }
4301: }
4302:
4303: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4304: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4305: }
4306:
4307: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4308: for(theta=1; theta <=npar; theta++)
4309: trgradg[j][theta]=gradg[theta][j];
4310:
4311: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4312: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4313:
4314: pmij(pmmij,cov,ncovmodel,x,nlstate);
4315:
4316: k=0;
4317: for(i=1; i<=(nlstate); i++){
4318: for(j=1; j<=(nlstate+ndeath);j++){
4319: k=k+1;
4320: mu[k][(int) age]=pmmij[i][j];
4321: }
4322: }
4323: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4324: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4325: varpij[i][j][(int)age] = doldm[i][j];
4326:
4327: /*printf("\n%d ",(int)age);
4328: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4329: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4330: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4331: }*/
4332:
4333: fprintf(ficresprob,"\n%d ",(int)age);
4334: fprintf(ficresprobcov,"\n%d ",(int)age);
4335: fprintf(ficresprobcor,"\n%d ",(int)age);
4336:
4337: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4338: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4339: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4340: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4341: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4342: }
4343: i=0;
4344: for (k=1; k<=(nlstate);k++){
4345: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4346: i++;
1.126 brouard 4347: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4348: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4349: for (j=1; j<=i;j++){
1.145 brouard 4350: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4351: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4352: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4353: }
4354: }
4355: }/* end of loop for state */
4356: } /* end of loop for age */
1.145 brouard 4357: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4358: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4359: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4360: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4361:
1.126 brouard 4362: /* Confidence intervalle of pij */
4363: /*
1.131 brouard 4364: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4365: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4366: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4367: 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);
4368: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4369: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4370: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4371: */
4372:
4373: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4374: first1=1;first2=2;
1.126 brouard 4375: for (k2=1; k2<=(nlstate);k2++){
4376: for (l2=1; l2<=(nlstate+ndeath);l2++){
4377: if(l2==k2) continue;
4378: j=(k2-1)*(nlstate+ndeath)+l2;
4379: for (k1=1; k1<=(nlstate);k1++){
4380: for (l1=1; l1<=(nlstate+ndeath);l1++){
4381: if(l1==k1) continue;
4382: i=(k1-1)*(nlstate+ndeath)+l1;
4383: if(i<=j) continue;
4384: for (age=bage; age<=fage; age ++){
4385: if ((int)age %5==0){
4386: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4387: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4388: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4389: mu1=mu[i][(int) age]/stepm*YEARM ;
4390: mu2=mu[j][(int) age]/stepm*YEARM;
4391: c12=cv12/sqrt(v1*v2);
4392: /* Computing eigen value of matrix of covariance */
4393: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4394: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4395: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4396: if(first2==1){
4397: first1=0;
4398: 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);
4399: }
4400: 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);
4401: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4402: /* lc2=fabs(lc2); */
1.135 brouard 4403: }
4404:
1.126 brouard 4405: /* Eigen vectors */
4406: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4407: /*v21=sqrt(1.-v11*v11); *//* error */
4408: v21=(lc1-v1)/cv12*v11;
4409: v12=-v21;
4410: v22=v11;
4411: tnalp=v21/v11;
4412: if(first1==1){
4413: first1=0;
4414: 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);
4415: }
4416: 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);
4417: /*printf(fignu*/
4418: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4419: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4420: if(first==1){
4421: first=0;
4422: fprintf(ficgp,"\nset parametric;unset label");
4423: 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 4424: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4425: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4426: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4427: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4428: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4429: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4430: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4431: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4432: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4433: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4434: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4435: 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",\
4436: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4437: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4438: }else{
4439: first=0;
4440: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4441: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4442: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4443: 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",\
4444: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4445: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4446: }/* if first */
4447: } /* age mod 5 */
4448: } /* end loop age */
4449: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4450: first=1;
4451: } /*l12 */
4452: } /* k12 */
4453: } /*l1 */
4454: }/* k1 */
1.169 brouard 4455: /* } */ /* loop covariates */
1.126 brouard 4456: }
4457: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4458: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4459: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4460: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4461: free_vector(xp,1,npar);
4462: fclose(ficresprob);
4463: fclose(ficresprobcov);
4464: fclose(ficresprobcor);
4465: fflush(ficgp);
4466: fflush(fichtmcov);
4467: }
4468:
4469:
4470: /******************* Printing html file ***********/
4471: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4472: int lastpass, int stepm, int weightopt, char model[],\
4473: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4474: int popforecast, int estepm ,\
4475: double jprev1, double mprev1,double anprev1, \
4476: double jprev2, double mprev2,double anprev2){
4477: int jj1, k1, i1, cpt;
4478:
4479: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4480: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4481: </ul>");
4482: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4483: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4484: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4485: fprintf(fichtm,"\
4486: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4487: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4488: fprintf(fichtm,"\
4489: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4490: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4491: fprintf(fichtm,"\
1.128 brouard 4492: - (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 4493: <a href=\"%s\">%s</a> <br>\n",
4494: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4495: fprintf(fichtm,"\
4496: - Population projections by age and states: \
4497: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4498:
4499: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4500:
1.145 brouard 4501: m=pow(2,cptcoveff);
1.126 brouard 4502: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4503:
4504: jj1=0;
4505: for(k1=1; k1<=m;k1++){
1.192 ! brouard 4506: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4507: jj1++;
4508: if (cptcovn > 0) {
4509: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 ! brouard 4510: for (cpt=1; cpt<=cptcoveff;cpt++){
1.126 brouard 4511: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
1.192 ! brouard 4512: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
! 4513: }
1.126 brouard 4514: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4515: }
4516: /* Pij */
1.145 brouard 4517: 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> \
4518: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4519: /* Quasi-incidences */
4520: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4521: 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> \
4522: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4523: /* Period (stable) prevalence in each health state */
1.154 brouard 4524: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4525: 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> \
4526: <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 4527: }
4528: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4529: 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> \
4530: <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 4531: }
1.192 ! brouard 4532: /* } /\* end i1 *\/ */
1.126 brouard 4533: }/* End k1 */
4534: fprintf(fichtm,"</ul>");
4535:
4536:
4537: fprintf(fichtm,"\
4538: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4539: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4540:
4541: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4542: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4543: fprintf(fichtm,"\
4544: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4545: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4546:
4547: fprintf(fichtm,"\
4548: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4549: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4550: fprintf(fichtm,"\
4551: - 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): \
4552: <a href=\"%s\">%s</a> <br>\n</li>",
4553: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4554: fprintf(fichtm,"\
4555: - (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): \
4556: <a href=\"%s\">%s</a> <br>\n</li>",
4557: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4558: fprintf(fichtm,"\
1.128 brouard 4559: - 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 4560: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4561: fprintf(fichtm,"\
1.128 brouard 4562: - 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",
4563: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4564: fprintf(fichtm,"\
4565: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4566: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4567:
4568: /* if(popforecast==1) fprintf(fichtm,"\n */
4569: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4570: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4571: /* <br>",fileres,fileres,fileres,fileres); */
4572: /* else */
4573: /* 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); */
4574: fflush(fichtm);
4575: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4576:
1.145 brouard 4577: m=pow(2,cptcoveff);
1.126 brouard 4578: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4579:
4580: jj1=0;
4581: for(k1=1; k1<=m;k1++){
1.192 ! brouard 4582: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4583: jj1++;
4584: if (cptcovn > 0) {
4585: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4586: for (cpt=1; cpt<=cptcoveff;cpt++)
4587: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4588: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4589: }
4590: for(cpt=1; cpt<=nlstate;cpt++) {
4591: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4592: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4593: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4594: }
4595: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4596: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4597: true period expectancies (those weighted with period prevalences are also\
4598: drawn in addition to the population based expectancies computed using\
4599: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4600: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192 ! brouard 4601: /* } /\* end i1 *\/ */
1.126 brouard 4602: }/* End k1 */
4603: fprintf(fichtm,"</ul>");
4604: fflush(fichtm);
4605: }
4606:
4607: /******************* Gnuplot file **************/
4608: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4609:
4610: char dirfileres[132],optfileres[132];
1.164 brouard 4611: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4612: int ng=0;
1.126 brouard 4613: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4614: /* printf("Problem with file %s",optionfilegnuplot); */
4615: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4616: /* } */
4617:
4618: /*#ifdef windows */
4619: fprintf(ficgp,"cd \"%s\" \n",pathc);
4620: /*#endif */
4621: m=pow(2,cptcoveff);
4622:
4623: strcpy(dirfileres,optionfilefiname);
4624: strcpy(optfileres,"vpl");
4625: /* 1eme*/
1.153 brouard 4626: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4627: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4628: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4629: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4630: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4631: fprintf(ficgp,"set xlabel \"Age\" \n\
4632: set ylabel \"Probability\" \n\
1.145 brouard 4633: set ter png small size 320, 240\n\
1.170 brouard 4634: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4635:
4636: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4637: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4638: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4639: }
1.170 brouard 4640: 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 4641: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4642: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4643: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4644: }
1.170 brouard 4645: 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 4646: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4647: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4648: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4649: }
1.145 brouard 4650: 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 4651: }
4652: }
4653: /*2 eme*/
1.153 brouard 4654: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4655: for (k1=1; k1<= m ; k1 ++) {
4656: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4657: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4658:
4659: for (i=1; i<= nlstate+1 ; i ++) {
4660: k=2*i;
1.170 brouard 4661: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4662: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4663: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4664: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4665: }
4666: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4667: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4668: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4669: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4670: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4671: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4672: }
1.145 brouard 4673: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4674: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4675: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4676: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4677: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4678: }
1.145 brouard 4679: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4680: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4681: }
4682: }
4683:
4684: /*3eme*/
4685:
4686: for (k1=1; k1<= m ; k1 ++) {
4687: for (cpt=1; cpt<= nlstate ; cpt ++) {
4688: /* k=2+nlstate*(2*cpt-2); */
4689: k=2+(nlstate+1)*(cpt-1);
4690: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4691: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4692: 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);
4693: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4694: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4695: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4696: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4697: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4698: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4699:
4700: */
4701: for (i=1; i< nlstate ; i ++) {
4702: 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);
4703: /* 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);*/
4704:
4705: }
4706: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4707: }
4708: }
4709:
4710: /* CV preval stable (period) */
1.153 brouard 4711: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4712: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4713: k=3;
1.153 brouard 4714: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4715: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4716: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4717: set ter png small size 320, 240\n\
1.126 brouard 4718: unset log y\n\
1.153 brouard 4719: plot [%.f:%.f] ", ageminpar, agemaxpar);
4720: for (i=1; i<= nlstate ; i ++){
4721: if(i==1)
4722: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4723: else
4724: fprintf(ficgp,", '' ");
1.154 brouard 4725: l=(nlstate+ndeath)*(i-1)+1;
4726: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4727: for (j=1; j<= (nlstate-1) ; j ++)
4728: fprintf(ficgp,"+$%d",k+l+j);
4729: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4730: } /* nlstate */
4731: fprintf(ficgp,"\n");
4732: } /* end cpt state*/
4733: } /* end covariate */
1.126 brouard 4734:
4735: /* proba elementaires */
1.187 brouard 4736: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 4737: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 4738: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 4739: for(k=1; k <=(nlstate+ndeath); k++){
4740: if (k != i) {
1.187 brouard 4741: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 4742: for(j=1; j <=ncovmodel; j++){
1.187 brouard 4743: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 4744: jk++;
4745: }
1.187 brouard 4746: fprintf(ficgp,"\n");
1.126 brouard 4747: }
4748: }
4749: }
1.187 brouard 4750: fprintf(ficgp,"##############\n#\n");
4751:
1.145 brouard 4752: /*goto avoid;*/
1.187 brouard 4753: fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
4754: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4755: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4756: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4757: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4758: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4759: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4760: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4761: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4762: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4763: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4764: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4765: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4766: fprintf(ficgp,"#\n");
1.126 brouard 4767: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187 brouard 4768: fprintf(ficgp,"# ng=%d\n",ng);
4769: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 4770: for(jk=1; jk <=m; jk++) {
1.187 brouard 4771: fprintf(ficgp,"# jk=%d\n",jk);
1.145 brouard 4772: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4773: if (ng==2)
4774: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4775: else
4776: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4777: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4778: i=1;
4779: for(k2=1; k2<=nlstate; k2++) {
4780: k3=i;
4781: for(k=1; k<=(nlstate+ndeath); k++) {
4782: if (k != k2){
4783: if(ng==2)
1.187 brouard 4784: if(nagesqr==0)
4785: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4786: else /* nagesqr =1 */
4787: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126 brouard 4788: else
1.187 brouard 4789: if(nagesqr==0)
4790: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4791: else /* nagesqr =1 */
4792: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141 brouard 4793: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 4794: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186 brouard 4795: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187 brouard 4796: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186 brouard 4797: ij++;
4798: }
4799: else
1.187 brouard 4800: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4801: }
4802: fprintf(ficgp,")/(1");
4803:
1.187 brouard 4804: for(k1=1; k1 <=nlstate; k1++){
4805: if(nagesqr==0)
4806: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4807: else /* nagesqr =1 */
4808: 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);
4809:
1.126 brouard 4810: ij=1;
1.187 brouard 4811: for(j=3; j <=ncovmodel-nagesqr; j++){
1.186 brouard 4812: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187 brouard 4813: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186 brouard 4814: ij++;
4815: }
4816: else
1.187 brouard 4817: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4818: }
4819: fprintf(ficgp,")");
4820: }
4821: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4822: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4823: i=i+ncovmodel;
4824: }
4825: } /* end k */
4826: } /* end k2 */
4827: } /* end jk */
4828: } /* end ng */
1.164 brouard 4829: /* avoid: */
1.126 brouard 4830: fflush(ficgp);
4831: } /* end gnuplot */
4832:
4833:
4834: /*************** Moving average **************/
4835: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4836:
4837: int i, cpt, cptcod;
4838: int modcovmax =1;
4839: int mobilavrange, mob;
4840: double age;
4841:
4842: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4843: a covariate has 2 modalities */
4844: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4845:
4846: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4847: if(mobilav==1) mobilavrange=5; /* default */
4848: else mobilavrange=mobilav;
4849: for (age=bage; age<=fage; age++)
4850: for (i=1; i<=nlstate;i++)
4851: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4852: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4853: /* We keep the original values on the extreme ages bage, fage and for
4854: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4855: we use a 5 terms etc. until the borders are no more concerned.
4856: */
4857: for (mob=3;mob <=mobilavrange;mob=mob+2){
4858: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4859: for (i=1; i<=nlstate;i++){
4860: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4861: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4862: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4863: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4864: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4865: }
4866: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4867: }
4868: }
4869: }/* end age */
4870: }/* end mob */
4871: }else return -1;
4872: return 0;
4873: }/* End movingaverage */
4874:
4875:
4876: /************** Forecasting ******************/
1.169 brouard 4877: 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 4878: /* proj1, year, month, day of starting projection
4879: agemin, agemax range of age
4880: dateprev1 dateprev2 range of dates during which prevalence is computed
4881: anproj2 year of en of projection (same day and month as proj1).
4882: */
1.164 brouard 4883: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4884: double agec; /* generic age */
4885: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4886: double *popeffectif,*popcount;
4887: double ***p3mat;
4888: double ***mobaverage;
4889: char fileresf[FILENAMELENGTH];
4890:
4891: agelim=AGESUP;
4892: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4893:
4894: strcpy(fileresf,"f");
4895: strcat(fileresf,fileres);
4896: if((ficresf=fopen(fileresf,"w"))==NULL) {
4897: printf("Problem with forecast resultfile: %s\n", fileresf);
4898: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4899: }
4900: printf("Computing forecasting: result on file '%s' \n", fileresf);
4901: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4902:
4903: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4904:
4905: if (mobilav!=0) {
4906: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4907: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4908: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4909: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4910: }
4911: }
4912:
4913: stepsize=(int) (stepm+YEARM-1)/YEARM;
4914: if (stepm<=12) stepsize=1;
4915: if(estepm < stepm){
4916: printf ("Problem %d lower than %d\n",estepm, stepm);
4917: }
4918: else hstepm=estepm;
4919:
4920: hstepm=hstepm/stepm;
4921: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4922: fractional in yp1 */
4923: anprojmean=yp;
4924: yp2=modf((yp1*12),&yp);
4925: mprojmean=yp;
4926: yp1=modf((yp2*30.5),&yp);
4927: jprojmean=yp;
4928: if(jprojmean==0) jprojmean=1;
4929: if(mprojmean==0) jprojmean=1;
4930:
4931: i1=cptcoveff;
4932: if (cptcovn < 1){i1=1;}
4933:
4934: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4935:
4936: fprintf(ficresf,"#****** Routine prevforecast **\n");
4937:
4938: /* if (h==(int)(YEARM*yearp)){ */
4939: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4940: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4941: k=k+1;
4942: fprintf(ficresf,"\n#******");
4943: for(j=1;j<=cptcoveff;j++) {
4944: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4945: }
4946: fprintf(ficresf,"******\n");
4947: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4948: for(j=1; j<=nlstate+ndeath;j++){
4949: for(i=1; i<=nlstate;i++)
4950: fprintf(ficresf," p%d%d",i,j);
4951: fprintf(ficresf," p.%d",j);
4952: }
4953: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4954: fprintf(ficresf,"\n");
4955: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4956:
4957: for (agec=fage; agec>=(ageminpar-1); agec--){
4958: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4959: nhstepm = nhstepm/hstepm;
4960: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4961: oldm=oldms;savm=savms;
4962: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4963:
4964: for (h=0; h<=nhstepm; h++){
4965: if (h*hstepm/YEARM*stepm ==yearp) {
4966: fprintf(ficresf,"\n");
4967: for(j=1;j<=cptcoveff;j++)
4968: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4969: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4970: }
4971: for(j=1; j<=nlstate+ndeath;j++) {
4972: ppij=0.;
4973: for(i=1; i<=nlstate;i++) {
4974: if (mobilav==1)
4975: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4976: else {
4977: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4978: }
4979: if (h*hstepm/YEARM*stepm== yearp) {
4980: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4981: }
4982: } /* end i */
4983: if (h*hstepm/YEARM*stepm==yearp) {
4984: fprintf(ficresf," %.3f", ppij);
4985: }
4986: }/* end j */
4987: } /* end h */
4988: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4989: } /* end agec */
4990: } /* end yearp */
4991: } /* end cptcod */
4992: } /* end cptcov */
4993:
4994: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4995:
4996: fclose(ficresf);
4997: }
4998:
4999: /************** Forecasting *****not tested NB*************/
1.169 brouard 5000: 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 5001:
5002: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5003: int *popage;
5004: double calagedatem, agelim, kk1, kk2;
5005: double *popeffectif,*popcount;
5006: double ***p3mat,***tabpop,***tabpopprev;
5007: double ***mobaverage;
5008: char filerespop[FILENAMELENGTH];
5009:
5010: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5011: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5012: agelim=AGESUP;
5013: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5014:
5015: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5016:
5017:
5018: strcpy(filerespop,"pop");
5019: strcat(filerespop,fileres);
5020: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5021: printf("Problem with forecast resultfile: %s\n", filerespop);
5022: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5023: }
5024: printf("Computing forecasting: result on file '%s' \n", filerespop);
5025: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5026:
5027: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5028:
5029: if (mobilav!=0) {
5030: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5031: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5032: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5033: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5034: }
5035: }
5036:
5037: stepsize=(int) (stepm+YEARM-1)/YEARM;
5038: if (stepm<=12) stepsize=1;
5039:
5040: agelim=AGESUP;
5041:
5042: hstepm=1;
5043: hstepm=hstepm/stepm;
5044:
5045: if (popforecast==1) {
5046: if((ficpop=fopen(popfile,"r"))==NULL) {
5047: printf("Problem with population file : %s\n",popfile);exit(0);
5048: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5049: }
5050: popage=ivector(0,AGESUP);
5051: popeffectif=vector(0,AGESUP);
5052: popcount=vector(0,AGESUP);
5053:
5054: i=1;
5055: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5056:
5057: imx=i;
5058: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5059: }
5060:
5061: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5062: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5063: k=k+1;
5064: fprintf(ficrespop,"\n#******");
5065: for(j=1;j<=cptcoveff;j++) {
5066: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5067: }
5068: fprintf(ficrespop,"******\n");
5069: fprintf(ficrespop,"# Age");
5070: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5071: if (popforecast==1) fprintf(ficrespop," [Population]");
5072:
5073: for (cpt=0; cpt<=0;cpt++) {
5074: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5075:
5076: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5077: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5078: nhstepm = nhstepm/hstepm;
5079:
5080: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5081: oldm=oldms;savm=savms;
5082: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5083:
5084: for (h=0; h<=nhstepm; h++){
5085: if (h==(int) (calagedatem+YEARM*cpt)) {
5086: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5087: }
5088: for(j=1; j<=nlstate+ndeath;j++) {
5089: kk1=0.;kk2=0;
5090: for(i=1; i<=nlstate;i++) {
5091: if (mobilav==1)
5092: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5093: else {
5094: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5095: }
5096: }
5097: if (h==(int)(calagedatem+12*cpt)){
5098: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5099: /*fprintf(ficrespop," %.3f", kk1);
5100: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5101: }
5102: }
5103: for(i=1; i<=nlstate;i++){
5104: kk1=0.;
5105: for(j=1; j<=nlstate;j++){
5106: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5107: }
5108: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5109: }
5110:
5111: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5112: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5113: }
5114: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5115: }
5116: }
5117:
5118: /******/
5119:
5120: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5121: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5122: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5123: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5124: nhstepm = nhstepm/hstepm;
5125:
5126: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5127: oldm=oldms;savm=savms;
5128: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5129: for (h=0; h<=nhstepm; h++){
5130: if (h==(int) (calagedatem+YEARM*cpt)) {
5131: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5132: }
5133: for(j=1; j<=nlstate+ndeath;j++) {
5134: kk1=0.;kk2=0;
5135: for(i=1; i<=nlstate;i++) {
5136: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5137: }
5138: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5139: }
5140: }
5141: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5142: }
5143: }
5144: }
5145: }
5146:
5147: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5148:
5149: if (popforecast==1) {
5150: free_ivector(popage,0,AGESUP);
5151: free_vector(popeffectif,0,AGESUP);
5152: free_vector(popcount,0,AGESUP);
5153: }
5154: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5155: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5156: fclose(ficrespop);
5157: } /* End of popforecast */
5158:
5159: int fileappend(FILE *fichier, char *optionfich)
5160: {
5161: if((fichier=fopen(optionfich,"a"))==NULL) {
5162: printf("Problem with file: %s\n", optionfich);
5163: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5164: return (0);
5165: }
5166: fflush(fichier);
5167: return (1);
5168: }
5169:
5170:
5171: /**************** function prwizard **********************/
5172: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5173: {
5174:
5175: /* Wizard to print covariance matrix template */
5176:
1.164 brouard 5177: char ca[32], cb[32];
5178: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5179: int numlinepar;
5180:
5181: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5182: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5183: for(i=1; i <=nlstate; i++){
5184: jj=0;
5185: for(j=1; j <=nlstate+ndeath; j++){
5186: if(j==i) continue;
5187: jj++;
5188: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5189: printf("%1d%1d",i,j);
5190: fprintf(ficparo,"%1d%1d",i,j);
5191: for(k=1; k<=ncovmodel;k++){
5192: /* printf(" %lf",param[i][j][k]); */
5193: /* fprintf(ficparo," %lf",param[i][j][k]); */
5194: printf(" 0.");
5195: fprintf(ficparo," 0.");
5196: }
5197: printf("\n");
5198: fprintf(ficparo,"\n");
5199: }
5200: }
5201: printf("# Scales (for hessian or gradient estimation)\n");
5202: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5203: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5204: for(i=1; i <=nlstate; i++){
5205: jj=0;
5206: for(j=1; j <=nlstate+ndeath; j++){
5207: if(j==i) continue;
5208: jj++;
5209: fprintf(ficparo,"%1d%1d",i,j);
5210: printf("%1d%1d",i,j);
5211: fflush(stdout);
5212: for(k=1; k<=ncovmodel;k++){
5213: /* printf(" %le",delti3[i][j][k]); */
5214: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5215: printf(" 0.");
5216: fprintf(ficparo," 0.");
5217: }
5218: numlinepar++;
5219: printf("\n");
5220: fprintf(ficparo,"\n");
5221: }
5222: }
5223: printf("# Covariance matrix\n");
5224: /* # 121 Var(a12)\n\ */
5225: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5226: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5227: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5228: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5229: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5230: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5231: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5232: fflush(stdout);
5233: fprintf(ficparo,"# Covariance matrix\n");
5234: /* # 121 Var(a12)\n\ */
5235: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5236: /* # ...\n\ */
5237: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5238:
5239: for(itimes=1;itimes<=2;itimes++){
5240: jj=0;
5241: for(i=1; i <=nlstate; i++){
5242: for(j=1; j <=nlstate+ndeath; j++){
5243: if(j==i) continue;
5244: for(k=1; k<=ncovmodel;k++){
5245: jj++;
5246: ca[0]= k+'a'-1;ca[1]='\0';
5247: if(itimes==1){
5248: printf("#%1d%1d%d",i,j,k);
5249: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5250: }else{
5251: printf("%1d%1d%d",i,j,k);
5252: fprintf(ficparo,"%1d%1d%d",i,j,k);
5253: /* printf(" %.5le",matcov[i][j]); */
5254: }
5255: ll=0;
5256: for(li=1;li <=nlstate; li++){
5257: for(lj=1;lj <=nlstate+ndeath; lj++){
5258: if(lj==li) continue;
5259: for(lk=1;lk<=ncovmodel;lk++){
5260: ll++;
5261: if(ll<=jj){
5262: cb[0]= lk +'a'-1;cb[1]='\0';
5263: if(ll<jj){
5264: if(itimes==1){
5265: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5266: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5267: }else{
5268: printf(" 0.");
5269: fprintf(ficparo," 0.");
5270: }
5271: }else{
5272: if(itimes==1){
5273: printf(" Var(%s%1d%1d)",ca,i,j);
5274: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5275: }else{
5276: printf(" 0.");
5277: fprintf(ficparo," 0.");
5278: }
5279: }
5280: }
5281: } /* end lk */
5282: } /* end lj */
5283: } /* end li */
5284: printf("\n");
5285: fprintf(ficparo,"\n");
5286: numlinepar++;
5287: } /* end k*/
5288: } /*end j */
5289: } /* end i */
5290: } /* end itimes */
5291:
5292: } /* end of prwizard */
5293: /******************* Gompertz Likelihood ******************************/
5294: double gompertz(double x[])
5295: {
5296: double A,B,L=0.0,sump=0.,num=0.;
5297: int i,n=0; /* n is the size of the sample */
5298:
5299: for (i=0;i<=imx-1 ; i++) {
5300: sump=sump+weight[i];
5301: /* sump=sump+1;*/
5302: num=num+1;
5303: }
5304:
5305:
5306: /* for (i=0; i<=imx; i++)
5307: 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]);*/
5308:
5309: for (i=1;i<=imx ; i++)
5310: {
5311: if (cens[i] == 1 && wav[i]>1)
5312: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5313:
5314: if (cens[i] == 0 && wav[i]>1)
5315: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5316: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5317:
5318: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5319: if (wav[i] > 1 ) { /* ??? */
5320: L=L+A*weight[i];
5321: /* 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]);*/
5322: }
5323: }
5324:
5325: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5326:
5327: return -2*L*num/sump;
5328: }
5329:
1.136 brouard 5330: #ifdef GSL
5331: /******************* Gompertz_f Likelihood ******************************/
5332: double gompertz_f(const gsl_vector *v, void *params)
5333: {
5334: double A,B,LL=0.0,sump=0.,num=0.;
5335: double *x= (double *) v->data;
5336: int i,n=0; /* n is the size of the sample */
5337:
5338: for (i=0;i<=imx-1 ; i++) {
5339: sump=sump+weight[i];
5340: /* sump=sump+1;*/
5341: num=num+1;
5342: }
5343:
5344:
5345: /* for (i=0; i<=imx; i++)
5346: 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]);*/
5347: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5348: for (i=1;i<=imx ; i++)
5349: {
5350: if (cens[i] == 1 && wav[i]>1)
5351: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5352:
5353: if (cens[i] == 0 && wav[i]>1)
5354: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5355: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5356:
5357: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5358: if (wav[i] > 1 ) { /* ??? */
5359: LL=LL+A*weight[i];
5360: /* 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]);*/
5361: }
5362: }
5363:
5364: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5365: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5366:
5367: return -2*LL*num/sump;
5368: }
5369: #endif
5370:
1.126 brouard 5371: /******************* Printing html file ***********/
5372: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5373: int lastpass, int stepm, int weightopt, char model[],\
5374: int imx, double p[],double **matcov,double agemortsup){
5375: int i,k;
5376:
5377: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5378: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5379: for (i=1;i<=2;i++)
5380: 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]));
5381: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5382: fprintf(fichtm,"</ul>");
5383:
5384: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5385:
5386: 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>");
5387:
5388: for (k=agegomp;k<(agemortsup-2);k++)
5389: 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]);
5390:
5391:
5392: fflush(fichtm);
5393: }
5394:
5395: /******************* Gnuplot file **************/
5396: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5397:
5398: char dirfileres[132],optfileres[132];
1.164 brouard 5399:
1.126 brouard 5400: int ng;
5401:
5402:
5403: /*#ifdef windows */
5404: fprintf(ficgp,"cd \"%s\" \n",pathc);
5405: /*#endif */
5406:
5407:
5408: strcpy(dirfileres,optionfilefiname);
5409: strcpy(optfileres,"vpl");
5410: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5411: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5412: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5413: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5414: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5415:
5416: }
5417:
1.136 brouard 5418: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5419: {
1.126 brouard 5420:
1.136 brouard 5421: /*-------- data file ----------*/
5422: FILE *fic;
5423: char dummy[]=" ";
1.164 brouard 5424: int i=0, j=0, n=0;
1.136 brouard 5425: int linei, month, year,iout;
5426: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5427: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5428: char *stratrunc;
5429: int lstra;
1.126 brouard 5430:
5431:
1.136 brouard 5432: if((fic=fopen(datafile,"r"))==NULL) {
5433: printf("Problem while opening datafile: %s\n", datafile);return 1;
5434: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5435: }
1.126 brouard 5436:
1.136 brouard 5437: i=1;
5438: linei=0;
5439: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5440: linei=linei+1;
5441: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5442: if(line[j] == '\t')
5443: line[j] = ' ';
5444: }
5445: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5446: ;
5447: };
5448: line[j+1]=0; /* Trims blanks at end of line */
5449: if(line[0]=='#'){
5450: fprintf(ficlog,"Comment line\n%s\n",line);
5451: printf("Comment line\n%s\n",line);
5452: continue;
5453: }
5454: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5455: strcpy(line, linetmp);
1.136 brouard 5456:
1.126 brouard 5457:
1.136 brouard 5458: for (j=maxwav;j>=1;j--){
1.137 brouard 5459: cutv(stra, strb, line, ' ');
1.136 brouard 5460: if(strb[0]=='.') { /* Missing status */
5461: lval=-1;
5462: }else{
5463: errno=0;
5464: lval=strtol(strb,&endptr,10);
5465: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5466: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5467: 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);
5468: 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 5469: return 1;
5470: }
5471: }
5472: s[j][i]=lval;
5473:
5474: strcpy(line,stra);
5475: cutv(stra, strb,line,' ');
1.169 brouard 5476: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5477: }
1.169 brouard 5478: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5479: month=99;
5480: year=9999;
5481: }else{
1.141 brouard 5482: 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);
5483: 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 5484: return 1;
5485: }
5486: anint[j][i]= (double) year;
5487: mint[j][i]= (double)month;
5488: strcpy(line,stra);
5489: } /* ENd Waves */
5490:
5491: cutv(stra, strb,line,' ');
1.169 brouard 5492: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5493: }
1.169 brouard 5494: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5495: month=99;
5496: year=9999;
5497: }else{
1.141 brouard 5498: 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);
5499: 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 5500: return 1;
5501: }
5502: andc[i]=(double) year;
5503: moisdc[i]=(double) month;
5504: strcpy(line,stra);
5505:
5506: cutv(stra, strb,line,' ');
1.169 brouard 5507: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5508: }
1.169 brouard 5509: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5510: month=99;
5511: year=9999;
5512: }else{
1.141 brouard 5513: 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);
5514: 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 5515: return 1;
5516: }
5517: if (year==9999) {
1.141 brouard 5518: 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);
5519: 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 5520: return 1;
1.126 brouard 5521:
1.136 brouard 5522: }
5523: annais[i]=(double)(year);
5524: moisnais[i]=(double)(month);
5525: strcpy(line,stra);
5526:
5527: cutv(stra, strb,line,' ');
5528: errno=0;
5529: dval=strtod(strb,&endptr);
5530: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5531: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5532: 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 5533: fflush(ficlog);
5534: return 1;
5535: }
5536: weight[i]=dval;
5537: strcpy(line,stra);
5538:
5539: for (j=ncovcol;j>=1;j--){
5540: cutv(stra, strb,line,' ');
5541: if(strb[0]=='.') { /* Missing status */
5542: lval=-1;
5543: }else{
5544: errno=0;
5545: lval=strtol(strb,&endptr,10);
5546: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5547: 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);
5548: 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 5549: return 1;
5550: }
5551: }
5552: if(lval <-1 || lval >1){
1.141 brouard 5553: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5554: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5555: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5556: For example, for multinomial values like 1, 2 and 3,\n \
5557: build V1=0 V2=0 for the reference value (1),\n \
5558: V1=1 V2=0 for (2) \n \
5559: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5560: output of IMaCh is often meaningless.\n \
5561: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5562: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5563: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5564: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5565: For example, for multinomial values like 1, 2 and 3,\n \
5566: build V1=0 V2=0 for the reference value (1),\n \
5567: V1=1 V2=0 for (2) \n \
5568: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5569: output of IMaCh is often meaningless.\n \
5570: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5571: return 1;
5572: }
5573: covar[j][i]=(double)(lval);
5574: strcpy(line,stra);
5575: }
5576: lstra=strlen(stra);
5577:
5578: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5579: stratrunc = &(stra[lstra-9]);
5580: num[i]=atol(stratrunc);
5581: }
5582: else
5583: num[i]=atol(stra);
5584: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5585: 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;}*/
5586:
5587: i=i+1;
5588: } /* End loop reading data */
1.126 brouard 5589:
1.136 brouard 5590: *imax=i-1; /* Number of individuals */
5591: fclose(fic);
5592:
5593: return (0);
1.164 brouard 5594: /* endread: */
1.136 brouard 5595: printf("Exiting readdata: ");
5596: fclose(fic);
5597: return (1);
1.126 brouard 5598:
5599:
5600:
1.136 brouard 5601: }
1.145 brouard 5602: void removespace(char *str) {
5603: char *p1 = str, *p2 = str;
5604: do
5605: while (*p2 == ' ')
5606: p2++;
1.169 brouard 5607: while (*p1++ == *p2++);
1.145 brouard 5608: }
5609:
5610: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5611: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5612: * - nagesqr = 1 if age*age in the model, otherwise 0.
5613: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5614: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5615: * - cptcovage number of covariates with age*products =2
5616: * - cptcovs number of simple covariates
5617: * - 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
5618: * which is a new column after the 9 (ncovcol) variables.
5619: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5620: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5621: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5622: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5623: */
1.136 brouard 5624: {
1.145 brouard 5625: int i, j, k, ks;
1.164 brouard 5626: int j1, k1, k2;
1.136 brouard 5627: char modelsav[80];
1.145 brouard 5628: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 5629: char *strpt;
1.136 brouard 5630:
1.145 brouard 5631: /*removespace(model);*/
1.136 brouard 5632: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5633: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 5634: if (strstr(model,"AGE") !=0){
1.192 ! brouard 5635: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
! 5636: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 5637: return 1;
5638: }
1.141 brouard 5639: if (strstr(model,"v") !=0){
5640: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5641: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5642: return 1;
5643: }
1.187 brouard 5644: strcpy(modelsav,model);
5645: if ((strpt=strstr(model,"age*age")) !=0){
5646: printf(" strpt=%s, model=%s\n",strpt, model);
5647: if(strpt != model){
5648: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 ! brouard 5649: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5650: corresponding column of parameters.\n",model);
5651: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 ! brouard 5652: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5653: corresponding column of parameters.\n",model); fflush(ficlog);
5654: return 1;
5655: }
5656:
5657: nagesqr=1;
5658: if (strstr(model,"+age*age") !=0)
5659: substrchaine(modelsav, model, "+age*age");
5660: else if (strstr(model,"age*age+") !=0)
5661: substrchaine(modelsav, model, "age*age+");
5662: else
5663: substrchaine(modelsav, model, "age*age");
5664: }else
5665: nagesqr=0;
5666: if (strlen(modelsav) >1){
5667: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5668: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5669: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5670: cptcovt= j+1; /* Number of total covariates in the model, not including
5671: * cst, age and age*age
5672: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5673: /* including age products which are counted in cptcovage.
5674: * but the covariates which are products must be treated
5675: * separately: ncovn=4- 2=2 (V1+V3). */
5676: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5677: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5678:
5679:
5680: /* Design
5681: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5682: * < ncovcol=8 >
5683: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5684: * k= 1 2 3 4 5 6 7 8
5685: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5686: * covar[k,i], value of kth covariate if not including age for individual i:
5687: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5688: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5689: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5690: * Tage[++cptcovage]=k
5691: * if products, new covar are created after ncovcol with k1
5692: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5693: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5694: * 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
5695: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5696: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5697: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5698: * < ncovcol=8 >
5699: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5700: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5701: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5702: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5703: * p Tprod[1]@2={ 6, 5}
5704: *p Tvard[1][1]@4= {7, 8, 5, 6}
5705: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5706: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5707: *How to reorganize?
5708: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5709: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5710: * {2, 1, 4, 8, 5, 6, 3, 7}
5711: * Struct []
5712: */
1.145 brouard 5713:
1.187 brouard 5714: /* This loop fills the array Tvar from the string 'model'.*/
5715: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5716: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5717: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5718: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5719: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5720: /* k=1 Tvar[1]=2 (from V2) */
5721: /* k=5 Tvar[5] */
5722: /* for (k=1; k<=cptcovn;k++) { */
5723: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5724: /* } */
5725: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
5726: /*
5727: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5728: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 5729: Tvar[k]=0;
1.187 brouard 5730: cptcovage=0;
5731: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5732: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5733: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5734: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5735: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5736: /*scanf("%d",i);*/
5737: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5738: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5739: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5740: /* covar is not filled and then is empty */
5741: cptcovprod--;
5742: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5743: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5744: cptcovage++; /* Sums the number of covariates which include age as a product */
5745: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5746: /*printf("stre=%s ", stre);*/
5747: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5748: cptcovprod--;
5749: cutl(stre,strb,strc,'V');
5750: Tvar[k]=atoi(stre);
5751: cptcovage++;
5752: Tage[cptcovage]=k;
5753: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5754: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5755: cptcovn++;
5756: cptcovprodnoage++;k1++;
5757: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5758: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5759: because this model-covariate is a construction we invent a new column
5760: ncovcol + k1
5761: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5762: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5763: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5764: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5765: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5766: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5767: k2=k2+2;
5768: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5769: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5770: for (i=1; i<=lastobs;i++){
5771: /* Computes the new covariate which is a product of
5772: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5773: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5774: }
5775: } /* End age is not in the model */
5776: } /* End if model includes a product */
5777: else { /* no more sum */
5778: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5779: /* scanf("%d",i);*/
5780: cutl(strd,strc,strb,'V');
5781: ks++; /**< Number of simple covariates */
1.145 brouard 5782: cptcovn++;
1.187 brouard 5783: Tvar[k]=atoi(strd);
5784: }
5785: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5786: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5787: scanf("%d",i);*/
5788: } /* end of loop + on total covariates */
5789: } /* end if strlen(modelsave == 0) age*age might exist */
5790: } /* end if strlen(model == 0) */
1.136 brouard 5791:
5792: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5793: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5794:
5795: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5796: printf("cptcovprod=%d ", cptcovprod);
5797: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5798:
5799: scanf("%d ",i);*/
5800:
5801:
1.137 brouard 5802: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5803: /*endread:*/
1.136 brouard 5804: printf("Exiting decodemodel: ");
5805: return (1);
5806: }
5807:
1.169 brouard 5808: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5809: {
5810: int i, m;
5811:
5812: for (i=1; i<=imx; i++) {
5813: for(m=2; (m<= maxwav); m++) {
5814: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5815: anint[m][i]=9999;
5816: s[m][i]=-1;
5817: }
5818: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5819: *nberr = *nberr + 1;
5820: 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);
5821: 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 5822: s[m][i]=-1;
5823: }
5824: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5825: (*nberr)++;
1.136 brouard 5826: 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]);
5827: 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]);
5828: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5829: }
5830: }
5831: }
5832:
5833: for (i=1; i<=imx; i++) {
5834: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5835: for(m=firstpass; (m<= lastpass); m++){
5836: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5837: if (s[m][i] >= nlstate+1) {
1.169 brouard 5838: if(agedc[i]>0){
5839: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5840: agev[m][i]=agedc[i];
5841: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5842: }else {
1.136 brouard 5843: if ((int)andc[i]!=9999){
5844: nbwarn++;
5845: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5846: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5847: agev[m][i]=-1;
5848: }
5849: }
1.169 brouard 5850: } /* agedc > 0 */
1.136 brouard 5851: }
5852: else if(s[m][i] !=9){ /* Standard case, age in fractional
5853: years but with the precision of a month */
5854: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5855: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5856: agev[m][i]=1;
5857: else if(agev[m][i] < *agemin){
5858: *agemin=agev[m][i];
5859: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5860: }
5861: else if(agev[m][i] >*agemax){
5862: *agemax=agev[m][i];
1.156 brouard 5863: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5864: }
5865: /*agev[m][i]=anint[m][i]-annais[i];*/
5866: /* agev[m][i] = age[i]+2*m;*/
5867: }
5868: else { /* =9 */
5869: agev[m][i]=1;
5870: s[m][i]=-1;
5871: }
5872: }
5873: else /*= 0 Unknown */
5874: agev[m][i]=1;
5875: }
5876:
5877: }
5878: for (i=1; i<=imx; i++) {
5879: for(m=firstpass; (m<=lastpass); m++){
5880: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5881: (*nberr)++;
1.136 brouard 5882: 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);
5883: 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);
5884: return 1;
5885: }
5886: }
5887: }
5888:
5889: /*for (i=1; i<=imx; i++){
5890: for (m=firstpass; (m<lastpass); m++){
5891: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5892: }
5893:
5894: }*/
5895:
5896:
1.139 brouard 5897: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5898: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5899:
5900: return (0);
1.164 brouard 5901: /* endread:*/
1.136 brouard 5902: printf("Exiting calandcheckages: ");
5903: return (1);
5904: }
5905:
1.172 brouard 5906: #if defined(_MSC_VER)
5907: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5908: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5909: //#include "stdafx.h"
5910: //#include <stdio.h>
5911: //#include <tchar.h>
5912: //#include <windows.h>
5913: //#include <iostream>
5914: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5915:
5916: LPFN_ISWOW64PROCESS fnIsWow64Process;
5917:
5918: BOOL IsWow64()
5919: {
5920: BOOL bIsWow64 = FALSE;
5921:
5922: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5923: // (HANDLE, PBOOL);
5924:
5925: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5926:
5927: HMODULE module = GetModuleHandle(_T("kernel32"));
5928: const char funcName[] = "IsWow64Process";
5929: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5930: GetProcAddress(module, funcName);
5931:
5932: if (NULL != fnIsWow64Process)
5933: {
5934: if (!fnIsWow64Process(GetCurrentProcess(),
5935: &bIsWow64))
5936: //throw std::exception("Unknown error");
5937: printf("Unknown error\n");
5938: }
5939: return bIsWow64 != FALSE;
5940: }
5941: #endif
1.177 brouard 5942:
1.191 brouard 5943: void syscompilerinfo(int logged)
1.167 brouard 5944: {
5945: /* #include "syscompilerinfo.h"*/
1.185 brouard 5946: /* command line Intel compiler 32bit windows, XP compatible:*/
5947: /* /GS /W3 /Gy
5948: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5949: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5950: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 5951: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5952: */
5953: /* 64 bits */
1.185 brouard 5954: /*
5955: /GS /W3 /Gy
5956: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5957: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5958: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5959: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5960: /* Optimization are useless and O3 is slower than O2 */
5961: /*
5962: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
5963: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
5964: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
5965: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
5966: */
1.186 brouard 5967: /* Link is */ /* /OUT:"visual studio
1.185 brouard 5968: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
5969: /PDB:"visual studio
5970: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
5971: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
5972: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
5973: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
5974: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
5975: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
5976: uiAccess='false'"
5977: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
5978: /NOLOGO /TLBID:1
5979: */
1.177 brouard 5980: #if defined __INTEL_COMPILER
1.178 brouard 5981: #if defined(__GNUC__)
5982: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5983: #endif
1.177 brouard 5984: #elif defined(__GNUC__)
1.179 brouard 5985: #ifndef __APPLE__
1.174 brouard 5986: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5987: #endif
1.177 brouard 5988: struct utsname sysInfo;
1.178 brouard 5989: int cross = CROSS;
5990: if (cross){
5991: printf("Cross-");
1.191 brouard 5992: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 5993: }
1.174 brouard 5994: #endif
5995:
1.171 brouard 5996: #include <stdint.h>
1.178 brouard 5997:
1.191 brouard 5998: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 5999: #if defined(__clang__)
1.191 brouard 6000: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6001: #endif
6002: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6003: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6004: #endif
6005: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6006: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6007: #endif
6008: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6009: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6010: #endif
6011: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6012: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6013: #endif
6014: #if defined(_MSC_VER)
1.191 brouard 6015: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6016: #endif
6017: #if defined(__PGI)
1.191 brouard 6018: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6019: #endif
6020: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6021: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6022: #endif
1.191 brouard 6023: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6024:
1.167 brouard 6025: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6026: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6027: // Windows (x64 and x86)
1.191 brouard 6028: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6029: #elif __unix__ // all unices, not all compilers
6030: // Unix
1.191 brouard 6031: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6032: #elif __linux__
6033: // linux
1.191 brouard 6034: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6035: #elif __APPLE__
1.174 brouard 6036: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6037: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6038: #endif
6039:
6040: /* __MINGW32__ */
6041: /* __CYGWIN__ */
6042: /* __MINGW64__ */
6043: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6044: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6045: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6046: /* _WIN64 // Defined for applications for Win64. */
6047: /* _M_X64 // Defined for compilations that target x64 processors. */
6048: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6049:
1.167 brouard 6050: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6051: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6052: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6053: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6054: #else
1.191 brouard 6055: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6056: #endif
6057:
1.169 brouard 6058: #if defined(__GNUC__)
6059: # if defined(__GNUC_PATCHLEVEL__)
6060: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6061: + __GNUC_MINOR__ * 100 \
6062: + __GNUC_PATCHLEVEL__)
6063: # else
6064: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6065: + __GNUC_MINOR__ * 100)
6066: # endif
1.174 brouard 6067: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6068: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6069:
6070: if (uname(&sysInfo) != -1) {
6071: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6072: 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 6073: }
6074: else
6075: perror("uname() error");
1.179 brouard 6076: //#ifndef __INTEL_COMPILER
6077: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6078: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6079: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6080: #endif
1.169 brouard 6081: #endif
1.172 brouard 6082:
6083: // void main()
6084: // {
1.169 brouard 6085: #if defined(_MSC_VER)
1.174 brouard 6086: if (IsWow64()){
1.191 brouard 6087: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6088: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6089: }
6090: else{
1.191 brouard 6091: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6092: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6093: }
1.172 brouard 6094: // printf("\nPress Enter to continue...");
6095: // getchar();
6096: // }
6097:
1.169 brouard 6098: #endif
6099:
1.167 brouard 6100:
6101: }
1.136 brouard 6102:
1.180 brouard 6103: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6104: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6105: int i, j, k, i1 ;
6106: double ftolpl = 1.e-10;
6107: double age, agebase, agelim;
6108:
6109: strcpy(filerespl,"pl");
6110: strcat(filerespl,fileres);
6111: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6112: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6113: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6114: }
6115: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6116: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6117: pstamp(ficrespl);
6118: fprintf(ficrespl,"# Period (stable) prevalence \n");
6119: fprintf(ficrespl,"#Age ");
6120: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6121: fprintf(ficrespl,"\n");
6122:
6123: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6124:
6125: agebase=ageminpar;
6126: agelim=agemaxpar;
6127:
6128: i1=pow(2,cptcoveff);
6129: if (cptcovn < 1){i1=1;}
6130:
6131: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6132: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6133: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6134: k=k+1;
6135: /* to clean */
6136: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
6137: fprintf(ficrespl,"\n#******");
6138: printf("\n#******");
6139: fprintf(ficlog,"\n#******");
6140: for(j=1;j<=cptcoveff;j++) {
6141: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6142: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6143: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6144: }
6145: fprintf(ficrespl,"******\n");
6146: printf("******\n");
6147: fprintf(ficlog,"******\n");
6148:
6149: fprintf(ficrespl,"#Age ");
6150: for(j=1;j<=cptcoveff;j++) {
6151: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6152: }
6153: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6154: fprintf(ficrespl,"\n");
6155:
6156: for (age=agebase; age<=agelim; age++){
6157: /* for (age=agebase; age<=agebase; age++){ */
6158: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6159: fprintf(ficrespl,"%.0f ",age );
6160: for(j=1;j<=cptcoveff;j++)
6161: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6162: for(i=1; i<=nlstate;i++)
6163: fprintf(ficrespl," %.5f", prlim[i][i]);
6164: fprintf(ficrespl,"\n");
6165: } /* Age */
6166: /* was end of cptcod */
6167: } /* cptcov */
1.184 brouard 6168: return 0;
1.180 brouard 6169: }
6170:
6171: int hPijx(double *p, int bage, int fage){
6172: /*------------- h Pij x at various ages ------------*/
6173:
6174: int stepsize;
6175: int agelim;
6176: int hstepm;
6177: int nhstepm;
6178: int h, i, i1, j, k;
6179:
6180: double agedeb;
6181: double ***p3mat;
6182:
6183: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6184: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6185: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6186: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6187: }
6188: printf("Computing pij: result on file '%s' \n", filerespij);
6189: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6190:
6191: stepsize=(int) (stepm+YEARM-1)/YEARM;
6192: /*if (stepm<=24) stepsize=2;*/
6193:
6194: agelim=AGESUP;
6195: hstepm=stepsize*YEARM; /* Every year of age */
6196: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6197:
6198: /* hstepm=1; aff par mois*/
6199: pstamp(ficrespij);
6200: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6201: i1= pow(2,cptcoveff);
1.183 brouard 6202: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6203: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6204: /* k=k+1; */
6205: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6206: fprintf(ficrespij,"\n#****** ");
6207: for(j=1;j<=cptcoveff;j++)
6208: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6209: fprintf(ficrespij,"******\n");
6210:
6211: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6212: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6213: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6214:
6215: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6216:
1.183 brouard 6217: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6218: oldm=oldms;savm=savms;
6219: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6220: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6221: for(i=1; i<=nlstate;i++)
6222: for(j=1; j<=nlstate+ndeath;j++)
6223: fprintf(ficrespij," %1d-%1d",i,j);
6224: fprintf(ficrespij,"\n");
6225: for (h=0; h<=nhstepm; h++){
6226: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6227: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6228: for(i=1; i<=nlstate;i++)
6229: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6230: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6231: fprintf(ficrespij,"\n");
6232: }
1.183 brouard 6233: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6234: fprintf(ficrespij,"\n");
6235: }
1.180 brouard 6236: /*}*/
6237: }
1.184 brouard 6238: return 0;
1.180 brouard 6239: }
6240:
6241:
1.136 brouard 6242: /***********************************************/
6243: /**************** Main Program *****************/
6244: /***********************************************/
6245:
6246: int main(int argc, char *argv[])
6247: {
6248: #ifdef GSL
6249: const gsl_multimin_fminimizer_type *T;
6250: size_t iteri = 0, it;
6251: int rval = GSL_CONTINUE;
6252: int status = GSL_SUCCESS;
6253: double ssval;
6254: #endif
6255: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6256: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6257:
6258: int jj, ll, li, lj, lk;
1.136 brouard 6259: int numlinepar=0; /* Current linenumber of parameter file */
6260: int itimes;
6261: int NDIM=2;
6262: int vpopbased=0;
6263:
1.164 brouard 6264: char ca[32], cb[32];
1.136 brouard 6265: /* FILE *fichtm; *//* Html File */
6266: /* FILE *ficgp;*/ /*Gnuplot File */
6267: struct stat info;
1.191 brouard 6268: double agedeb=0.;
1.136 brouard 6269: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
6270:
1.165 brouard 6271: double fret;
1.191 brouard 6272: double dum=0.; /* Dummy variable */
1.136 brouard 6273: double ***p3mat;
6274: double ***mobaverage;
1.164 brouard 6275:
6276: char line[MAXLINE];
1.136 brouard 6277: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
6278: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6279: char *tok, *val; /* pathtot */
1.136 brouard 6280: int firstobs=1, lastobs=10;
1.164 brouard 6281: int c, h , cpt;
1.191 brouard 6282: int jl=0;
6283: int i1, j1, jk, stepsize=0;
1.164 brouard 6284: int *tab;
1.136 brouard 6285: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6286: int mobilav=0,popforecast=0;
1.191 brouard 6287: int hstepm=0, nhstepm=0;
1.136 brouard 6288: int agemortsup;
6289: float sumlpop=0.;
6290: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6291: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6292:
1.191 brouard 6293: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6294: double ftolpl=FTOL;
6295: double **prlim;
6296: double ***param; /* Matrix of parameters */
6297: double *p;
6298: double **matcov; /* Matrix of covariance */
6299: double ***delti3; /* Scale */
6300: double *delti; /* Scale */
6301: double ***eij, ***vareij;
6302: double **varpl; /* Variances of prevalence limits by age */
6303: double *epj, vepp;
1.164 brouard 6304:
1.136 brouard 6305: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6306: double **ximort;
1.145 brouard 6307: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6308: int *dcwave;
6309:
1.164 brouard 6310: char z[1]="c";
1.136 brouard 6311:
6312: /*char *strt;*/
6313: char strtend[80];
1.126 brouard 6314:
1.164 brouard 6315:
1.126 brouard 6316: /* setlocale (LC_ALL, ""); */
6317: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6318: /* textdomain (PACKAGE); */
6319: /* setlocale (LC_CTYPE, ""); */
6320: /* setlocale (LC_MESSAGES, ""); */
6321:
6322: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6323: rstart_time = time(NULL);
6324: /* (void) gettimeofday(&start_time,&tzp);*/
6325: start_time = *localtime(&rstart_time);
1.126 brouard 6326: curr_time=start_time;
1.157 brouard 6327: /*tml = *localtime(&start_time.tm_sec);*/
6328: /* strcpy(strstart,asctime(&tml)); */
6329: strcpy(strstart,asctime(&start_time));
1.126 brouard 6330:
6331: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6332: /* tp.tm_sec = tp.tm_sec +86400; */
6333: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6334: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6335: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6336: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6337: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6338: /* strt=asctime(&tmg); */
6339: /* printf("Time(after) =%s",strstart); */
6340: /* (void) time (&time_value);
6341: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6342: * tm = *localtime(&time_value);
6343: * strstart=asctime(&tm);
6344: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6345: */
6346:
6347: nberr=0; /* Number of errors and warnings */
6348: nbwarn=0;
1.184 brouard 6349: #ifdef WIN32
6350: _getcwd(pathcd, size);
6351: #else
1.126 brouard 6352: getcwd(pathcd, size);
1.184 brouard 6353: #endif
1.191 brouard 6354: syscompilerinfo(0);
1.126 brouard 6355: printf("\n%s\n%s",version,fullversion);
6356: if(argc <=1){
6357: printf("\nEnter the parameter file name: ");
6358: fgets(pathr,FILENAMELENGTH,stdin);
6359: i=strlen(pathr);
6360: if(pathr[i-1]=='\n')
6361: pathr[i-1]='\0';
1.156 brouard 6362: i=strlen(pathr);
6363: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6364: pathr[i-1]='\0';
1.126 brouard 6365: for (tok = pathr; tok != NULL; ){
6366: printf("Pathr |%s|\n",pathr);
6367: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6368: printf("val= |%s| pathr=%s\n",val,pathr);
6369: strcpy (pathtot, val);
6370: if(pathr[0] == '\0') break; /* Dirty */
6371: }
6372: }
6373: else{
6374: strcpy(pathtot,argv[1]);
6375: }
6376: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6377: /*cygwin_split_path(pathtot,path,optionfile);
6378: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6379: /* cutv(path,optionfile,pathtot,'\\');*/
6380:
6381: /* Split argv[0], imach program to get pathimach */
6382: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6383: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6384: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6385: /* strcpy(pathimach,argv[0]); */
6386: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6387: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6388: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6389: #ifdef WIN32
6390: _chdir(path); /* Can be a relative path */
6391: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6392: #else
1.126 brouard 6393: chdir(path); /* Can be a relative path */
1.184 brouard 6394: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6395: #endif
6396: printf("Current directory %s!\n",pathcd);
1.126 brouard 6397: strcpy(command,"mkdir ");
6398: strcat(command,optionfilefiname);
6399: if((outcmd=system(command)) != 0){
1.169 brouard 6400: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6401: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6402: /* fclose(ficlog); */
6403: /* exit(1); */
6404: }
6405: /* if((imk=mkdir(optionfilefiname))<0){ */
6406: /* perror("mkdir"); */
6407: /* } */
6408:
6409: /*-------- arguments in the command line --------*/
6410:
1.186 brouard 6411: /* Main Log file */
1.126 brouard 6412: strcat(filelog, optionfilefiname);
6413: strcat(filelog,".log"); /* */
6414: if((ficlog=fopen(filelog,"w"))==NULL) {
6415: printf("Problem with logfile %s\n",filelog);
6416: goto end;
6417: }
6418: fprintf(ficlog,"Log filename:%s\n",filelog);
6419: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6420: fprintf(ficlog,"\nEnter the parameter file name: \n");
6421: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6422: path=%s \n\
6423: optionfile=%s\n\
6424: optionfilext=%s\n\
1.156 brouard 6425: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6426:
1.191 brouard 6427: syscompilerinfo(0);
1.167 brouard 6428:
1.126 brouard 6429: printf("Local time (at start):%s",strstart);
6430: fprintf(ficlog,"Local time (at start): %s",strstart);
6431: fflush(ficlog);
6432: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6433: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6434:
6435: /* */
6436: strcpy(fileres,"r");
6437: strcat(fileres, optionfilefiname);
6438: strcat(fileres,".txt"); /* Other files have txt extension */
6439:
1.186 brouard 6440: /* Main ---------arguments file --------*/
1.126 brouard 6441:
6442: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6443: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6444: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6445: fflush(ficlog);
1.149 brouard 6446: /* goto end; */
6447: exit(70);
1.126 brouard 6448: }
6449:
6450:
6451:
6452: strcpy(filereso,"o");
6453: strcat(filereso,fileres);
6454: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6455: printf("Problem with Output resultfile: %s\n", filereso);
6456: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6457: fflush(ficlog);
6458: goto end;
6459: }
6460:
6461: /* Reads comments: lines beginning with '#' */
6462: numlinepar=0;
6463: while((c=getc(ficpar))=='#' && c!= EOF){
6464: ungetc(c,ficpar);
6465: fgets(line, MAXLINE, ficpar);
6466: numlinepar++;
1.141 brouard 6467: fputs(line,stdout);
1.126 brouard 6468: fputs(line,ficparo);
6469: fputs(line,ficlog);
6470: }
6471: ungetc(c,ficpar);
6472:
1.187 brouard 6473: 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);
1.126 brouard 6474: numlinepar++;
1.187 brouard 6475: 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);
6476: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6477: model[strlen(model)-1]='\0';
6478: 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);
6479: 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 6480: fflush(ficlog);
1.190 brouard 6481: /* if(model[0]=='#'|| model[0]== '\0'){ */
6482: if(model[0]=='#'){
1.187 brouard 6483: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6484: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6485: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6486: if(mle != -1){
6487: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6488: exit(1);
6489: }
6490: }
1.126 brouard 6491: while((c=getc(ficpar))=='#' && c!= EOF){
6492: ungetc(c,ficpar);
6493: fgets(line, MAXLINE, ficpar);
6494: numlinepar++;
1.141 brouard 6495: fputs(line, stdout);
6496: //puts(line);
1.126 brouard 6497: fputs(line,ficparo);
6498: fputs(line,ficlog);
6499: }
6500: ungetc(c,ficpar);
6501:
6502:
1.145 brouard 6503: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6504: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6505: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6506: v1+v2*age+v2*v3 makes cptcovn = 3
6507: */
6508: if (strlen(model)>1)
1.187 brouard 6509: 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 6510: else
1.187 brouard 6511: ncovmodel=2; /* Constant and age */
1.133 brouard 6512: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6513: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6514: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6515: 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);
6516: 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);
6517: fflush(stdout);
6518: fclose (ficlog);
6519: goto end;
6520: }
1.126 brouard 6521: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6522: delti=delti3[1][1];
6523: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6524: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6525: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 6526: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6527: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6528: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6529: fclose (ficparo);
6530: fclose (ficlog);
6531: goto end;
6532: exit(0);
6533: }
1.186 brouard 6534: else if(mle==-3) { /* Main Wizard */
1.126 brouard 6535: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 ! brouard 6536: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
! 6537: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6538: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6539: matcov=matrix(1,npar,1,npar);
6540: }
6541: else{
1.145 brouard 6542: /* Read guessed parameters */
1.126 brouard 6543: /* Reads comments: lines beginning with '#' */
6544: while((c=getc(ficpar))=='#' && c!= EOF){
6545: ungetc(c,ficpar);
6546: fgets(line, MAXLINE, ficpar);
6547: numlinepar++;
1.141 brouard 6548: fputs(line,stdout);
1.126 brouard 6549: fputs(line,ficparo);
6550: fputs(line,ficlog);
6551: }
6552: ungetc(c,ficpar);
6553:
6554: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6555: for(i=1; i <=nlstate; i++){
6556: j=0;
6557: for(jj=1; jj <=nlstate+ndeath; jj++){
6558: if(jj==i) continue;
6559: j++;
6560: fscanf(ficpar,"%1d%1d",&i1,&j1);
6561: if ((i1 != i) && (j1 != j)){
6562: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6563: It might be a problem of design; if ncovcol and the model are correct\n \
6564: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6565: exit(1);
6566: }
6567: fprintf(ficparo,"%1d%1d",i1,j1);
6568: if(mle==1)
6569: printf("%1d%1d",i,j);
6570: fprintf(ficlog,"%1d%1d",i,j);
6571: for(k=1; k<=ncovmodel;k++){
6572: fscanf(ficpar," %lf",¶m[i][j][k]);
6573: if(mle==1){
6574: printf(" %lf",param[i][j][k]);
6575: fprintf(ficlog," %lf",param[i][j][k]);
6576: }
6577: else
6578: fprintf(ficlog," %lf",param[i][j][k]);
6579: fprintf(ficparo," %lf",param[i][j][k]);
6580: }
6581: fscanf(ficpar,"\n");
6582: numlinepar++;
6583: if(mle==1)
6584: printf("\n");
6585: fprintf(ficlog,"\n");
6586: fprintf(ficparo,"\n");
6587: }
6588: }
6589: fflush(ficlog);
6590:
1.145 brouard 6591: /* Reads scales values */
1.126 brouard 6592: p=param[1][1];
6593:
6594: /* Reads comments: lines beginning with '#' */
6595: while((c=getc(ficpar))=='#' && c!= EOF){
6596: ungetc(c,ficpar);
6597: fgets(line, MAXLINE, ficpar);
6598: numlinepar++;
1.141 brouard 6599: fputs(line,stdout);
1.126 brouard 6600: fputs(line,ficparo);
6601: fputs(line,ficlog);
6602: }
6603: ungetc(c,ficpar);
6604:
6605: for(i=1; i <=nlstate; i++){
6606: for(j=1; j <=nlstate+ndeath-1; j++){
6607: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6608: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6609: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6610: exit(1);
6611: }
6612: printf("%1d%1d",i,j);
6613: fprintf(ficparo,"%1d%1d",i1,j1);
6614: fprintf(ficlog,"%1d%1d",i1,j1);
6615: for(k=1; k<=ncovmodel;k++){
6616: fscanf(ficpar,"%le",&delti3[i][j][k]);
6617: printf(" %le",delti3[i][j][k]);
6618: fprintf(ficparo," %le",delti3[i][j][k]);
6619: fprintf(ficlog," %le",delti3[i][j][k]);
6620: }
6621: fscanf(ficpar,"\n");
6622: numlinepar++;
6623: printf("\n");
6624: fprintf(ficparo,"\n");
6625: fprintf(ficlog,"\n");
6626: }
6627: }
6628: fflush(ficlog);
6629:
1.145 brouard 6630: /* Reads covariance matrix */
1.126 brouard 6631: delti=delti3[1][1];
6632:
6633:
6634: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6635:
6636: /* Reads comments: lines beginning with '#' */
6637: while((c=getc(ficpar))=='#' && c!= EOF){
6638: ungetc(c,ficpar);
6639: fgets(line, MAXLINE, ficpar);
6640: numlinepar++;
1.141 brouard 6641: fputs(line,stdout);
1.126 brouard 6642: fputs(line,ficparo);
6643: fputs(line,ficlog);
6644: }
6645: ungetc(c,ficpar);
6646:
6647: matcov=matrix(1,npar,1,npar);
1.131 brouard 6648: for(i=1; i <=npar; i++)
6649: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6650:
1.126 brouard 6651: for(i=1; i <=npar; i++){
1.145 brouard 6652: fscanf(ficpar,"%s",str);
1.126 brouard 6653: if(mle==1)
6654: printf("%s",str);
6655: fprintf(ficlog,"%s",str);
6656: fprintf(ficparo,"%s",str);
6657: for(j=1; j <=i; j++){
6658: fscanf(ficpar," %le",&matcov[i][j]);
6659: if(mle==1){
6660: printf(" %.5le",matcov[i][j]);
6661: }
6662: fprintf(ficlog," %.5le",matcov[i][j]);
6663: fprintf(ficparo," %.5le",matcov[i][j]);
6664: }
6665: fscanf(ficpar,"\n");
6666: numlinepar++;
6667: if(mle==1)
6668: printf("\n");
6669: fprintf(ficlog,"\n");
6670: fprintf(ficparo,"\n");
6671: }
6672: for(i=1; i <=npar; i++)
6673: for(j=i+1;j<=npar;j++)
6674: matcov[i][j]=matcov[j][i];
6675:
6676: if(mle==1)
6677: printf("\n");
6678: fprintf(ficlog,"\n");
6679:
6680: fflush(ficlog);
6681:
6682: /*-------- Rewriting parameter file ----------*/
6683: strcpy(rfileres,"r"); /* "Rparameterfile */
6684: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6685: strcat(rfileres,"."); /* */
6686: strcat(rfileres,optionfilext); /* Other files have txt extension */
6687: if((ficres =fopen(rfileres,"w"))==NULL) {
6688: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6689: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6690: }
6691: fprintf(ficres,"#%s\n",version);
6692: } /* End of mle != -3 */
6693:
1.186 brouard 6694: /* Main data
6695: */
1.126 brouard 6696: n= lastobs;
6697: num=lvector(1,n);
6698: moisnais=vector(1,n);
6699: annais=vector(1,n);
6700: moisdc=vector(1,n);
6701: andc=vector(1,n);
6702: agedc=vector(1,n);
6703: cod=ivector(1,n);
6704: weight=vector(1,n);
6705: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6706: mint=matrix(1,maxwav,1,n);
6707: anint=matrix(1,maxwav,1,n);
1.131 brouard 6708: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6709: tab=ivector(1,NCOVMAX);
1.144 brouard 6710: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 ! brouard 6711: 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 6712:
1.136 brouard 6713: /* Reads data from file datafile */
6714: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6715: goto end;
6716:
6717: /* Calculation of the number of parameters from char model */
1.137 brouard 6718: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6719: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6720: k=3 V4 Tvar[k=3]= 4 (from V4)
6721: k=2 V1 Tvar[k=2]= 1 (from V1)
6722: k=1 Tvar[1]=2 (from V2)
6723: */
6724: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6725: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6726: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6727: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6728: */
6729: /* For model-covariate k tells which data-covariate to use but
6730: because this model-covariate is a construction we invent a new column
6731: ncovcol + k1
6732: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6733: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6734: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6735: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6736: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6737: */
1.145 brouard 6738: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6739: 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 6740: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6741: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6742: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6743: 4 covariates (3 plus signs)
6744: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6745: */
1.136 brouard 6746:
1.186 brouard 6747: /* Main decodemodel */
6748:
1.187 brouard 6749:
1.136 brouard 6750: if(decodemodel(model, lastobs) == 1)
6751: goto end;
6752:
1.137 brouard 6753: if((double)(lastobs-imx)/(double)imx > 1.10){
6754: nbwarn++;
6755: 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);
6756: 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);
6757: }
1.136 brouard 6758: /* if(mle==1){*/
1.137 brouard 6759: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6760: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6761: }
6762:
6763: /*-calculation of age at interview from date of interview and age at death -*/
6764: agev=matrix(1,maxwav,1,imx);
6765:
6766: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6767: goto end;
6768:
1.126 brouard 6769:
1.136 brouard 6770: agegomp=(int)agemin;
6771: free_vector(moisnais,1,n);
6772: free_vector(annais,1,n);
1.126 brouard 6773: /* free_matrix(mint,1,maxwav,1,n);
6774: free_matrix(anint,1,maxwav,1,n);*/
6775: free_vector(moisdc,1,n);
6776: free_vector(andc,1,n);
1.145 brouard 6777: /* */
6778:
1.126 brouard 6779: wav=ivector(1,imx);
6780: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6781: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6782: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6783:
6784: /* Concatenates waves */
6785: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6786: /* */
6787:
1.126 brouard 6788: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6789:
6790: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6791: ncodemax[1]=1;
1.145 brouard 6792: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 6793: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 6794: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 6795: /* Nbcode gives the value of the lth modality of jth covariate, in
6796: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6797: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 6798:
6799: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6800: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186 brouard 6801: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 6802: h=0;
6803:
6804:
6805: /*if (cptcovn > 0) */
1.126 brouard 6806:
1.145 brouard 6807:
1.126 brouard 6808: m=pow(2,cptcoveff);
6809:
1.131 brouard 6810: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6811: 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 */
6812: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6813: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
1.126 brouard 6814: h++;
1.141 brouard 6815: if (h>m)
1.136 brouard 6816: h=1;
1.144 brouard 6817: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 6818: * For k=4 covariates, h goes from 1 to 2**k
6819: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6820: * h\k 1 2 3 4
1.143 brouard 6821: *______________________________
6822: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6823: * 2 2 1 1 1
6824: * 3 i=2 1 2 1 1
6825: * 4 2 2 1 1
6826: * 5 i=3 1 i=2 1 2 1
6827: * 6 2 1 2 1
6828: * 7 i=4 1 2 2 1
6829: * 8 2 2 2 1
6830: * 9 i=5 1 i=3 1 i=2 1 1
6831: * 10 2 1 1 1
6832: * 11 i=6 1 2 1 1
6833: * 12 2 2 1 1
6834: * 13 i=7 1 i=4 1 2 1
6835: * 14 2 1 2 1
6836: * 15 i=8 1 2 2 1
6837: * 16 2 2 2 1
6838: */
1.141 brouard 6839: codtab[h][k]=j;
1.186 brouard 6840: /* codtab[12][3]=1; */
1.145 brouard 6841: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6842: 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]]);
1.126 brouard 6843: }
6844: }
6845: }
6846: }
6847: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6848: codtab[1][2]=1;codtab[2][2]=2; */
6849: /* for(i=1; i <=m ;i++){
6850: for(k=1; k <=cptcovn; k++){
1.131 brouard 6851: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6852: }
6853: printf("\n");
6854: }
6855: scanf("%d",i);*/
1.145 brouard 6856:
6857: free_ivector(Ndum,-1,NCOVMAX);
6858:
6859:
1.126 brouard 6860:
1.186 brouard 6861: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 6862: strcpy(optionfilegnuplot,optionfilefiname);
6863: if(mle==-3)
6864: strcat(optionfilegnuplot,"-mort");
6865: strcat(optionfilegnuplot,".gp");
6866:
6867: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6868: printf("Problem with file %s",optionfilegnuplot);
6869: }
6870: else{
6871: fprintf(ficgp,"\n# %s\n", version);
6872: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6873: //fprintf(ficgp,"set missing 'NaNq'\n");
6874: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6875: }
6876: /* fclose(ficgp);*/
1.186 brouard 6877:
6878:
6879: /* Initialisation of --------- index.htm --------*/
1.126 brouard 6880:
6881: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6882: if(mle==-3)
6883: strcat(optionfilehtm,"-mort");
6884: strcat(optionfilehtm,".htm");
6885: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6886: printf("Problem with %s \n",optionfilehtm);
6887: exit(0);
1.126 brouard 6888: }
6889:
6890: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6891: strcat(optionfilehtmcov,"-cov.htm");
6892: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6893: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6894: }
6895: else{
6896: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6897: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6898: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6899: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6900: }
6901:
6902: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6903: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6904: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6905: \n\
6906: <hr size=\"2\" color=\"#EC5E5E\">\
6907: <ul><li><h4>Parameter files</h4>\n\
6908: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6909: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6910: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6911: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6912: - Date and time at start: %s</ul>\n",\
6913: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6914: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6915: fileres,fileres,\
6916: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6917: fflush(fichtm);
6918:
6919: strcpy(pathr,path);
6920: strcat(pathr,optionfilefiname);
1.184 brouard 6921: #ifdef WIN32
6922: _chdir(optionfilefiname); /* Move to directory named optionfile */
6923: #else
1.126 brouard 6924: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 6925: #endif
6926:
1.126 brouard 6927:
6928: /* Calculates basic frequencies. Computes observed prevalence at single age
6929: and prints on file fileres'p'. */
6930: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6931:
6932: fprintf(fichtm,"\n");
6933: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6934: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6935: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6936: imx,agemin,agemax,jmin,jmax,jmean);
6937: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6938: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6939: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6940: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6941: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6942:
6943:
6944: /* For Powell, parameters are in a vector p[] starting at p[1]
6945: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6946: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6947:
6948: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 6949: /* For mortality only */
1.126 brouard 6950: if (mle==-3){
1.136 brouard 6951: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 6952: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6953: cens=ivector(1,n);
6954: ageexmed=vector(1,n);
6955: agecens=vector(1,n);
6956: dcwave=ivector(1,n);
6957:
6958: for (i=1; i<=imx; i++){
6959: dcwave[i]=-1;
6960: for (m=firstpass; m<=lastpass; m++)
6961: if (s[m][i]>nlstate) {
6962: dcwave[i]=m;
6963: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6964: break;
6965: }
6966: }
6967:
6968: for (i=1; i<=imx; i++) {
6969: if (wav[i]>0){
6970: ageexmed[i]=agev[mw[1][i]][i];
6971: j=wav[i];
6972: agecens[i]=1.;
6973:
6974: if (ageexmed[i]> 1 && wav[i] > 0){
6975: agecens[i]=agev[mw[j][i]][i];
6976: cens[i]= 1;
6977: }else if (ageexmed[i]< 1)
6978: cens[i]= -1;
6979: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6980: cens[i]=0 ;
6981: }
6982: else cens[i]=-1;
6983: }
6984:
6985: for (i=1;i<=NDIM;i++) {
6986: for (j=1;j<=NDIM;j++)
6987: ximort[i][j]=(i == j ? 1.0 : 0.0);
6988: }
6989:
1.145 brouard 6990: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6991: /*printf("%lf %lf", p[1], p[2]);*/
6992:
6993:
1.136 brouard 6994: #ifdef GSL
6995: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6996: #else
1.126 brouard 6997: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6998: #endif
1.126 brouard 6999: strcpy(filerespow,"pow-mort");
7000: strcat(filerespow,fileres);
7001: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7002: printf("Problem with resultfile: %s\n", filerespow);
7003: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7004: }
1.136 brouard 7005: #ifdef GSL
7006: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7007: #else
1.126 brouard 7008: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7009: #endif
1.126 brouard 7010: /* for (i=1;i<=nlstate;i++)
7011: for(j=1;j<=nlstate+ndeath;j++)
7012: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7013: */
7014: fprintf(ficrespow,"\n");
1.136 brouard 7015: #ifdef GSL
7016: /* gsl starts here */
7017: T = gsl_multimin_fminimizer_nmsimplex;
7018: gsl_multimin_fminimizer *sfm = NULL;
7019: gsl_vector *ss, *x;
7020: gsl_multimin_function minex_func;
7021:
7022: /* Initial vertex size vector */
7023: ss = gsl_vector_alloc (NDIM);
7024:
7025: if (ss == NULL){
7026: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7027: }
7028: /* Set all step sizes to 1 */
7029: gsl_vector_set_all (ss, 0.001);
7030:
7031: /* Starting point */
1.126 brouard 7032:
1.136 brouard 7033: x = gsl_vector_alloc (NDIM);
7034:
7035: if (x == NULL){
7036: gsl_vector_free(ss);
7037: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7038: }
7039:
7040: /* Initialize method and iterate */
7041: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7042: /* gsl_vector_set(x, 0, 0.0268); */
7043: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7044: gsl_vector_set(x, 0, p[1]);
7045: gsl_vector_set(x, 1, p[2]);
7046:
7047: minex_func.f = &gompertz_f;
7048: minex_func.n = NDIM;
7049: minex_func.params = (void *)&p; /* ??? */
7050:
7051: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7052: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7053:
7054: printf("Iterations beginning .....\n\n");
7055: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7056:
7057: iteri=0;
7058: while (rval == GSL_CONTINUE){
7059: iteri++;
7060: status = gsl_multimin_fminimizer_iterate(sfm);
7061:
7062: if (status) printf("error: %s\n", gsl_strerror (status));
7063: fflush(0);
7064:
7065: if (status)
7066: break;
7067:
7068: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7069: ssval = gsl_multimin_fminimizer_size (sfm);
7070:
7071: if (rval == GSL_SUCCESS)
7072: printf ("converged to a local maximum at\n");
7073:
7074: printf("%5d ", iteri);
7075: for (it = 0; it < NDIM; it++){
7076: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7077: }
7078: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7079: }
7080:
7081: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7082:
7083: gsl_vector_free(x); /* initial values */
7084: gsl_vector_free(ss); /* inital step size */
7085: for (it=0; it<NDIM; it++){
7086: p[it+1]=gsl_vector_get(sfm->x,it);
7087: fprintf(ficrespow," %.12lf", p[it]);
7088: }
7089: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7090: #endif
7091: #ifdef POWELL
7092: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7093: #endif
1.126 brouard 7094: fclose(ficrespow);
7095:
7096: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7097:
7098: for(i=1; i <=NDIM; i++)
7099: for(j=i+1;j<=NDIM;j++)
7100: matcov[i][j]=matcov[j][i];
7101:
7102: printf("\nCovariance matrix\n ");
7103: for(i=1; i <=NDIM; i++) {
7104: for(j=1;j<=NDIM;j++){
7105: printf("%f ",matcov[i][j]);
7106: }
7107: printf("\n ");
7108: }
7109:
7110: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7111: for (i=1;i<=NDIM;i++)
7112: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7113:
7114: lsurv=vector(1,AGESUP);
7115: lpop=vector(1,AGESUP);
7116: tpop=vector(1,AGESUP);
7117: lsurv[agegomp]=100000;
7118:
7119: for (k=agegomp;k<=AGESUP;k++) {
7120: agemortsup=k;
7121: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7122: }
7123:
7124: for (k=agegomp;k<agemortsup;k++)
7125: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7126:
7127: for (k=agegomp;k<agemortsup;k++){
7128: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7129: sumlpop=sumlpop+lpop[k];
7130: }
7131:
7132: tpop[agegomp]=sumlpop;
7133: for (k=agegomp;k<(agemortsup-3);k++){
7134: /* tpop[k+1]=2;*/
7135: tpop[k+1]=tpop[k]-lpop[k];
7136: }
7137:
7138:
7139: printf("\nAge lx qx dx Lx Tx e(x)\n");
7140: for (k=agegomp;k<(agemortsup-2);k++)
7141: 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]);
7142:
7143:
7144: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7145: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7146:
7147: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7148: stepm, weightopt,\
7149: model,imx,p,matcov,agemortsup);
7150:
7151: free_vector(lsurv,1,AGESUP);
7152: free_vector(lpop,1,AGESUP);
7153: free_vector(tpop,1,AGESUP);
1.136 brouard 7154: #ifdef GSL
7155: free_ivector(cens,1,n);
7156: free_vector(agecens,1,n);
7157: free_ivector(dcwave,1,n);
7158: free_matrix(ximort,1,NDIM,1,NDIM);
7159: #endif
1.186 brouard 7160: } /* Endof if mle==-3 mortality only */
7161: /* Standard maximisation */
1.126 brouard 7162: else{ /* For mle >=1 */
1.132 brouard 7163: globpr=0;/* debug */
1.186 brouard 7164: /* Computes likelihood for initial parameters */
1.132 brouard 7165: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7166: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7167: for (k=1; k<=npar;k++)
7168: printf(" %d %8.5f",k,p[k]);
7169: printf("\n");
1.186 brouard 7170: globpr=1; /* again, to print the contributions */
1.126 brouard 7171: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7172: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7173: for (k=1; k<=npar;k++)
7174: printf(" %d %8.5f",k,p[k]);
7175: printf("\n");
1.186 brouard 7176: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126 brouard 7177: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7178: }
7179:
7180: /*--------- results files --------------*/
1.192 ! brouard 7181: 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 7182:
7183:
7184: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7185: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7186: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7187: for(i=1,jk=1; i <=nlstate; i++){
7188: for(k=1; k <=(nlstate+ndeath); k++){
7189: if (k != i) {
7190: printf("%d%d ",i,k);
7191: fprintf(ficlog,"%d%d ",i,k);
7192: fprintf(ficres,"%1d%1d ",i,k);
7193: for(j=1; j <=ncovmodel; j++){
1.190 brouard 7194: printf("%12.7f ",p[jk]);
7195: fprintf(ficlog,"%12.7f ",p[jk]);
7196: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 7197: jk++;
7198: }
7199: printf("\n");
7200: fprintf(ficlog,"\n");
7201: fprintf(ficres,"\n");
7202: }
7203: }
7204: }
7205: if(mle!=0){
7206: /* Computing hessian and covariance matrix */
7207: ftolhess=ftol; /* Usually correct */
7208: hesscov(matcov, p, npar, delti, ftolhess, func);
7209: }
7210: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7211: printf("# Scales (for hessian or gradient estimation)\n");
7212: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7213: for(i=1,jk=1; i <=nlstate; i++){
7214: for(j=1; j <=nlstate+ndeath; j++){
7215: if (j!=i) {
7216: fprintf(ficres,"%1d%1d",i,j);
7217: printf("%1d%1d",i,j);
7218: fprintf(ficlog,"%1d%1d",i,j);
7219: for(k=1; k<=ncovmodel;k++){
7220: printf(" %.5e",delti[jk]);
7221: fprintf(ficlog," %.5e",delti[jk]);
7222: fprintf(ficres," %.5e",delti[jk]);
7223: jk++;
7224: }
7225: printf("\n");
7226: fprintf(ficlog,"\n");
7227: fprintf(ficres,"\n");
7228: }
7229: }
7230: }
7231:
7232: 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");
7233: if(mle>=1)
7234: 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");
7235: 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");
7236: /* # 121 Var(a12)\n\ */
7237: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7238: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7239: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7240: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7241: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7242: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7243: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7244:
7245:
7246: /* Just to have a covariance matrix which will be more understandable
7247: even is we still don't want to manage dictionary of variables
7248: */
7249: for(itimes=1;itimes<=2;itimes++){
7250: jj=0;
7251: for(i=1; i <=nlstate; i++){
7252: for(j=1; j <=nlstate+ndeath; j++){
7253: if(j==i) continue;
7254: for(k=1; k<=ncovmodel;k++){
7255: jj++;
7256: ca[0]= k+'a'-1;ca[1]='\0';
7257: if(itimes==1){
7258: if(mle>=1)
7259: printf("#%1d%1d%d",i,j,k);
7260: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7261: fprintf(ficres,"#%1d%1d%d",i,j,k);
7262: }else{
7263: if(mle>=1)
7264: printf("%1d%1d%d",i,j,k);
7265: fprintf(ficlog,"%1d%1d%d",i,j,k);
7266: fprintf(ficres,"%1d%1d%d",i,j,k);
7267: }
7268: ll=0;
7269: for(li=1;li <=nlstate; li++){
7270: for(lj=1;lj <=nlstate+ndeath; lj++){
7271: if(lj==li) continue;
7272: for(lk=1;lk<=ncovmodel;lk++){
7273: ll++;
7274: if(ll<=jj){
7275: cb[0]= lk +'a'-1;cb[1]='\0';
7276: if(ll<jj){
7277: if(itimes==1){
7278: if(mle>=1)
7279: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7280: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7281: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7282: }else{
7283: if(mle>=1)
7284: printf(" %.5e",matcov[jj][ll]);
7285: fprintf(ficlog," %.5e",matcov[jj][ll]);
7286: fprintf(ficres," %.5e",matcov[jj][ll]);
7287: }
7288: }else{
7289: if(itimes==1){
7290: if(mle>=1)
7291: printf(" Var(%s%1d%1d)",ca,i,j);
7292: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7293: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7294: }else{
7295: if(mle>=1)
7296: printf(" %.5e",matcov[jj][ll]);
7297: fprintf(ficlog," %.5e",matcov[jj][ll]);
7298: fprintf(ficres," %.5e",matcov[jj][ll]);
7299: }
7300: }
7301: }
7302: } /* end lk */
7303: } /* end lj */
7304: } /* end li */
7305: if(mle>=1)
7306: printf("\n");
7307: fprintf(ficlog,"\n");
7308: fprintf(ficres,"\n");
7309: numlinepar++;
7310: } /* end k*/
7311: } /*end j */
7312: } /* end i */
7313: } /* end itimes */
7314:
7315: fflush(ficlog);
7316: fflush(ficres);
7317:
7318: while((c=getc(ficpar))=='#' && c!= EOF){
7319: ungetc(c,ficpar);
7320: fgets(line, MAXLINE, ficpar);
1.141 brouard 7321: fputs(line,stdout);
1.126 brouard 7322: fputs(line,ficparo);
7323: }
7324: ungetc(c,ficpar);
7325:
7326: estepm=0;
7327: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7328: if (estepm==0 || estepm < stepm) estepm=stepm;
7329: if (fage <= 2) {
7330: bage = ageminpar;
7331: fage = agemaxpar;
7332: }
7333:
7334: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7335: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7336: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7337:
7338: /* Other stuffs, more or less useful */
1.126 brouard 7339: while((c=getc(ficpar))=='#' && c!= EOF){
7340: ungetc(c,ficpar);
7341: fgets(line, MAXLINE, ficpar);
1.141 brouard 7342: fputs(line,stdout);
1.126 brouard 7343: fputs(line,ficparo);
7344: }
7345: ungetc(c,ficpar);
7346:
7347: 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);
7348: 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);
7349: 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);
7350: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7351: 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);
7352:
7353: while((c=getc(ficpar))=='#' && c!= EOF){
7354: ungetc(c,ficpar);
7355: fgets(line, MAXLINE, ficpar);
1.141 brouard 7356: fputs(line,stdout);
1.126 brouard 7357: fputs(line,ficparo);
7358: }
7359: ungetc(c,ficpar);
7360:
7361:
7362: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7363: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7364:
7365: fscanf(ficpar,"pop_based=%d\n",&popbased);
7366: fprintf(ficparo,"pop_based=%d\n",popbased);
7367: fprintf(ficres,"pop_based=%d\n",popbased);
7368:
7369: while((c=getc(ficpar))=='#' && c!= EOF){
7370: ungetc(c,ficpar);
7371: fgets(line, MAXLINE, ficpar);
1.141 brouard 7372: fputs(line,stdout);
1.126 brouard 7373: fputs(line,ficparo);
7374: }
7375: ungetc(c,ficpar);
7376:
7377: 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);
7378: 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);
7379: 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);
7380: 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);
7381: 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);
7382: /* day and month of proj2 are not used but only year anproj2.*/
7383:
7384:
7385:
1.145 brouard 7386: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7387: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7388:
7389: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7390: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7391:
7392: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7393: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7394: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7395:
7396: /*------------ free_vector -------------*/
7397: /* chdir(path); */
7398:
7399: free_ivector(wav,1,imx);
7400: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7401: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7402: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7403: free_lvector(num,1,n);
7404: free_vector(agedc,1,n);
7405: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7406: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7407: fclose(ficparo);
7408: fclose(ficres);
7409:
7410:
1.186 brouard 7411: /* Other results (useful)*/
7412:
7413:
1.126 brouard 7414: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7415: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7416: prlim=matrix(1,nlstate,1,nlstate);
7417: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7418: fclose(ficrespl);
7419:
1.145 brouard 7420: #ifdef FREEEXIT2
7421: #include "freeexit2.h"
7422: #endif
7423:
1.126 brouard 7424: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7425: /*#include "hpijx.h"*/
7426: hPijx(p, bage, fage);
1.145 brouard 7427: fclose(ficrespij);
1.126 brouard 7428:
1.145 brouard 7429: /*-------------- Variance of one-step probabilities---*/
7430: k=1;
1.126 brouard 7431: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7432:
7433:
7434: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7435: for(i=1;i<=AGESUP;i++)
7436: for(j=1;j<=NCOVMAX;j++)
7437: for(k=1;k<=NCOVMAX;k++)
7438: probs[i][j][k]=0.;
7439:
7440: /*---------- Forecasting ------------------*/
7441: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7442: if(prevfcast==1){
7443: /* if(stepm ==1){*/
7444: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7445: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7446: /* } */
7447: /* else{ */
7448: /* erreur=108; */
7449: /* 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); */
7450: /* 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); */
7451: /* } */
7452: }
1.186 brouard 7453:
7454: /* ------ Other prevalence ratios------------ */
1.126 brouard 7455:
1.127 brouard 7456: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7457:
7458: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7459: /* 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",\
7460: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7461: */
1.126 brouard 7462:
1.127 brouard 7463: if (mobilav!=0) {
7464: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7465: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7466: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7467: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7468: }
1.126 brouard 7469: }
7470:
7471:
1.127 brouard 7472: /*---------- Health expectancies, no variances ------------*/
7473:
1.126 brouard 7474: strcpy(filerese,"e");
7475: strcat(filerese,fileres);
7476: if((ficreseij=fopen(filerese,"w"))==NULL) {
7477: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7478: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7479: }
7480: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7481: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7482: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7483: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7484:
7485: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7486: fprintf(ficreseij,"\n#****** ");
7487: for(j=1;j<=cptcoveff;j++) {
7488: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7489: }
7490: fprintf(ficreseij,"******\n");
7491:
7492: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7493: oldm=oldms;savm=savms;
7494: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7495:
7496: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7497: /*}*/
1.127 brouard 7498: }
7499: fclose(ficreseij);
7500:
7501:
7502: /*---------- Health expectancies and variances ------------*/
7503:
7504:
7505: strcpy(filerest,"t");
7506: strcat(filerest,fileres);
7507: if((ficrest=fopen(filerest,"w"))==NULL) {
7508: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7509: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7510: }
7511: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7512: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7513:
1.126 brouard 7514:
7515: strcpy(fileresstde,"stde");
7516: strcat(fileresstde,fileres);
7517: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7518: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7519: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7520: }
7521: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7522: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7523:
7524: strcpy(filerescve,"cve");
7525: strcat(filerescve,fileres);
7526: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7527: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7528: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7529: }
7530: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7531: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7532:
7533: strcpy(fileresv,"v");
7534: strcat(fileresv,fileres);
7535: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7536: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7537: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7538: }
7539: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7540: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7541:
1.145 brouard 7542: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7543: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7544:
7545: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7546: fprintf(ficrest,"\n#****** ");
1.126 brouard 7547: for(j=1;j<=cptcoveff;j++)
7548: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7549: fprintf(ficrest,"******\n");
7550:
7551: fprintf(ficresstdeij,"\n#****** ");
7552: fprintf(ficrescveij,"\n#****** ");
7553: for(j=1;j<=cptcoveff;j++) {
7554: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7555: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7556: }
7557: fprintf(ficresstdeij,"******\n");
7558: fprintf(ficrescveij,"******\n");
7559:
7560: fprintf(ficresvij,"\n#****** ");
7561: for(j=1;j<=cptcoveff;j++)
7562: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7563: fprintf(ficresvij,"******\n");
7564:
7565: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7566: oldm=oldms;savm=savms;
1.127 brouard 7567: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7568: /*
7569: */
7570: /* goto endfree; */
1.126 brouard 7571:
7572: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7573: pstamp(ficrest);
1.145 brouard 7574:
7575:
1.128 brouard 7576: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7577: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7578: cptcod= 0; /* To be deleted */
7579: 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 7580: 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 7581: if(vpopbased==1)
7582: 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);
7583: else
7584: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7585: fprintf(ficrest,"# Age e.. (std) ");
7586: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7587: fprintf(ficrest,"\n");
1.126 brouard 7588:
1.128 brouard 7589: epj=vector(1,nlstate+1);
7590: for(age=bage; age <=fage ;age++){
7591: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7592: if (vpopbased==1) {
7593: if(mobilav ==0){
7594: for(i=1; i<=nlstate;i++)
7595: prlim[i][i]=probs[(int)age][i][k];
7596: }else{ /* mobilav */
7597: for(i=1; i<=nlstate;i++)
7598: prlim[i][i]=mobaverage[(int)age][i][k];
7599: }
1.126 brouard 7600: }
7601:
1.128 brouard 7602: fprintf(ficrest," %4.0f",age);
7603: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7604: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7605: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7606: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7607: }
7608: epj[nlstate+1] +=epj[j];
1.126 brouard 7609: }
7610:
1.128 brouard 7611: for(i=1, vepp=0.;i <=nlstate;i++)
7612: for(j=1;j <=nlstate;j++)
7613: vepp += vareij[i][j][(int)age];
7614: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7615: for(j=1;j <=nlstate;j++){
7616: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7617: }
7618: fprintf(ficrest,"\n");
1.126 brouard 7619: }
7620: }
7621: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7622: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7623: free_vector(epj,1,nlstate+1);
1.145 brouard 7624: /*}*/
1.126 brouard 7625: }
7626: free_vector(weight,1,n);
1.145 brouard 7627: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7628: free_imatrix(s,1,maxwav+1,1,n);
7629: free_matrix(anint,1,maxwav,1,n);
7630: free_matrix(mint,1,maxwav,1,n);
7631: free_ivector(cod,1,n);
7632: free_ivector(tab,1,NCOVMAX);
7633: fclose(ficresstdeij);
7634: fclose(ficrescveij);
7635: fclose(ficresvij);
7636: fclose(ficrest);
7637: fclose(ficpar);
7638:
7639: /*------- Variance of period (stable) prevalence------*/
7640:
7641: strcpy(fileresvpl,"vpl");
7642: strcat(fileresvpl,fileres);
7643: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7644: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7645: exit(0);
7646: }
7647: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7648:
1.145 brouard 7649: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7650: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7651:
7652: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7653: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7654: for(j=1;j<=cptcoveff;j++)
7655: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7656: fprintf(ficresvpl,"******\n");
7657:
7658: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7659: oldm=oldms;savm=savms;
7660: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7661: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7662: /*}*/
1.126 brouard 7663: }
7664:
7665: fclose(ficresvpl);
7666:
7667: /*---------- End : free ----------------*/
7668: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7669: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7670: } /* mle==-3 arrives here for freeing */
1.164 brouard 7671: /* endfree:*/
1.141 brouard 7672: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7673: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7674: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7675: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7676: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7677: free_matrix(covar,0,NCOVMAX,1,n);
7678: free_matrix(matcov,1,npar,1,npar);
7679: /*free_vector(delti,1,npar);*/
7680: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7681: free_matrix(agev,1,maxwav,1,imx);
7682: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7683:
1.145 brouard 7684: free_ivector(ncodemax,1,NCOVMAX);
1.192 ! brouard 7685: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 7686: free_ivector(Tvar,1,NCOVMAX);
7687: free_ivector(Tprod,1,NCOVMAX);
7688: free_ivector(Tvaraff,1,NCOVMAX);
7689: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7690:
7691: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7692: free_imatrix(codtab,1,100,1,10);
7693: fflush(fichtm);
7694: fflush(ficgp);
7695:
7696:
7697: if((nberr >0) || (nbwarn>0)){
7698: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7699: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7700: }else{
7701: printf("End of Imach\n");
7702: fprintf(ficlog,"End of Imach\n");
7703: }
7704: printf("See log file on %s\n",filelog);
7705: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7706: /*(void) gettimeofday(&end_time,&tzp);*/
7707: rend_time = time(NULL);
7708: end_time = *localtime(&rend_time);
7709: /* tml = *localtime(&end_time.tm_sec); */
7710: strcpy(strtend,asctime(&end_time));
1.126 brouard 7711: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7712: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7713: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7714:
1.157 brouard 7715: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7716: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7717: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7718: /* printf("Total time was %d uSec.\n", total_usecs);*/
7719: /* if(fileappend(fichtm,optionfilehtm)){ */
7720: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7721: fclose(fichtm);
7722: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7723: fclose(fichtmcov);
7724: fclose(ficgp);
7725: fclose(ficlog);
7726: /*------ End -----------*/
7727:
7728:
7729: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 7730: #ifdef WIN32
7731: if (_chdir(pathcd) != 0)
7732: printf("Can't move to directory %s!\n",path);
7733: if(_getcwd(pathcd,MAXLINE) > 0)
7734: #else
1.126 brouard 7735: if(chdir(pathcd) != 0)
1.184 brouard 7736: printf("Can't move to directory %s!\n", path);
7737: if (getcwd(pathcd, MAXLINE) > 0)
7738: #endif
1.126 brouard 7739: printf("Current directory %s!\n",pathcd);
7740: /*strcat(plotcmd,CHARSEPARATOR);*/
7741: sprintf(plotcmd,"gnuplot");
1.157 brouard 7742: #ifdef _WIN32
1.126 brouard 7743: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7744: #endif
7745: if(!stat(plotcmd,&info)){
1.158 brouard 7746: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7747: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7748: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7749: }else
7750: strcpy(pplotcmd,plotcmd);
1.157 brouard 7751: #ifdef __unix
1.126 brouard 7752: strcpy(plotcmd,GNUPLOTPROGRAM);
7753: if(!stat(plotcmd,&info)){
1.158 brouard 7754: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7755: }else
7756: strcpy(pplotcmd,plotcmd);
7757: #endif
7758: }else
7759: strcpy(pplotcmd,plotcmd);
7760:
7761: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7762: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7763:
7764: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7765: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7766: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7767: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7768: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7769: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7770: }
1.158 brouard 7771: printf(" Successful, please wait...");
1.126 brouard 7772: while (z[0] != 'q') {
7773: /* chdir(path); */
1.154 brouard 7774: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7775: scanf("%s",z);
7776: /* if (z[0] == 'c') system("./imach"); */
7777: if (z[0] == 'e') {
1.158 brouard 7778: #ifdef __APPLE__
1.152 brouard 7779: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7780: #elif __linux
7781: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7782: #else
1.152 brouard 7783: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7784: #endif
7785: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7786: system(pplotcmd);
1.126 brouard 7787: }
7788: else if (z[0] == 'g') system(plotcmd);
7789: else if (z[0] == 'q') exit(0);
7790: }
7791: end:
7792: while (z[0] != 'q') {
7793: printf("\nType q for exiting: ");
7794: scanf("%s",z);
7795: }
7796: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>