Annotation of imach/src/imach.c, revision 1.194
1.194 ! brouard 1: /* $Id: imach.c,v 1.193 2015/08/04 07:17:42 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.194 ! brouard 4: Revision 1.193 2015/08/04 07:17:42 brouard
! 5: Summary: 0.98q4
! 6:
1.193 brouard 7: Revision 1.192 2015/07/16 16:49:02 brouard
8: Summary: Fixing some outputs
9:
1.192 brouard 10: Revision 1.191 2015/07/14 10:00:33 brouard
11: Summary: Some fixes
12:
1.191 brouard 13: Revision 1.190 2015/05/05 08:51:13 brouard
14: Summary: Adding digits in output parameters (7 digits instead of 6)
15:
16: Fix 1+age+.
17:
1.190 brouard 18: Revision 1.189 2015/04/30 14:45:16 brouard
19: Summary: 0.98q2
20:
1.189 brouard 21: Revision 1.188 2015/04/30 08:27:53 brouard
22: *** empty log message ***
23:
1.188 brouard 24: Revision 1.187 2015/04/29 09:11:15 brouard
25: *** empty log message ***
26:
1.187 brouard 27: Revision 1.186 2015/04/23 12:01:52 brouard
28: Summary: V1*age is working now, version 0.98q1
29:
30: Some codes had been disabled in order to simplify and Vn*age was
31: working in the optimization phase, ie, giving correct MLE parameters,
32: but, as usual, outputs were not correct and program core dumped.
33:
1.186 brouard 34: Revision 1.185 2015/03/11 13:26:42 brouard
35: Summary: Inclusion of compile and links command line for Intel Compiler
36:
1.185 brouard 37: Revision 1.184 2015/03/11 11:52:39 brouard
38: Summary: Back from Windows 8. Intel Compiler
39:
1.184 brouard 40: Revision 1.183 2015/03/10 20:34:32 brouard
41: Summary: 0.98q0, trying with directest, mnbrak fixed
42:
43: We use directest instead of original Powell test; probably no
44: incidence on the results, but better justifications;
45: We fixed Numerical Recipes mnbrak routine which was wrong and gave
46: wrong results.
47:
1.183 brouard 48: Revision 1.182 2015/02/12 08:19:57 brouard
49: Summary: Trying to keep directest which seems simpler and more general
50: Author: Nicolas Brouard
51:
1.182 brouard 52: Revision 1.181 2015/02/11 23:22:24 brouard
53: Summary: Comments on Powell added
54:
55: Author:
56:
1.181 brouard 57: Revision 1.180 2015/02/11 17:33:45 brouard
58: Summary: Finishing move from main to function (hpijx and prevalence_limit)
59:
1.180 brouard 60: Revision 1.179 2015/01/04 09:57:06 brouard
61: Summary: back to OS/X
62:
1.179 brouard 63: Revision 1.178 2015/01/04 09:35:48 brouard
64: *** empty log message ***
65:
1.178 brouard 66: Revision 1.177 2015/01/03 18:40:56 brouard
67: Summary: Still testing ilc32 on OSX
68:
1.177 brouard 69: Revision 1.176 2015/01/03 16:45:04 brouard
70: *** empty log message ***
71:
1.176 brouard 72: Revision 1.175 2015/01/03 16:33:42 brouard
73: *** empty log message ***
74:
1.175 brouard 75: Revision 1.174 2015/01/03 16:15:49 brouard
76: Summary: Still in cross-compilation
77:
1.174 brouard 78: Revision 1.173 2015/01/03 12:06:26 brouard
79: Summary: trying to detect cross-compilation
80:
1.173 brouard 81: Revision 1.172 2014/12/27 12:07:47 brouard
82: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
83:
1.172 brouard 84: Revision 1.171 2014/12/23 13:26:59 brouard
85: Summary: Back from Visual C
86:
87: Still problem with utsname.h on Windows
88:
1.171 brouard 89: Revision 1.170 2014/12/23 11:17:12 brouard
90: Summary: Cleaning some \%% back to %%
91:
92: The escape was mandatory for a specific compiler (which one?), but too many warnings.
93:
1.170 brouard 94: Revision 1.169 2014/12/22 23:08:31 brouard
95: Summary: 0.98p
96:
97: Outputs some informations on compiler used, OS etc. Testing on different platforms.
98:
1.169 brouard 99: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 100: Summary: update
1.169 brouard 101:
1.168 brouard 102: Revision 1.167 2014/12/22 13:50:56 brouard
103: Summary: Testing uname and compiler version and if compiled 32 or 64
104:
105: Testing on Linux 64
106:
1.167 brouard 107: Revision 1.166 2014/12/22 11:40:47 brouard
108: *** empty log message ***
109:
1.166 brouard 110: Revision 1.165 2014/12/16 11:20:36 brouard
111: Summary: After compiling on Visual C
112:
113: * imach.c (Module): Merging 1.61 to 1.162
114:
1.165 brouard 115: Revision 1.164 2014/12/16 10:52:11 brouard
116: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
117:
118: * imach.c (Module): Merging 1.61 to 1.162
119:
1.164 brouard 120: Revision 1.163 2014/12/16 10:30:11 brouard
121: * imach.c (Module): Merging 1.61 to 1.162
122:
1.163 brouard 123: Revision 1.162 2014/09/25 11:43:39 brouard
124: Summary: temporary backup 0.99!
125:
1.162 brouard 126: Revision 1.1 2014/09/16 11:06:58 brouard
127: Summary: With some code (wrong) for nlopt
128:
129: Author:
130:
131: Revision 1.161 2014/09/15 20:41:41 brouard
132: Summary: Problem with macro SQR on Intel compiler
133:
1.161 brouard 134: Revision 1.160 2014/09/02 09:24:05 brouard
135: *** empty log message ***
136:
1.160 brouard 137: Revision 1.159 2014/09/01 10:34:10 brouard
138: Summary: WIN32
139: Author: Brouard
140:
1.159 brouard 141: Revision 1.158 2014/08/27 17:11:51 brouard
142: *** empty log message ***
143:
1.158 brouard 144: Revision 1.157 2014/08/27 16:26:55 brouard
145: Summary: Preparing windows Visual studio version
146: Author: Brouard
147:
148: In order to compile on Visual studio, time.h is now correct and time_t
149: and tm struct should be used. difftime should be used but sometimes I
150: just make the differences in raw time format (time(&now).
151: Trying to suppress #ifdef LINUX
152: Add xdg-open for __linux in order to open default browser.
153:
1.157 brouard 154: Revision 1.156 2014/08/25 20:10:10 brouard
155: *** empty log message ***
156:
1.156 brouard 157: Revision 1.155 2014/08/25 18:32:34 brouard
158: Summary: New compile, minor changes
159: Author: Brouard
160:
1.155 brouard 161: Revision 1.154 2014/06/20 17:32:08 brouard
162: Summary: Outputs now all graphs of convergence to period prevalence
163:
1.154 brouard 164: Revision 1.153 2014/06/20 16:45:46 brouard
165: Summary: If 3 live state, convergence to period prevalence on same graph
166: Author: Brouard
167:
1.153 brouard 168: Revision 1.152 2014/06/18 17:54:09 brouard
169: Summary: open browser, use gnuplot on same dir than imach if not found in the path
170:
1.152 brouard 171: Revision 1.151 2014/06/18 16:43:30 brouard
172: *** empty log message ***
173:
1.151 brouard 174: Revision 1.150 2014/06/18 16:42:35 brouard
175: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
176: Author: brouard
177:
1.150 brouard 178: Revision 1.149 2014/06/18 15:51:14 brouard
179: Summary: Some fixes in parameter files errors
180: Author: Nicolas Brouard
181:
1.149 brouard 182: Revision 1.148 2014/06/17 17:38:48 brouard
183: Summary: Nothing new
184: Author: Brouard
185:
186: Just a new packaging for OS/X version 0.98nS
187:
1.148 brouard 188: Revision 1.147 2014/06/16 10:33:11 brouard
189: *** empty log message ***
190:
1.147 brouard 191: Revision 1.146 2014/06/16 10:20:28 brouard
192: Summary: Merge
193: Author: Brouard
194:
195: Merge, before building revised version.
196:
1.146 brouard 197: Revision 1.145 2014/06/10 21:23:15 brouard
198: Summary: Debugging with valgrind
199: Author: Nicolas Brouard
200:
201: Lot of changes in order to output the results with some covariates
202: After the Edimburgh REVES conference 2014, it seems mandatory to
203: improve the code.
204: No more memory valgrind error but a lot has to be done in order to
205: continue the work of splitting the code into subroutines.
206: Also, decodemodel has been improved. Tricode is still not
207: optimal. nbcode should be improved. Documentation has been added in
208: the source code.
209:
1.144 brouard 210: Revision 1.143 2014/01/26 09:45:38 brouard
211: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
212:
213: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
214: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
215:
1.143 brouard 216: Revision 1.142 2014/01/26 03:57:36 brouard
217: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
218:
219: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
220:
1.142 brouard 221: Revision 1.141 2014/01/26 02:42:01 brouard
222: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
223:
1.141 brouard 224: Revision 1.140 2011/09/02 10:37:54 brouard
225: Summary: times.h is ok with mingw32 now.
226:
1.140 brouard 227: Revision 1.139 2010/06/14 07:50:17 brouard
228: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
229: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
230:
1.139 brouard 231: Revision 1.138 2010/04/30 18:19:40 brouard
232: *** empty log message ***
233:
1.138 brouard 234: Revision 1.137 2010/04/29 18:11:38 brouard
235: (Module): Checking covariates for more complex models
236: than V1+V2. A lot of change to be done. Unstable.
237:
1.137 brouard 238: Revision 1.136 2010/04/26 20:30:53 brouard
239: (Module): merging some libgsl code. Fixing computation
240: of likelione (using inter/intrapolation if mle = 0) in order to
241: get same likelihood as if mle=1.
242: Some cleaning of code and comments added.
243:
1.136 brouard 244: Revision 1.135 2009/10/29 15:33:14 brouard
245: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
246:
1.135 brouard 247: Revision 1.134 2009/10/29 13:18:53 brouard
248: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
249:
1.134 brouard 250: Revision 1.133 2009/07/06 10:21:25 brouard
251: just nforces
252:
1.133 brouard 253: Revision 1.132 2009/07/06 08:22:05 brouard
254: Many tings
255:
1.132 brouard 256: Revision 1.131 2009/06/20 16:22:47 brouard
257: Some dimensions resccaled
258:
1.131 brouard 259: Revision 1.130 2009/05/26 06:44:34 brouard
260: (Module): Max Covariate is now set to 20 instead of 8. A
261: lot of cleaning with variables initialized to 0. Trying to make
262: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
263:
1.130 brouard 264: Revision 1.129 2007/08/31 13:49:27 lievre
265: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
266:
1.129 lievre 267: Revision 1.128 2006/06/30 13:02:05 brouard
268: (Module): Clarifications on computing e.j
269:
1.128 brouard 270: Revision 1.127 2006/04/28 18:11:50 brouard
271: (Module): Yes the sum of survivors was wrong since
272: imach-114 because nhstepm was no more computed in the age
273: loop. Now we define nhstepma in the age loop.
274: (Module): In order to speed up (in case of numerous covariates) we
275: compute health expectancies (without variances) in a first step
276: and then all the health expectancies with variances or standard
277: deviation (needs data from the Hessian matrices) which slows the
278: computation.
279: In the future we should be able to stop the program is only health
280: expectancies and graph are needed without standard deviations.
281:
1.127 brouard 282: Revision 1.126 2006/04/28 17:23:28 brouard
283: (Module): Yes the sum of survivors was wrong since
284: imach-114 because nhstepm was no more computed in the age
285: loop. Now we define nhstepma in the age loop.
286: Version 0.98h
287:
1.126 brouard 288: Revision 1.125 2006/04/04 15:20:31 lievre
289: Errors in calculation of health expectancies. Age was not initialized.
290: Forecasting file added.
291:
292: Revision 1.124 2006/03/22 17:13:53 lievre
293: Parameters are printed with %lf instead of %f (more numbers after the comma).
294: The log-likelihood is printed in the log file
295:
296: Revision 1.123 2006/03/20 10:52:43 brouard
297: * imach.c (Module): <title> changed, corresponds to .htm file
298: name. <head> headers where missing.
299:
300: * imach.c (Module): Weights can have a decimal point as for
301: English (a comma might work with a correct LC_NUMERIC environment,
302: otherwise the weight is truncated).
303: Modification of warning when the covariates values are not 0 or
304: 1.
305: Version 0.98g
306:
307: Revision 1.122 2006/03/20 09:45:41 brouard
308: (Module): Weights can have a decimal point as for
309: English (a comma might work with a correct LC_NUMERIC environment,
310: otherwise the weight is truncated).
311: Modification of warning when the covariates values are not 0 or
312: 1.
313: Version 0.98g
314:
315: Revision 1.121 2006/03/16 17:45:01 lievre
316: * imach.c (Module): Comments concerning covariates added
317:
318: * imach.c (Module): refinements in the computation of lli if
319: status=-2 in order to have more reliable computation if stepm is
320: not 1 month. Version 0.98f
321:
322: Revision 1.120 2006/03/16 15:10:38 lievre
323: (Module): refinements in the computation of lli if
324: status=-2 in order to have more reliable computation if stepm is
325: not 1 month. Version 0.98f
326:
327: Revision 1.119 2006/03/15 17:42:26 brouard
328: (Module): Bug if status = -2, the loglikelihood was
329: computed as likelihood omitting the logarithm. Version O.98e
330:
331: Revision 1.118 2006/03/14 18:20:07 brouard
332: (Module): varevsij Comments added explaining the second
333: table of variances if popbased=1 .
334: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
335: (Module): Function pstamp added
336: (Module): Version 0.98d
337:
338: Revision 1.117 2006/03/14 17:16:22 brouard
339: (Module): varevsij Comments added explaining the second
340: table of variances if popbased=1 .
341: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
342: (Module): Function pstamp added
343: (Module): Version 0.98d
344:
345: Revision 1.116 2006/03/06 10:29:27 brouard
346: (Module): Variance-covariance wrong links and
347: varian-covariance of ej. is needed (Saito).
348:
349: Revision 1.115 2006/02/27 12:17:45 brouard
350: (Module): One freematrix added in mlikeli! 0.98c
351:
352: Revision 1.114 2006/02/26 12:57:58 brouard
353: (Module): Some improvements in processing parameter
354: filename with strsep.
355:
356: Revision 1.113 2006/02/24 14:20:24 brouard
357: (Module): Memory leaks checks with valgrind and:
358: datafile was not closed, some imatrix were not freed and on matrix
359: allocation too.
360:
361: Revision 1.112 2006/01/30 09:55:26 brouard
362: (Module): Back to gnuplot.exe instead of wgnuplot.exe
363:
364: Revision 1.111 2006/01/25 20:38:18 brouard
365: (Module): Lots of cleaning and bugs added (Gompertz)
366: (Module): Comments can be added in data file. Missing date values
367: can be a simple dot '.'.
368:
369: Revision 1.110 2006/01/25 00:51:50 brouard
370: (Module): Lots of cleaning and bugs added (Gompertz)
371:
372: Revision 1.109 2006/01/24 19:37:15 brouard
373: (Module): Comments (lines starting with a #) are allowed in data.
374:
375: Revision 1.108 2006/01/19 18:05:42 lievre
376: Gnuplot problem appeared...
377: To be fixed
378:
379: Revision 1.107 2006/01/19 16:20:37 brouard
380: Test existence of gnuplot in imach path
381:
382: Revision 1.106 2006/01/19 13:24:36 brouard
383: Some cleaning and links added in html output
384:
385: Revision 1.105 2006/01/05 20:23:19 lievre
386: *** empty log message ***
387:
388: Revision 1.104 2005/09/30 16:11:43 lievre
389: (Module): sump fixed, loop imx fixed, and simplifications.
390: (Module): If the status is missing at the last wave but we know
391: that the person is alive, then we can code his/her status as -2
392: (instead of missing=-1 in earlier versions) and his/her
393: contributions to the likelihood is 1 - Prob of dying from last
394: health status (= 1-p13= p11+p12 in the easiest case of somebody in
395: the healthy state at last known wave). Version is 0.98
396:
397: Revision 1.103 2005/09/30 15:54:49 lievre
398: (Module): sump fixed, loop imx fixed, and simplifications.
399:
400: Revision 1.102 2004/09/15 17:31:30 brouard
401: Add the possibility to read data file including tab characters.
402:
403: Revision 1.101 2004/09/15 10:38:38 brouard
404: Fix on curr_time
405:
406: Revision 1.100 2004/07/12 18:29:06 brouard
407: Add version for Mac OS X. Just define UNIX in Makefile
408:
409: Revision 1.99 2004/06/05 08:57:40 brouard
410: *** empty log message ***
411:
412: Revision 1.98 2004/05/16 15:05:56 brouard
413: New version 0.97 . First attempt to estimate force of mortality
414: directly from the data i.e. without the need of knowing the health
415: state at each age, but using a Gompertz model: log u =a + b*age .
416: This is the basic analysis of mortality and should be done before any
417: other analysis, in order to test if the mortality estimated from the
418: cross-longitudinal survey is different from the mortality estimated
419: from other sources like vital statistic data.
420:
421: The same imach parameter file can be used but the option for mle should be -3.
422:
1.133 brouard 423: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 424: former routines in order to include the new code within the former code.
425:
426: The output is very simple: only an estimate of the intercept and of
427: the slope with 95% confident intervals.
428:
429: Current limitations:
430: A) Even if you enter covariates, i.e. with the
431: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
432: B) There is no computation of Life Expectancy nor Life Table.
433:
434: Revision 1.97 2004/02/20 13:25:42 lievre
435: Version 0.96d. Population forecasting command line is (temporarily)
436: suppressed.
437:
438: Revision 1.96 2003/07/15 15:38:55 brouard
439: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
440: rewritten within the same printf. Workaround: many printfs.
441:
442: Revision 1.95 2003/07/08 07:54:34 brouard
443: * imach.c (Repository):
444: (Repository): Using imachwizard code to output a more meaningful covariance
445: matrix (cov(a12,c31) instead of numbers.
446:
447: Revision 1.94 2003/06/27 13:00:02 brouard
448: Just cleaning
449:
450: Revision 1.93 2003/06/25 16:33:55 brouard
451: (Module): On windows (cygwin) function asctime_r doesn't
452: exist so I changed back to asctime which exists.
453: (Module): Version 0.96b
454:
455: Revision 1.92 2003/06/25 16:30:45 brouard
456: (Module): On windows (cygwin) function asctime_r doesn't
457: exist so I changed back to asctime which exists.
458:
459: Revision 1.91 2003/06/25 15:30:29 brouard
460: * imach.c (Repository): Duplicated warning errors corrected.
461: (Repository): Elapsed time after each iteration is now output. It
462: helps to forecast when convergence will be reached. Elapsed time
463: is stamped in powell. We created a new html file for the graphs
464: concerning matrix of covariance. It has extension -cov.htm.
465:
466: Revision 1.90 2003/06/24 12:34:15 brouard
467: (Module): Some bugs corrected for windows. Also, when
468: mle=-1 a template is output in file "or"mypar.txt with the design
469: of the covariance matrix to be input.
470:
471: Revision 1.89 2003/06/24 12:30:52 brouard
472: (Module): Some bugs corrected for windows. Also, when
473: mle=-1 a template is output in file "or"mypar.txt with the design
474: of the covariance matrix to be input.
475:
476: Revision 1.88 2003/06/23 17:54:56 brouard
477: * 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.
478:
479: Revision 1.87 2003/06/18 12:26:01 brouard
480: Version 0.96
481:
482: Revision 1.86 2003/06/17 20:04:08 brouard
483: (Module): Change position of html and gnuplot routines and added
484: routine fileappend.
485:
486: Revision 1.85 2003/06/17 13:12:43 brouard
487: * imach.c (Repository): Check when date of death was earlier that
488: current date of interview. It may happen when the death was just
489: prior to the death. In this case, dh was negative and likelihood
490: was wrong (infinity). We still send an "Error" but patch by
491: assuming that the date of death was just one stepm after the
492: interview.
493: (Repository): Because some people have very long ID (first column)
494: we changed int to long in num[] and we added a new lvector for
495: memory allocation. But we also truncated to 8 characters (left
496: truncation)
497: (Repository): No more line truncation errors.
498:
499: Revision 1.84 2003/06/13 21:44:43 brouard
500: * imach.c (Repository): Replace "freqsummary" at a correct
501: place. It differs from routine "prevalence" which may be called
502: many times. Probs is memory consuming and must be used with
503: parcimony.
504: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
505:
506: Revision 1.83 2003/06/10 13:39:11 lievre
507: *** empty log message ***
508:
509: Revision 1.82 2003/06/05 15:57:20 brouard
510: Add log in imach.c and fullversion number is now printed.
511:
512: */
513: /*
514: Interpolated Markov Chain
515:
516: Short summary of the programme:
517:
518: This program computes Healthy Life Expectancies from
519: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
520: first survey ("cross") where individuals from different ages are
521: interviewed on their health status or degree of disability (in the
522: case of a health survey which is our main interest) -2- at least a
523: second wave of interviews ("longitudinal") which measure each change
524: (if any) in individual health status. Health expectancies are
525: computed from the time spent in each health state according to a
526: model. More health states you consider, more time is necessary to reach the
527: Maximum Likelihood of the parameters involved in the model. The
528: simplest model is the multinomial logistic model where pij is the
529: probability to be observed in state j at the second wave
530: conditional to be observed in state i at the first wave. Therefore
531: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
532: 'age' is age and 'sex' is a covariate. If you want to have a more
533: complex model than "constant and age", you should modify the program
534: where the markup *Covariates have to be included here again* invites
535: you to do it. More covariates you add, slower the
536: convergence.
537:
538: The advantage of this computer programme, compared to a simple
539: multinomial logistic model, is clear when the delay between waves is not
540: identical for each individual. Also, if a individual missed an
541: intermediate interview, the information is lost, but taken into
542: account using an interpolation or extrapolation.
543:
544: hPijx is the probability to be observed in state i at age x+h
545: conditional to the observed state i at age x. The delay 'h' can be
546: split into an exact number (nh*stepm) of unobserved intermediate
547: states. This elementary transition (by month, quarter,
548: semester or year) is modelled as a multinomial logistic. The hPx
549: matrix is simply the matrix product of nh*stepm elementary matrices
550: and the contribution of each individual to the likelihood is simply
551: hPijx.
552:
553: Also this programme outputs the covariance matrix of the parameters but also
554: of the life expectancies. It also computes the period (stable) prevalence.
555:
1.133 brouard 556: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
557: Institut national d'études démographiques, Paris.
1.126 brouard 558: This software have been partly granted by Euro-REVES, a concerted action
559: from the European Union.
560: It is copyrighted identically to a GNU software product, ie programme and
561: software can be distributed freely for non commercial use. Latest version
562: can be accessed at http://euroreves.ined.fr/imach .
563:
564: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
565: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
566:
567: **********************************************************************/
568: /*
569: main
570: read parameterfile
571: read datafile
572: concatwav
573: freqsummary
574: if (mle >= 1)
575: mlikeli
576: print results files
577: if mle==1
578: computes hessian
579: read end of parameter file: agemin, agemax, bage, fage, estepm
580: begin-prev-date,...
581: open gnuplot file
582: open html file
1.145 brouard 583: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
584: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
585: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
586: freexexit2 possible for memory heap.
587:
588: h Pij x | pij_nom ficrestpij
589: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
590: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
591: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
592:
593: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
594: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
595: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
596: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
597: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
598:
1.126 brouard 599: forecasting if prevfcast==1 prevforecast call prevalence()
600: health expectancies
601: Variance-covariance of DFLE
602: prevalence()
603: movingaverage()
604: varevsij()
605: if popbased==1 varevsij(,popbased)
606: total life expectancies
607: Variance of period (stable) prevalence
608: end
609: */
610:
1.187 brouard 611: /* #define DEBUG */
612: /* #define DEBUGBRENT */
1.165 brouard 613: #define POWELL /* Instead of NLOPT */
1.192 brouard 614: #define POWELLF1F3 /* Skip test */
1.186 brouard 615: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
616: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 617:
618: #include <math.h>
619: #include <stdio.h>
620: #include <stdlib.h>
621: #include <string.h>
1.159 brouard 622:
623: #ifdef _WIN32
624: #include <io.h>
1.172 brouard 625: #include <windows.h>
626: #include <tchar.h>
1.159 brouard 627: #else
1.126 brouard 628: #include <unistd.h>
1.159 brouard 629: #endif
1.126 brouard 630:
631: #include <limits.h>
632: #include <sys/types.h>
1.171 brouard 633:
634: #if defined(__GNUC__)
635: #include <sys/utsname.h> /* Doesn't work on Windows */
636: #endif
637:
1.126 brouard 638: #include <sys/stat.h>
639: #include <errno.h>
1.159 brouard 640: /* extern int errno; */
1.126 brouard 641:
1.157 brouard 642: /* #ifdef LINUX */
643: /* #include <time.h> */
644: /* #include "timeval.h" */
645: /* #else */
646: /* #include <sys/time.h> */
647: /* #endif */
648:
1.126 brouard 649: #include <time.h>
650:
1.136 brouard 651: #ifdef GSL
652: #include <gsl/gsl_errno.h>
653: #include <gsl/gsl_multimin.h>
654: #endif
655:
1.167 brouard 656:
1.162 brouard 657: #ifdef NLOPT
658: #include <nlopt.h>
659: typedef struct {
660: double (* function)(double [] );
661: } myfunc_data ;
662: #endif
663:
1.126 brouard 664: /* #include <libintl.h> */
665: /* #define _(String) gettext (String) */
666:
1.141 brouard 667: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 668:
669: #define GNUPLOTPROGRAM "gnuplot"
670: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
671: #define FILENAMELENGTH 132
672:
673: #define GLOCK_ERROR_NOPATH -1 /* empty path */
674: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
675:
1.144 brouard 676: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
677: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 678:
679: #define NINTERVMAX 8
1.144 brouard 680: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
681: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
682: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 683: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 684: #define MAXN 20000
1.144 brouard 685: #define YEARM 12. /**< Number of months per year */
1.126 brouard 686: #define AGESUP 130
687: #define AGEBASE 40
1.194 ! brouard 688: #define AGEOVERFLOW 1.e20
1.164 brouard 689: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 690: #ifdef _WIN32
691: #define DIRSEPARATOR '\\'
692: #define CHARSEPARATOR "\\"
693: #define ODIRSEPARATOR '/'
694: #else
1.126 brouard 695: #define DIRSEPARATOR '/'
696: #define CHARSEPARATOR "/"
697: #define ODIRSEPARATOR '\\'
698: #endif
699:
1.194 ! brouard 700: /* $Id: imach.c,v 1.193 2015/08/04 07:17:42 brouard Exp $ */
1.126 brouard 701: /* $State: Exp $ */
702:
1.194 ! brouard 703: char version[]="Imach version 0.98q5, August 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
! 704: char fullversion[]="$Revision: 1.193 $ $Date: 2015/08/04 07:17:42 $";
1.126 brouard 705: char strstart[80];
706: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 707: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 708: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 709: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
710: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
711: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
712: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
713: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
714: int cptcovprodnoage=0; /**< Number of covariate products without age */
715: int cptcoveff=0; /* Total number of covariates to vary for printing results */
716: int cptcov=0; /* Working variable */
1.126 brouard 717: int npar=NPARMAX;
718: int nlstate=2; /* Number of live states */
719: int ndeath=1; /* Number of dead states */
1.130 brouard 720: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 721: int popbased=0;
722:
723: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 724: int maxwav=0; /* Maxim number of waves */
725: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
726: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
727: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 728: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 729: int mle=1, weightopt=0;
1.126 brouard 730: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
731: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
732: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
733: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 734: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 735: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 736: double **matprod2(); /* test */
1.126 brouard 737: double **oldm, **newm, **savm; /* Working pointers to matrices */
738: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 739: /*FILE *fic ; */ /* Used in readdata only */
740: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 741: FILE *ficlog, *ficrespow;
1.130 brouard 742: int globpr=0; /* Global variable for printing or not */
1.126 brouard 743: double fretone; /* Only one call to likelihood */
1.130 brouard 744: long ipmx=0; /* Number of contributions */
1.126 brouard 745: double sw; /* Sum of weights */
746: char filerespow[FILENAMELENGTH];
747: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
748: FILE *ficresilk;
749: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
750: FILE *ficresprobmorprev;
751: FILE *fichtm, *fichtmcov; /* Html File */
752: FILE *ficreseij;
753: char filerese[FILENAMELENGTH];
754: FILE *ficresstdeij;
755: char fileresstde[FILENAMELENGTH];
756: FILE *ficrescveij;
757: char filerescve[FILENAMELENGTH];
758: FILE *ficresvij;
759: char fileresv[FILENAMELENGTH];
760: FILE *ficresvpl;
761: char fileresvpl[FILENAMELENGTH];
762: char title[MAXLINE];
763: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
764: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
765: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
766: char command[FILENAMELENGTH];
767: int outcmd=0;
768:
769: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
770:
771: char filelog[FILENAMELENGTH]; /* Log file */
772: char filerest[FILENAMELENGTH];
773: char fileregp[FILENAMELENGTH];
774: char popfile[FILENAMELENGTH];
775:
776: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
777:
1.157 brouard 778: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
779: /* struct timezone tzp; */
780: /* extern int gettimeofday(); */
781: struct tm tml, *gmtime(), *localtime();
782:
783: extern time_t time();
784:
785: struct tm start_time, end_time, curr_time, last_time, forecast_time;
786: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
787: struct tm tm;
788:
1.126 brouard 789: char strcurr[80], strfor[80];
790:
791: char *endptr;
792: long lval;
793: double dval;
794:
795: #define NR_END 1
796: #define FREE_ARG char*
797: #define FTOL 1.0e-10
798:
799: #define NRANSI
800: #define ITMAX 200
801:
802: #define TOL 2.0e-4
803:
804: #define CGOLD 0.3819660
805: #define ZEPS 1.0e-10
806: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
807:
808: #define GOLD 1.618034
809: #define GLIMIT 100.0
810: #define TINY 1.0e-20
811:
812: static double maxarg1,maxarg2;
813: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
814: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
815:
816: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
817: #define rint(a) floor(a+0.5)
1.166 brouard 818: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 819: #define mytinydouble 1.0e-16
1.166 brouard 820: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
821: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
822: /* static double dsqrarg; */
823: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 824: static double sqrarg;
825: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
826: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
827: int agegomp= AGEGOMP;
828:
829: int imx;
830: int stepm=1;
831: /* Stepm, step in month: minimum step interpolation*/
832:
833: int estepm;
834: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
835:
836: int m,nb;
837: long *num;
1.192 brouard 838: int firstpass=0, lastpass=4,*cod, *Tage,*cens;
839: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
840: covariate for which somebody answered excluding
841: undefined. Usually 2: 0 and 1. */
842: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
843: covariate for which somebody answered including
844: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 845: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
846: double **pmmij, ***probs;
847: double *ageexmed,*agecens;
848: double dateintmean=0;
849:
850: double *weight;
851: int **s; /* Status */
1.141 brouard 852: double *agedc;
1.145 brouard 853: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 854: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 855: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 856: double idx;
857: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 858: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 859: int **codtab; /**< codtab=imatrix(1,100,1,10); */
860: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 861: double *lsurv, *lpop, *tpop;
862:
1.143 brouard 863: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
864: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 865:
866: /**************** split *************************/
867: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
868: {
869: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
870: the name of the file (name), its extension only (ext) and its first part of the name (finame)
871: */
872: char *ss; /* pointer */
1.186 brouard 873: int l1=0, l2=0; /* length counters */
1.126 brouard 874:
875: l1 = strlen(path ); /* length of path */
876: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
877: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
878: if ( ss == NULL ) { /* no directory, so determine current directory */
879: strcpy( name, path ); /* we got the fullname name because no directory */
880: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
881: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
882: /* get current working directory */
883: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 884: #ifdef WIN32
885: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
886: #else
887: if (getcwd(dirc, FILENAME_MAX) == NULL) {
888: #endif
1.126 brouard 889: return( GLOCK_ERROR_GETCWD );
890: }
891: /* got dirc from getcwd*/
892: printf(" DIRC = %s \n",dirc);
893: } else { /* strip direcotry from path */
894: ss++; /* after this, the filename */
895: l2 = strlen( ss ); /* length of filename */
896: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
897: strcpy( name, ss ); /* save file name */
898: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 899: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 900: printf(" DIRC2 = %s \n",dirc);
901: }
902: /* We add a separator at the end of dirc if not exists */
903: l1 = strlen( dirc ); /* length of directory */
904: if( dirc[l1-1] != DIRSEPARATOR ){
905: dirc[l1] = DIRSEPARATOR;
906: dirc[l1+1] = 0;
907: printf(" DIRC3 = %s \n",dirc);
908: }
909: ss = strrchr( name, '.' ); /* find last / */
910: if (ss >0){
911: ss++;
912: strcpy(ext,ss); /* save extension */
913: l1= strlen( name);
914: l2= strlen(ss)+1;
915: strncpy( finame, name, l1-l2);
916: finame[l1-l2]= 0;
917: }
918:
919: return( 0 ); /* we're done */
920: }
921:
922:
923: /******************************************/
924:
925: void replace_back_to_slash(char *s, char*t)
926: {
927: int i;
928: int lg=0;
929: i=0;
930: lg=strlen(t);
931: for(i=0; i<= lg; i++) {
932: (s[i] = t[i]);
933: if (t[i]== '\\') s[i]='/';
934: }
935: }
936:
1.132 brouard 937: char *trimbb(char *out, char *in)
1.137 brouard 938: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 939: char *s;
940: s=out;
941: while (*in != '\0'){
1.137 brouard 942: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 943: in++;
944: }
945: *out++ = *in++;
946: }
947: *out='\0';
948: return s;
949: }
950:
1.187 brouard 951: /* char *substrchaine(char *out, char *in, char *chain) */
952: /* { */
953: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
954: /* char *s, *t; */
955: /* t=in;s=out; */
956: /* while ((*in != *chain) && (*in != '\0')){ */
957: /* *out++ = *in++; */
958: /* } */
959:
960: /* /\* *in matches *chain *\/ */
961: /* while ((*in++ == *chain++) && (*in != '\0')){ */
962: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
963: /* } */
964: /* in--; chain--; */
965: /* while ( (*in != '\0')){ */
966: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
967: /* *out++ = *in++; */
968: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
969: /* } */
970: /* *out='\0'; */
971: /* out=s; */
972: /* return out; */
973: /* } */
974: char *substrchaine(char *out, char *in, char *chain)
975: {
976: /* Substract chain 'chain' from 'in', return and output 'out' */
977: /* in="V1+V1*age+age*age+V2", chain="age*age" */
978:
979: char *strloc;
980:
981: strcpy (out, in);
982: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
983: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
984: if(strloc != NULL){
985: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
986: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
987: /* strcpy (strloc, strloc +strlen(chain));*/
988: }
989: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
990: return out;
991: }
992:
993:
1.145 brouard 994: char *cutl(char *blocc, char *alocc, char *in, char occ)
995: {
1.187 brouard 996: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 997: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 998: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 999: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1000: */
1.160 brouard 1001: char *s, *t;
1.145 brouard 1002: t=in;s=in;
1003: while ((*in != occ) && (*in != '\0')){
1004: *alocc++ = *in++;
1005: }
1006: if( *in == occ){
1007: *(alocc)='\0';
1008: s=++in;
1009: }
1010:
1011: if (s == t) {/* occ not found */
1012: *(alocc-(in-s))='\0';
1013: in=s;
1014: }
1015: while ( *in != '\0'){
1016: *blocc++ = *in++;
1017: }
1018:
1019: *blocc='\0';
1020: return t;
1021: }
1.137 brouard 1022: char *cutv(char *blocc, char *alocc, char *in, char occ)
1023: {
1.187 brouard 1024: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1025: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1026: gives blocc="abcdef2ghi" and alocc="j".
1027: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1028: */
1029: char *s, *t;
1030: t=in;s=in;
1031: while (*in != '\0'){
1032: while( *in == occ){
1033: *blocc++ = *in++;
1034: s=in;
1035: }
1036: *blocc++ = *in++;
1037: }
1038: if (s == t) /* occ not found */
1039: *(blocc-(in-s))='\0';
1040: else
1041: *(blocc-(in-s)-1)='\0';
1042: in=s;
1043: while ( *in != '\0'){
1044: *alocc++ = *in++;
1045: }
1046:
1047: *alocc='\0';
1048: return s;
1049: }
1050:
1.126 brouard 1051: int nbocc(char *s, char occ)
1052: {
1053: int i,j=0;
1054: int lg=20;
1055: i=0;
1056: lg=strlen(s);
1057: for(i=0; i<= lg; i++) {
1058: if (s[i] == occ ) j++;
1059: }
1060: return j;
1061: }
1062:
1.137 brouard 1063: /* void cutv(char *u,char *v, char*t, char occ) */
1064: /* { */
1065: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1066: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1067: /* gives u="abcdef2ghi" and v="j" *\/ */
1068: /* int i,lg,j,p=0; */
1069: /* i=0; */
1070: /* lg=strlen(t); */
1071: /* for(j=0; j<=lg-1; j++) { */
1072: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1073: /* } */
1.126 brouard 1074:
1.137 brouard 1075: /* for(j=0; j<p; j++) { */
1076: /* (u[j] = t[j]); */
1077: /* } */
1078: /* u[p]='\0'; */
1.126 brouard 1079:
1.137 brouard 1080: /* for(j=0; j<= lg; j++) { */
1081: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1082: /* } */
1083: /* } */
1.126 brouard 1084:
1.160 brouard 1085: #ifdef _WIN32
1086: char * strsep(char **pp, const char *delim)
1087: {
1088: char *p, *q;
1089:
1090: if ((p = *pp) == NULL)
1091: return 0;
1092: if ((q = strpbrk (p, delim)) != NULL)
1093: {
1094: *pp = q + 1;
1095: *q = '\0';
1096: }
1097: else
1098: *pp = 0;
1099: return p;
1100: }
1101: #endif
1102:
1.126 brouard 1103: /********************** nrerror ********************/
1104:
1105: void nrerror(char error_text[])
1106: {
1107: fprintf(stderr,"ERREUR ...\n");
1108: fprintf(stderr,"%s\n",error_text);
1109: exit(EXIT_FAILURE);
1110: }
1111: /*********************** vector *******************/
1112: double *vector(int nl, int nh)
1113: {
1114: double *v;
1115: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1116: if (!v) nrerror("allocation failure in vector");
1117: return v-nl+NR_END;
1118: }
1119:
1120: /************************ free vector ******************/
1121: void free_vector(double*v, int nl, int nh)
1122: {
1123: free((FREE_ARG)(v+nl-NR_END));
1124: }
1125:
1126: /************************ivector *******************************/
1127: int *ivector(long nl,long nh)
1128: {
1129: int *v;
1130: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1131: if (!v) nrerror("allocation failure in ivector");
1132: return v-nl+NR_END;
1133: }
1134:
1135: /******************free ivector **************************/
1136: void free_ivector(int *v, long nl, long nh)
1137: {
1138: free((FREE_ARG)(v+nl-NR_END));
1139: }
1140:
1141: /************************lvector *******************************/
1142: long *lvector(long nl,long nh)
1143: {
1144: long *v;
1145: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1146: if (!v) nrerror("allocation failure in ivector");
1147: return v-nl+NR_END;
1148: }
1149:
1150: /******************free lvector **************************/
1151: void free_lvector(long *v, long nl, long nh)
1152: {
1153: free((FREE_ARG)(v+nl-NR_END));
1154: }
1155:
1156: /******************* imatrix *******************************/
1157: int **imatrix(long nrl, long nrh, long ncl, long nch)
1158: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1159: {
1160: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1161: int **m;
1162:
1163: /* allocate pointers to rows */
1164: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1165: if (!m) nrerror("allocation failure 1 in matrix()");
1166: m += NR_END;
1167: m -= nrl;
1168:
1169:
1170: /* allocate rows and set pointers to them */
1171: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1172: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1173: m[nrl] += NR_END;
1174: m[nrl] -= ncl;
1175:
1176: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1177:
1178: /* return pointer to array of pointers to rows */
1179: return m;
1180: }
1181:
1182: /****************** free_imatrix *************************/
1183: void free_imatrix(m,nrl,nrh,ncl,nch)
1184: int **m;
1185: long nch,ncl,nrh,nrl;
1186: /* free an int matrix allocated by imatrix() */
1187: {
1188: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1189: free((FREE_ARG) (m+nrl-NR_END));
1190: }
1191:
1192: /******************* matrix *******************************/
1193: double **matrix(long nrl, long nrh, long ncl, long nch)
1194: {
1195: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1196: double **m;
1197:
1198: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1199: if (!m) nrerror("allocation failure 1 in matrix()");
1200: m += NR_END;
1201: m -= nrl;
1202:
1203: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1204: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1205: m[nrl] += NR_END;
1206: m[nrl] -= ncl;
1207:
1208: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1209: return m;
1.145 brouard 1210: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1211: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1212: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1213: */
1214: }
1215:
1216: /*************************free matrix ************************/
1217: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1218: {
1219: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1220: free((FREE_ARG)(m+nrl-NR_END));
1221: }
1222:
1223: /******************* ma3x *******************************/
1224: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1225: {
1226: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1227: double ***m;
1228:
1229: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1230: if (!m) nrerror("allocation failure 1 in matrix()");
1231: m += NR_END;
1232: m -= nrl;
1233:
1234: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1235: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1236: m[nrl] += NR_END;
1237: m[nrl] -= ncl;
1238:
1239: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1240:
1241: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1242: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1243: m[nrl][ncl] += NR_END;
1244: m[nrl][ncl] -= nll;
1245: for (j=ncl+1; j<=nch; j++)
1246: m[nrl][j]=m[nrl][j-1]+nlay;
1247:
1248: for (i=nrl+1; i<=nrh; i++) {
1249: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1250: for (j=ncl+1; j<=nch; j++)
1251: m[i][j]=m[i][j-1]+nlay;
1252: }
1253: return m;
1254: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1255: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1256: */
1257: }
1258:
1259: /*************************free ma3x ************************/
1260: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1261: {
1262: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1263: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1264: free((FREE_ARG)(m+nrl-NR_END));
1265: }
1266:
1267: /*************** function subdirf ***********/
1268: char *subdirf(char fileres[])
1269: {
1270: /* Caution optionfilefiname is hidden */
1271: strcpy(tmpout,optionfilefiname);
1272: strcat(tmpout,"/"); /* Add to the right */
1273: strcat(tmpout,fileres);
1274: return tmpout;
1275: }
1276:
1277: /*************** function subdirf2 ***********/
1278: char *subdirf2(char fileres[], char *preop)
1279: {
1280:
1281: /* Caution optionfilefiname is hidden */
1282: strcpy(tmpout,optionfilefiname);
1283: strcat(tmpout,"/");
1284: strcat(tmpout,preop);
1285: strcat(tmpout,fileres);
1286: return tmpout;
1287: }
1288:
1289: /*************** function subdirf3 ***********/
1290: char *subdirf3(char fileres[], char *preop, char *preop2)
1291: {
1292:
1293: /* Caution optionfilefiname is hidden */
1294: strcpy(tmpout,optionfilefiname);
1295: strcat(tmpout,"/");
1296: strcat(tmpout,preop);
1297: strcat(tmpout,preop2);
1298: strcat(tmpout,fileres);
1299: return tmpout;
1300: }
1301:
1.162 brouard 1302: char *asc_diff_time(long time_sec, char ascdiff[])
1303: {
1304: long sec_left, days, hours, minutes;
1305: days = (time_sec) / (60*60*24);
1306: sec_left = (time_sec) % (60*60*24);
1307: hours = (sec_left) / (60*60) ;
1308: sec_left = (sec_left) %(60*60);
1309: minutes = (sec_left) /60;
1310: sec_left = (sec_left) % (60);
1311: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1312: return ascdiff;
1313: }
1314:
1.126 brouard 1315: /***************** f1dim *************************/
1316: extern int ncom;
1317: extern double *pcom,*xicom;
1318: extern double (*nrfunc)(double []);
1319:
1320: double f1dim(double x)
1321: {
1322: int j;
1323: double f;
1324: double *xt;
1325:
1326: xt=vector(1,ncom);
1327: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1328: f=(*nrfunc)(xt);
1329: free_vector(xt,1,ncom);
1330: return f;
1331: }
1332:
1333: /*****************brent *************************/
1334: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1335: {
1336: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1337: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1338: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1339: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1340: * returned function value.
1341: */
1.126 brouard 1342: int iter;
1343: double a,b,d,etemp;
1.159 brouard 1344: double fu=0,fv,fw,fx;
1.164 brouard 1345: double ftemp=0.;
1.126 brouard 1346: double p,q,r,tol1,tol2,u,v,w,x,xm;
1347: double e=0.0;
1348:
1349: a=(ax < cx ? ax : cx);
1350: b=(ax > cx ? ax : cx);
1351: x=w=v=bx;
1352: fw=fv=fx=(*f)(x);
1353: for (iter=1;iter<=ITMAX;iter++) {
1354: xm=0.5*(a+b);
1355: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1356: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1357: printf(".");fflush(stdout);
1358: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1359: #ifdef DEBUGBRENT
1.126 brouard 1360: 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);
1361: 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);
1362: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1363: #endif
1364: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1365: *xmin=x;
1366: return fx;
1367: }
1368: ftemp=fu;
1369: if (fabs(e) > tol1) {
1370: r=(x-w)*(fx-fv);
1371: q=(x-v)*(fx-fw);
1372: p=(x-v)*q-(x-w)*r;
1373: q=2.0*(q-r);
1374: if (q > 0.0) p = -p;
1375: q=fabs(q);
1376: etemp=e;
1377: e=d;
1378: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1379: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1380: else {
1381: d=p/q;
1382: u=x+d;
1383: if (u-a < tol2 || b-u < tol2)
1384: d=SIGN(tol1,xm-x);
1385: }
1386: } else {
1387: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1388: }
1389: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1390: fu=(*f)(u);
1391: if (fu <= fx) {
1392: if (u >= x) a=x; else b=x;
1393: SHFT(v,w,x,u)
1.183 brouard 1394: SHFT(fv,fw,fx,fu)
1395: } else {
1396: if (u < x) a=u; else b=u;
1397: if (fu <= fw || w == x) {
1398: v=w;
1399: w=u;
1400: fv=fw;
1401: fw=fu;
1402: } else if (fu <= fv || v == x || v == w) {
1403: v=u;
1404: fv=fu;
1405: }
1406: }
1.126 brouard 1407: }
1408: nrerror("Too many iterations in brent");
1409: *xmin=x;
1410: return fx;
1411: }
1412:
1413: /****************** mnbrak ***********************/
1414:
1415: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1416: double (*func)(double))
1.183 brouard 1417: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1418: the downhill direction (defined by the function as evaluated at the initial points) and returns
1419: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1420: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1421: */
1.126 brouard 1422: double ulim,u,r,q, dum;
1423: double fu;
1.187 brouard 1424:
1425: double scale=10.;
1426: int iterscale=0;
1427:
1428: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1429: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1430:
1431:
1432: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1433: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1434: /* *bx = *ax - (*ax - *bx)/scale; */
1435: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1436: /* } */
1437:
1.126 brouard 1438: if (*fb > *fa) {
1439: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1440: SHFT(dum,*fb,*fa,dum)
1441: }
1.126 brouard 1442: *cx=(*bx)+GOLD*(*bx-*ax);
1443: *fc=(*func)(*cx);
1.183 brouard 1444: #ifdef DEBUG
1445: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1446: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1447: #endif
1448: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1449: r=(*bx-*ax)*(*fb-*fc);
1450: q=(*bx-*cx)*(*fb-*fa);
1451: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1452: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1453: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1454: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1455: fu=(*func)(u);
1.163 brouard 1456: #ifdef DEBUG
1457: /* f(x)=A(x-u)**2+f(u) */
1458: double A, fparabu;
1459: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1460: fparabu= *fa - A*(*ax-u)*(*ax-u);
1461: 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);
1462: 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 1463: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1464: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1465: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1466: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1467: #endif
1.184 brouard 1468: #ifdef MNBRAKORIGINAL
1.183 brouard 1469: #else
1.191 brouard 1470: /* if (fu > *fc) { */
1471: /* #ifdef DEBUG */
1472: /* printf("mnbrak4 fu > fc \n"); */
1473: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1474: /* #endif */
1475: /* /\* 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 *\\/ *\/ */
1476: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1477: /* dum=u; /\* Shifting c and u *\/ */
1478: /* u = *cx; */
1479: /* *cx = dum; */
1480: /* dum = fu; */
1481: /* fu = *fc; */
1482: /* *fc =dum; */
1483: /* } else { /\* end *\/ */
1484: /* #ifdef DEBUG */
1485: /* printf("mnbrak3 fu < fc \n"); */
1486: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1487: /* #endif */
1488: /* dum=u; /\* Shifting c and u *\/ */
1489: /* u = *cx; */
1490: /* *cx = dum; */
1491: /* dum = fu; */
1492: /* fu = *fc; */
1493: /* *fc =dum; */
1494: /* } */
1.183 brouard 1495: #ifdef DEBUG
1.191 brouard 1496: printf("mnbrak34 fu < or >= fc \n");
1497: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1498: #endif
1.191 brouard 1499: dum=u; /* Shifting c and u */
1500: u = *cx;
1501: *cx = dum;
1502: dum = fu;
1503: fu = *fc;
1504: *fc =dum;
1.183 brouard 1505: #endif
1.162 brouard 1506: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1507: #ifdef DEBUG
1508: printf("mnbrak2 u after c but before ulim\n");
1509: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1510: #endif
1.126 brouard 1511: fu=(*func)(u);
1512: if (fu < *fc) {
1.183 brouard 1513: #ifdef DEBUG
1514: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1515: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1516: #endif
1.126 brouard 1517: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1518: SHFT(*fb,*fc,fu,(*func)(u))
1519: }
1.162 brouard 1520: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1521: #ifdef DEBUG
1522: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1523: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1524: #endif
1.126 brouard 1525: u=ulim;
1526: fu=(*func)(u);
1.183 brouard 1527: } else { /* u could be left to b (if r > q parabola has a maximum) */
1528: #ifdef DEBUG
1529: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1530: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1531: #endif
1.126 brouard 1532: u=(*cx)+GOLD*(*cx-*bx);
1533: fu=(*func)(u);
1.183 brouard 1534: } /* end tests */
1.126 brouard 1535: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1536: SHFT(*fa,*fb,*fc,fu)
1537: #ifdef DEBUG
1538: 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);
1539: 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);
1540: #endif
1541: } /* 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 1542: }
1543:
1544: /*************** linmin ************************/
1.162 brouard 1545: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1546: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1547: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1548: the value of func at the returned location p . This is actually all accomplished by calling the
1549: routines mnbrak and brent .*/
1.126 brouard 1550: int ncom;
1551: double *pcom,*xicom;
1552: double (*nrfunc)(double []);
1553:
1554: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1555: {
1556: double brent(double ax, double bx, double cx,
1557: double (*f)(double), double tol, double *xmin);
1558: double f1dim(double x);
1559: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1560: double *fc, double (*func)(double));
1561: int j;
1562: double xx,xmin,bx,ax;
1563: double fx,fb,fa;
1.187 brouard 1564:
1565: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126 brouard 1566:
1567: ncom=n;
1568: pcom=vector(1,n);
1569: xicom=vector(1,n);
1570: nrfunc=func;
1571: for (j=1;j<=n;j++) {
1572: pcom[j]=p[j];
1573: xicom[j]=xi[j];
1574: }
1.187 brouard 1575:
1.192 brouard 1576: /* axs=0.0; */
1577: /* xxss=1; /\* 1 and using scale *\/ */
1.187 brouard 1578: xxs=1;
1.192 brouard 1579: /* do{ */
1.187 brouard 1580: ax=0.;
1581: xx= xxs;
1582: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1583: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1584: /* 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)) */
1585: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1586: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1587: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1588: /* 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 1589: /* if (fx != fx){ */
1590: /* xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
1591: /* 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); */
1592: /* } */
1593: /* }while(fx != fx); */
1.187 brouard 1594:
1.191 brouard 1595: #ifdef DEBUGLINMIN
1596: 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);
1597: #endif
1.187 brouard 1598: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1599: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1600: /* fmin = f(p[j] + xmin * xi[j]) */
1601: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1602: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1603: #ifdef DEBUG
1604: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1605: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1606: #endif
1.191 brouard 1607: #ifdef DEBUGLINMIN
1608: printf("linmin end ");
1609: #endif
1.126 brouard 1610: for (j=1;j<=n;j++) {
1.188 brouard 1611: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187 brouard 1612: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189 brouard 1613: /* if(xxs <1.0) */
1614: /* 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 1615: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1616: }
1.189 brouard 1617: /* printf("\n"); */
1.191 brouard 1618: #ifdef DEBUGLINMIN
1619: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1620: for (j=1;j<=n;j++) {
1621: printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
1622: if(j % ncovmodel == 0)
1623: printf("\n");
1624: }
1625: #endif
1.126 brouard 1626: free_vector(xicom,1,n);
1627: free_vector(pcom,1,n);
1628: }
1629:
1630:
1631: /*************** powell ************************/
1.162 brouard 1632: /*
1633: Minimization of a function func of n variables. Input consists of an initial starting point
1634: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1635: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1636: such that failure to decrease by more than this amount on one iteration signals doneness. On
1637: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1638: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1639: */
1.126 brouard 1640: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1641: double (*func)(double []))
1642: {
1643: void linmin(double p[], double xi[], int n, double *fret,
1644: double (*func)(double []));
1645: int i,ibig,j;
1646: double del,t,*pt,*ptt,*xit;
1.181 brouard 1647: double directest;
1.126 brouard 1648: double fp,fptt;
1649: double *xits;
1650: int niterf, itmp;
1651:
1652: pt=vector(1,n);
1653: ptt=vector(1,n);
1654: xit=vector(1,n);
1655: xits=vector(1,n);
1656: *fret=(*func)(p);
1657: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1658: rcurr_time = time(NULL);
1.126 brouard 1659: for (*iter=1;;++(*iter)) {
1.187 brouard 1660: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1661: ibig=0;
1662: del=0.0;
1.157 brouard 1663: rlast_time=rcurr_time;
1664: /* (void) gettimeofday(&curr_time,&tzp); */
1665: rcurr_time = time(NULL);
1666: curr_time = *localtime(&rcurr_time);
1667: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1668: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1669: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1670: for (i=1;i<=n;i++) {
1.126 brouard 1671: printf(" %d %.12f",i, p[i]);
1672: fprintf(ficlog," %d %.12lf",i, p[i]);
1673: fprintf(ficrespow," %.12lf", p[i]);
1674: }
1675: printf("\n");
1676: fprintf(ficlog,"\n");
1677: fprintf(ficrespow,"\n");fflush(ficrespow);
1678: if(*iter <=3){
1.157 brouard 1679: tml = *localtime(&rcurr_time);
1680: strcpy(strcurr,asctime(&tml));
1681: rforecast_time=rcurr_time;
1.126 brouard 1682: itmp = strlen(strcurr);
1683: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1684: strcurr[itmp-1]='\0';
1.162 brouard 1685: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1686: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1687: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1688: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1689: forecast_time = *localtime(&rforecast_time);
1690: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1691: itmp = strlen(strfor);
1692: if(strfor[itmp-1]=='\n')
1693: strfor[itmp-1]='\0';
1.157 brouard 1694: 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);
1695: 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 1696: }
1697: }
1.187 brouard 1698: for (i=1;i<=n;i++) { /* For each direction i */
1699: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1700: fptt=(*fret);
1701: #ifdef DEBUG
1.164 brouard 1702: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1703: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1704: #endif
1.187 brouard 1705: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1706: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1707: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1708: /* Outputs are fret(new point p) p is updated and xit rescaled */
1709: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1710: /* because that direction will be replaced unless the gain del is small */
1711: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1712: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1713: /* with the new direction. */
1.126 brouard 1714: del=fabs(fptt-(*fret));
1715: ibig=i;
1716: }
1717: #ifdef DEBUG
1718: printf("%d %.12e",i,(*fret));
1719: fprintf(ficlog,"%d %.12e",i,(*fret));
1720: for (j=1;j<=n;j++) {
1721: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1722: printf(" x(%d)=%.12e",j,xit[j]);
1723: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1724: }
1725: for(j=1;j<=n;j++) {
1.162 brouard 1726: printf(" p(%d)=%.12e",j,p[j]);
1727: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1728: }
1729: printf("\n");
1730: fprintf(ficlog,"\n");
1731: #endif
1.187 brouard 1732: } /* end loop on each direction i */
1733: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1734: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1735: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1736: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1737: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1738: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1739: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1740: /* decreased of more than 3.84 */
1741: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1742: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1743: /* By adding 10 parameters more the gain should be 18.31 */
1744:
1745: /* Starting the program with initial values given by a former maximization will simply change */
1746: /* the scales of the directions and the directions, because the are reset to canonical directions */
1747: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1748: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1749: #ifdef DEBUG
1750: int k[2],l;
1751: k[0]=1;
1752: k[1]=-1;
1753: printf("Max: %.12e",(*func)(p));
1754: fprintf(ficlog,"Max: %.12e",(*func)(p));
1755: for (j=1;j<=n;j++) {
1756: printf(" %.12e",p[j]);
1757: fprintf(ficlog," %.12e",p[j]);
1758: }
1759: printf("\n");
1760: fprintf(ficlog,"\n");
1761: for(l=0;l<=1;l++) {
1762: for (j=1;j<=n;j++) {
1763: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1764: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1765: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1766: }
1767: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1768: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1769: }
1770: #endif
1771:
1772:
1773: free_vector(xit,1,n);
1774: free_vector(xits,1,n);
1775: free_vector(ptt,1,n);
1776: free_vector(pt,1,n);
1777: return;
1.192 brouard 1778: } /* enough precision */
1.126 brouard 1779: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1780: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1781: ptt[j]=2.0*p[j]-pt[j];
1782: xit[j]=p[j]-pt[j];
1783: pt[j]=p[j];
1784: }
1.181 brouard 1785: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1786: #ifdef POWELLF1F3
1787: #else
1.161 brouard 1788: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1789: #endif
1.162 brouard 1790: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1791: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1792: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1793: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1794: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1795: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1796: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1797: #ifdef NRCORIGINAL
1798: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1799: #else
1800: 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 1801: t= t- del*SQR(fp-fptt);
1.183 brouard 1802: #endif
1.182 brouard 1803: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1804: #ifdef DEBUG
1.181 brouard 1805: 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);
1806: 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 1807: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1808: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1809: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1810: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1811: 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);
1812: 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);
1813: #endif
1.183 brouard 1814: #ifdef POWELLORIGINAL
1815: if (t < 0.0) { /* Then we use it for new direction */
1816: #else
1.182 brouard 1817: if (directest*t < 0.0) { /* Contradiction between both tests */
1.192 brouard 1818: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1819: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1820: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1821: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1822: }
1.181 brouard 1823: if (directest < 0.0) { /* Then we use it for new direction */
1824: #endif
1.191 brouard 1825: #ifdef DEBUGLINMIN
1826: printf("Before linmin in direction P%d-P0\n",n);
1827: for (j=1;j<=n;j++) {
1828: printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1829: if(j % ncovmodel == 0)
1830: printf("\n");
1831: }
1832: #endif
1.187 brouard 1833: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1834: #ifdef DEBUGLINMIN
1835: for (j=1;j<=n;j++) {
1836: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1837: if(j % ncovmodel == 0)
1838: printf("\n");
1839: }
1840: #endif
1.126 brouard 1841: for (j=1;j<=n;j++) {
1.181 brouard 1842: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1843: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1844: }
1.181 brouard 1845: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1846: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1847:
1.126 brouard 1848: #ifdef DEBUG
1.164 brouard 1849: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1850: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1851: for(j=1;j<=n;j++){
1852: printf(" %.12e",xit[j]);
1853: fprintf(ficlog," %.12e",xit[j]);
1854: }
1855: printf("\n");
1856: fprintf(ficlog,"\n");
1857: #endif
1.192 brouard 1858: } /* end of t or directest negative */
1859: #ifdef POWELLF1F3
1860: #else
1.162 brouard 1861: } /* end if (fptt < fp) */
1.192 brouard 1862: #endif
1863: } /* loop iteration */
1.126 brouard 1864: }
1865:
1866: /**** Prevalence limit (stable or period prevalence) ****************/
1867:
1868: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1869: {
1870: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1871: matrix by transitions matrix until convergence is reached */
1.169 brouard 1872:
1.126 brouard 1873: int i, ii,j,k;
1874: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1875: /* double **matprod2(); */ /* test */
1.131 brouard 1876: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1877: double **newm;
1878: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1879:
1.126 brouard 1880: for (ii=1;ii<=nlstate+ndeath;ii++)
1881: for (j=1;j<=nlstate+ndeath;j++){
1882: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1883: }
1.169 brouard 1884:
1885: cov[1]=1.;
1886:
1887: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1888: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1889: newm=savm;
1890: /* Covariates have to be included here again */
1.138 brouard 1891: cov[2]=agefin;
1.187 brouard 1892: if(nagesqr==1)
1893: cov[3]= agefin*agefin;;
1.138 brouard 1894: for (k=1; k<=cptcovn;k++) {
1.187 brouard 1895: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1896: /*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 1897: }
1.186 brouard 1898: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 1899: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186 brouard 1900: for (k=1; k<=cptcovprod;k++) /* Useless */
1.187 brouard 1901: 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 1902:
1903: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1904: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1905: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1906: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1907: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1908: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1909:
1.126 brouard 1910: savm=oldm;
1911: oldm=newm;
1912: maxmax=0.;
1913: for(j=1;j<=nlstate;j++){
1914: min=1.;
1915: max=0.;
1916: for(i=1; i<=nlstate; i++) {
1917: sumnew=0;
1918: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1919: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1920: /*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 1921: max=FMAX(max,prlim[i][j]);
1922: min=FMIN(min,prlim[i][j]);
1923: }
1924: maxmin=max-min;
1925: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1926: } /* j loop */
1.126 brouard 1927: if(maxmax < ftolpl){
1928: return prlim;
1929: }
1.169 brouard 1930: } /* age loop */
1931: return prlim; /* should not reach here */
1.126 brouard 1932: }
1933:
1934: /*************** transition probabilities ***************/
1935:
1936: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1937: {
1.138 brouard 1938: /* According to parameters values stored in x and the covariate's values stored in cov,
1939: computes the probability to be observed in state j being in state i by appying the
1940: model to the ncovmodel covariates (including constant and age).
1941: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1942: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1943: ncth covariate in the global vector x is given by the formula:
1944: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1945: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1946: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1947: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1948: Outputs ps[i][j] the probability to be observed in j being in j according to
1949: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1950: */
1951: double s1, lnpijopii;
1.126 brouard 1952: /*double t34;*/
1.164 brouard 1953: int i,j, nc, ii, jj;
1.126 brouard 1954:
1955: for(i=1; i<= nlstate; i++){
1956: for(j=1; j<i;j++){
1.138 brouard 1957: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1958: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1959: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1960: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1961: }
1.138 brouard 1962: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1963: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1964: }
1965: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1966: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1967: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1968: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1969: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1970: }
1.138 brouard 1971: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1972: }
1973: }
1974:
1975: for(i=1; i<= nlstate; i++){
1976: s1=0;
1.131 brouard 1977: for(j=1; j<i; j++){
1.138 brouard 1978: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1979: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1980: }
1981: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1982: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1983: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1984: }
1.138 brouard 1985: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1986: ps[i][i]=1./(s1+1.);
1.138 brouard 1987: /* Computing other pijs */
1.126 brouard 1988: for(j=1; j<i; j++)
1989: ps[i][j]= exp(ps[i][j])*ps[i][i];
1990: for(j=i+1; j<=nlstate+ndeath; j++)
1991: ps[i][j]= exp(ps[i][j])*ps[i][i];
1992: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1993: } /* end i */
1994:
1995: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1996: for(jj=1; jj<= nlstate+ndeath; jj++){
1997: ps[ii][jj]=0;
1998: ps[ii][ii]=1;
1999: }
2000: }
2001:
1.145 brouard 2002:
2003: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2004: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2005: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2006: /* } */
2007: /* printf("\n "); */
2008: /* } */
2009: /* printf("\n ");printf("%lf ",cov[2]);*/
2010: /*
1.126 brouard 2011: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2012: goto end;*/
2013: return ps;
2014: }
2015:
2016: /**************** Product of 2 matrices ******************/
2017:
1.145 brouard 2018: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2019: {
2020: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2021: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2022: /* in, b, out are matrice of pointers which should have been initialized
2023: before: only the contents of out is modified. The function returns
2024: a pointer to pointers identical to out */
1.145 brouard 2025: int i, j, k;
1.126 brouard 2026: for(i=nrl; i<= nrh; i++)
1.145 brouard 2027: for(k=ncolol; k<=ncoloh; k++){
2028: out[i][k]=0.;
2029: for(j=ncl; j<=nch; j++)
2030: out[i][k] +=in[i][j]*b[j][k];
2031: }
1.126 brouard 2032: return out;
2033: }
2034:
2035:
2036: /************* Higher Matrix Product ***************/
2037:
2038: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2039: {
2040: /* Computes the transition matrix starting at age 'age' over
2041: 'nhstepm*hstepm*stepm' months (i.e. until
2042: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2043: nhstepm*hstepm matrices.
2044: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2045: (typically every 2 years instead of every month which is too big
2046: for the memory).
2047: Model is determined by parameters x and covariates have to be
2048: included manually here.
2049:
2050: */
2051:
2052: int i, j, d, h, k;
1.131 brouard 2053: double **out, cov[NCOVMAX+1];
1.126 brouard 2054: double **newm;
1.187 brouard 2055: double agexact;
1.126 brouard 2056:
2057: /* Hstepm could be zero and should return the unit matrix */
2058: for (i=1;i<=nlstate+ndeath;i++)
2059: for (j=1;j<=nlstate+ndeath;j++){
2060: oldm[i][j]=(i==j ? 1.0 : 0.0);
2061: po[i][j][0]=(i==j ? 1.0 : 0.0);
2062: }
2063: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2064: for(h=1; h <=nhstepm; h++){
2065: for(d=1; d <=hstepm; d++){
2066: newm=savm;
2067: /* Covariates have to be included here again */
2068: cov[1]=1.;
1.187 brouard 2069: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2070: cov[2]=agexact;
2071: if(nagesqr==1)
2072: cov[3]= agexact*agexact;
1.131 brouard 2073: for (k=1; k<=cptcovn;k++)
1.187 brouard 2074: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186 brouard 2075: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2076: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 2077: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145 brouard 2078: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187 brouard 2079: 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 2080:
2081:
2082: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2083: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2084: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2085: pmij(pmmij,cov,ncovmodel,x,nlstate));
2086: savm=oldm;
2087: oldm=newm;
2088: }
2089: for(i=1; i<=nlstate+ndeath; i++)
2090: for(j=1;j<=nlstate+ndeath;j++) {
2091: po[i][j][h]=newm[i][j];
1.128 brouard 2092: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2093: }
1.128 brouard 2094: /*printf("h=%d ",h);*/
1.126 brouard 2095: } /* end h */
1.128 brouard 2096: /* printf("\n H=%d \n",h); */
1.126 brouard 2097: return po;
2098: }
2099:
1.162 brouard 2100: #ifdef NLOPT
2101: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2102: double fret;
2103: double *xt;
2104: int j;
2105: myfunc_data *d2 = (myfunc_data *) pd;
2106: /* xt = (p1-1); */
2107: xt=vector(1,n);
2108: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2109:
2110: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2111: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2112: printf("Function = %.12lf ",fret);
2113: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2114: printf("\n");
2115: free_vector(xt,1,n);
2116: return fret;
2117: }
2118: #endif
1.126 brouard 2119:
2120: /*************** log-likelihood *************/
2121: double func( double *x)
2122: {
2123: int i, ii, j, k, mi, d, kk;
1.131 brouard 2124: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2125: double **out;
2126: double sw; /* Sum of weights */
2127: double lli; /* Individual log likelihood */
2128: int s1, s2;
2129: double bbh, survp;
2130: long ipmx;
1.187 brouard 2131: double agexact;
1.126 brouard 2132: /*extern weight */
2133: /* We are differentiating ll according to initial status */
2134: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2135: /*for(i=1;i<imx;i++)
2136: printf(" %d\n",s[4][i]);
2137: */
1.162 brouard 2138:
2139: ++countcallfunc;
2140:
1.126 brouard 2141: cov[1]=1.;
2142:
2143: for(k=1; k<=nlstate; k++) ll[k]=0.;
2144:
2145: if(mle==1){
2146: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2147: /* Computes the values of the ncovmodel covariates of the model
2148: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2149: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2150: to be observed in j being in i according to the model.
2151: */
1.145 brouard 2152: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2153: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2154: }
1.137 brouard 2155: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2156: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2157: has been calculated etc */
1.126 brouard 2158: for(mi=1; mi<= wav[i]-1; mi++){
2159: for (ii=1;ii<=nlstate+ndeath;ii++)
2160: for (j=1;j<=nlstate+ndeath;j++){
2161: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2162: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2163: }
2164: for(d=0; d<dh[mi][i]; d++){
2165: newm=savm;
1.187 brouard 2166: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2167: cov[2]=agexact;
2168: if(nagesqr==1)
2169: cov[3]= agexact*agexact;
1.126 brouard 2170: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2171: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2172: }
2173: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2174: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2175: savm=oldm;
2176: oldm=newm;
2177: } /* end mult */
2178:
2179: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2180: /* But now since version 0.9 we anticipate for bias at large stepm.
2181: * If stepm is larger than one month (smallest stepm) and if the exact delay
2182: * (in months) between two waves is not a multiple of stepm, we rounded to
2183: * the nearest (and in case of equal distance, to the lowest) interval but now
2184: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2185: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2186: * probability in order to take into account the bias as a fraction of the way
2187: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2188: * -stepm/2 to stepm/2 .
2189: * For stepm=1 the results are the same as for previous versions of Imach.
2190: * For stepm > 1 the results are less biased than in previous versions.
2191: */
2192: s1=s[mw[mi][i]][i];
2193: s2=s[mw[mi+1][i]][i];
2194: bbh=(double)bh[mi][i]/(double)stepm;
2195: /* bias bh is positive if real duration
2196: * is higher than the multiple of stepm and negative otherwise.
2197: */
2198: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2199: if( s2 > nlstate){
2200: /* i.e. if s2 is a death state and if the date of death is known
2201: then the contribution to the likelihood is the probability to
2202: die between last step unit time and current step unit time,
2203: which is also equal to probability to die before dh
2204: minus probability to die before dh-stepm .
2205: In version up to 0.92 likelihood was computed
2206: as if date of death was unknown. Death was treated as any other
2207: health state: the date of the interview describes the actual state
2208: and not the date of a change in health state. The former idea was
2209: to consider that at each interview the state was recorded
2210: (healthy, disable or death) and IMaCh was corrected; but when we
2211: introduced the exact date of death then we should have modified
2212: the contribution of an exact death to the likelihood. This new
2213: contribution is smaller and very dependent of the step unit
2214: stepm. It is no more the probability to die between last interview
2215: and month of death but the probability to survive from last
2216: interview up to one month before death multiplied by the
2217: probability to die within a month. Thanks to Chris
2218: Jackson for correcting this bug. Former versions increased
2219: mortality artificially. The bad side is that we add another loop
2220: which slows down the processing. The difference can be up to 10%
2221: lower mortality.
2222: */
1.183 brouard 2223: /* If, at the beginning of the maximization mostly, the
2224: cumulative probability or probability to be dead is
2225: constant (ie = 1) over time d, the difference is equal to
2226: 0. out[s1][3] = savm[s1][3]: probability, being at state
2227: s1 at precedent wave, to be dead a month before current
2228: wave is equal to probability, being at state s1 at
2229: precedent wave, to be dead at mont of the current
2230: wave. Then the observed probability (that this person died)
2231: is null according to current estimated parameter. In fact,
2232: it should be very low but not zero otherwise the log go to
2233: infinity.
2234: */
2235: /* #ifdef INFINITYORIGINAL */
2236: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2237: /* #else */
2238: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2239: /* lli=log(mytinydouble); */
2240: /* else */
2241: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2242: /* #endif */
2243: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2244:
2245: } else if (s2==-2) {
2246: for (j=1,survp=0. ; j<=nlstate; j++)
2247: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2248: /*survp += out[s1][j]; */
2249: lli= log(survp);
2250: }
2251:
2252: else if (s2==-4) {
2253: for (j=3,survp=0. ; j<=nlstate; j++)
2254: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2255: lli= log(survp);
2256: }
2257:
2258: else if (s2==-5) {
2259: for (j=1,survp=0. ; j<=2; j++)
2260: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2261: lli= log(survp);
2262: }
2263:
2264: else{
2265: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2266: /* 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 */
2267: }
2268: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2269: /*if(lli ==000.0)*/
2270: /*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); */
2271: ipmx +=1;
2272: sw += weight[i];
2273: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2274: /* if (lli < log(mytinydouble)){ */
2275: /* 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); */
2276: /* 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]); */
2277: /* } */
1.126 brouard 2278: } /* end of wave */
2279: } /* end of individual */
2280: } else if(mle==2){
2281: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2282: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2283: for(mi=1; mi<= wav[i]-1; mi++){
2284: for (ii=1;ii<=nlstate+ndeath;ii++)
2285: for (j=1;j<=nlstate+ndeath;j++){
2286: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2287: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2288: }
2289: for(d=0; d<=dh[mi][i]; d++){
2290: newm=savm;
1.187 brouard 2291: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2292: cov[2]=agexact;
2293: if(nagesqr==1)
2294: cov[3]= agexact*agexact;
1.126 brouard 2295: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2296: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2297: }
2298: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2299: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2300: savm=oldm;
2301: oldm=newm;
2302: } /* end mult */
2303:
2304: s1=s[mw[mi][i]][i];
2305: s2=s[mw[mi+1][i]][i];
2306: bbh=(double)bh[mi][i]/(double)stepm;
2307: 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 */
2308: ipmx +=1;
2309: sw += weight[i];
2310: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2311: } /* end of wave */
2312: } /* end of individual */
2313: } else if(mle==3){ /* exponential inter-extrapolation */
2314: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2315: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2316: for(mi=1; mi<= wav[i]-1; mi++){
2317: for (ii=1;ii<=nlstate+ndeath;ii++)
2318: for (j=1;j<=nlstate+ndeath;j++){
2319: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2320: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2321: }
2322: for(d=0; d<dh[mi][i]; d++){
2323: newm=savm;
1.187 brouard 2324: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2325: cov[2]=agexact;
2326: if(nagesqr==1)
2327: cov[3]= agexact*agexact;
1.126 brouard 2328: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2329: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2330: }
2331: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2332: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2333: savm=oldm;
2334: oldm=newm;
2335: } /* end mult */
2336:
2337: s1=s[mw[mi][i]][i];
2338: s2=s[mw[mi+1][i]][i];
2339: bbh=(double)bh[mi][i]/(double)stepm;
2340: 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 */
2341: ipmx +=1;
2342: sw += weight[i];
2343: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2344: } /* end of wave */
2345: } /* end of individual */
2346: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2347: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2348: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2349: for(mi=1; mi<= wav[i]-1; mi++){
2350: for (ii=1;ii<=nlstate+ndeath;ii++)
2351: for (j=1;j<=nlstate+ndeath;j++){
2352: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2353: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2354: }
2355: for(d=0; d<dh[mi][i]; d++){
2356: newm=savm;
1.187 brouard 2357: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2358: cov[2]=agexact;
2359: if(nagesqr==1)
2360: cov[3]= agexact*agexact;
1.126 brouard 2361: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2362: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2363: }
2364:
2365: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2366: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2367: savm=oldm;
2368: oldm=newm;
2369: } /* end mult */
2370:
2371: s1=s[mw[mi][i]][i];
2372: s2=s[mw[mi+1][i]][i];
2373: if( s2 > nlstate){
2374: lli=log(out[s1][s2] - savm[s1][s2]);
2375: }else{
2376: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2377: }
2378: ipmx +=1;
2379: sw += weight[i];
2380: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2381: /* 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]); */
2382: } /* end of wave */
2383: } /* end of individual */
2384: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2385: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2386: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2387: for(mi=1; mi<= wav[i]-1; mi++){
2388: for (ii=1;ii<=nlstate+ndeath;ii++)
2389: for (j=1;j<=nlstate+ndeath;j++){
2390: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2391: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2392: }
2393: for(d=0; d<dh[mi][i]; d++){
2394: newm=savm;
1.187 brouard 2395: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2396: cov[2]=agexact;
2397: if(nagesqr==1)
2398: cov[3]= agexact*agexact;
1.126 brouard 2399: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2400: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2401: }
2402:
2403: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2404: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2405: savm=oldm;
2406: oldm=newm;
2407: } /* end mult */
2408:
2409: s1=s[mw[mi][i]][i];
2410: s2=s[mw[mi+1][i]][i];
2411: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2412: ipmx +=1;
2413: sw += weight[i];
2414: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2415: /*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]);*/
2416: } /* end of wave */
2417: } /* end of individual */
2418: } /* End of if */
2419: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2420: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2421: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2422: return -l;
2423: }
2424:
2425: /*************** log-likelihood *************/
2426: double funcone( double *x)
2427: {
2428: /* Same as likeli but slower because of a lot of printf and if */
2429: int i, ii, j, k, mi, d, kk;
1.131 brouard 2430: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2431: double **out;
2432: double lli; /* Individual log likelihood */
2433: double llt;
2434: int s1, s2;
2435: double bbh, survp;
1.187 brouard 2436: double agexact;
1.126 brouard 2437: /*extern weight */
2438: /* We are differentiating ll according to initial status */
2439: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2440: /*for(i=1;i<imx;i++)
2441: printf(" %d\n",s[4][i]);
2442: */
2443: cov[1]=1.;
2444:
2445: for(k=1; k<=nlstate; k++) ll[k]=0.;
2446:
2447: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2448: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2449: for(mi=1; mi<= wav[i]-1; mi++){
2450: for (ii=1;ii<=nlstate+ndeath;ii++)
2451: for (j=1;j<=nlstate+ndeath;j++){
2452: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2453: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2454: }
2455: for(d=0; d<dh[mi][i]; d++){
2456: newm=savm;
1.187 brouard 2457: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2458: cov[2]=agexact;
2459: if(nagesqr==1)
2460: cov[3]= agexact*agexact;
1.126 brouard 2461: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2462: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2463: }
1.187 brouard 2464:
1.145 brouard 2465: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2466: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2467: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2468: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2469: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2470: savm=oldm;
2471: oldm=newm;
2472: } /* end mult */
2473:
2474: s1=s[mw[mi][i]][i];
2475: s2=s[mw[mi+1][i]][i];
2476: bbh=(double)bh[mi][i]/(double)stepm;
2477: /* bias is positive if real duration
2478: * is higher than the multiple of stepm and negative otherwise.
2479: */
2480: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2481: lli=log(out[s1][s2] - savm[s1][s2]);
2482: } else if (s2==-2) {
2483: for (j=1,survp=0. ; j<=nlstate; j++)
2484: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2485: lli= log(survp);
2486: }else if (mle==1){
2487: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2488: } else if(mle==2){
2489: 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 */
2490: } else if(mle==3){ /* exponential inter-extrapolation */
2491: 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 */
2492: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2493: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2494: } else{ /* mle=0 back to 1 */
2495: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2496: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2497: } /* End of if */
2498: ipmx +=1;
2499: sw += weight[i];
2500: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2501: /*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 2502: if(globpr){
1.141 brouard 2503: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2504: %11.6f %11.6f %11.6f ", \
2505: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2506: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2507: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2508: llt +=ll[k]*gipmx/gsw;
2509: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2510: }
2511: fprintf(ficresilk," %10.6f\n", -llt);
2512: }
2513: } /* end of wave */
2514: } /* end of individual */
2515: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2516: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2517: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2518: if(globpr==0){ /* First time we count the contributions and weights */
2519: gipmx=ipmx;
2520: gsw=sw;
2521: }
2522: return -l;
2523: }
2524:
2525:
2526: /*************** function likelione ***********/
2527: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2528: {
2529: /* This routine should help understanding what is done with
2530: the selection of individuals/waves and
2531: to check the exact contribution to the likelihood.
2532: Plotting could be done.
2533: */
2534: int k;
2535:
2536: if(*globpri !=0){ /* Just counts and sums, no printings */
2537: strcpy(fileresilk,"ilk");
2538: strcat(fileresilk,fileres);
2539: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2540: printf("Problem with resultfile: %s\n", fileresilk);
2541: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2542: }
2543: 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");
2544: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2545: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2546: for(k=1; k<=nlstate; k++)
2547: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2548: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2549: }
2550:
2551: *fretone=(*funcone)(p);
2552: if(*globpri !=0){
2553: fclose(ficresilk);
2554: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2555: fflush(fichtm);
2556: }
2557: return;
2558: }
2559:
2560:
2561: /*********** Maximum Likelihood Estimation ***************/
2562:
2563: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2564: {
1.165 brouard 2565: int i,j, iter=0;
1.126 brouard 2566: double **xi;
2567: double fret;
2568: double fretone; /* Only one call to likelihood */
2569: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2570:
2571: #ifdef NLOPT
2572: int creturn;
2573: nlopt_opt opt;
2574: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2575: double *lb;
2576: double minf; /* the minimum objective value, upon return */
2577: double * p1; /* Shifted parameters from 0 instead of 1 */
2578: myfunc_data dinst, *d = &dinst;
2579: #endif
2580:
2581:
1.126 brouard 2582: xi=matrix(1,npar,1,npar);
2583: for (i=1;i<=npar;i++)
2584: for (j=1;j<=npar;j++)
2585: xi[i][j]=(i==j ? 1.0 : 0.0);
2586: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2587: strcpy(filerespow,"pow");
2588: strcat(filerespow,fileres);
2589: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2590: printf("Problem with resultfile: %s\n", filerespow);
2591: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2592: }
2593: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2594: for (i=1;i<=nlstate;i++)
2595: for(j=1;j<=nlstate+ndeath;j++)
2596: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2597: fprintf(ficrespow,"\n");
1.162 brouard 2598: #ifdef POWELL
1.126 brouard 2599: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2600: #endif
1.126 brouard 2601:
1.162 brouard 2602: #ifdef NLOPT
2603: #ifdef NEWUOA
2604: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2605: #else
2606: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2607: #endif
2608: lb=vector(0,npar-1);
2609: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2610: nlopt_set_lower_bounds(opt, lb);
2611: nlopt_set_initial_step1(opt, 0.1);
2612:
2613: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2614: d->function = func;
2615: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2616: nlopt_set_min_objective(opt, myfunc, d);
2617: nlopt_set_xtol_rel(opt, ftol);
2618: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2619: printf("nlopt failed! %d\n",creturn);
2620: }
2621: else {
2622: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2623: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2624: iter=1; /* not equal */
2625: }
2626: nlopt_destroy(opt);
2627: #endif
1.126 brouard 2628: free_matrix(xi,1,npar,1,npar);
2629: fclose(ficrespow);
1.180 brouard 2630: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2631: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2632: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2633:
2634: }
2635:
2636: /**** Computes Hessian and covariance matrix ***/
2637: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2638: {
2639: double **a,**y,*x,pd;
2640: double **hess;
1.164 brouard 2641: int i, j;
1.126 brouard 2642: int *indx;
2643:
2644: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2645: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2646: void lubksb(double **a, int npar, int *indx, double b[]) ;
2647: void ludcmp(double **a, int npar, int *indx, double *d) ;
2648: double gompertz(double p[]);
2649: hess=matrix(1,npar,1,npar);
2650:
2651: printf("\nCalculation of the hessian matrix. Wait...\n");
2652: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2653: for (i=1;i<=npar;i++){
2654: printf("%d",i);fflush(stdout);
2655: fprintf(ficlog,"%d",i);fflush(ficlog);
2656:
2657: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2658:
2659: /* printf(" %f ",p[i]);
2660: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2661: }
2662:
2663: for (i=1;i<=npar;i++) {
2664: for (j=1;j<=npar;j++) {
2665: if (j>i) {
2666: printf(".%d%d",i,j);fflush(stdout);
2667: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2668: hess[i][j]=hessij(p,delti,i,j,func,npar);
2669:
2670: hess[j][i]=hess[i][j];
2671: /*printf(" %lf ",hess[i][j]);*/
2672: }
2673: }
2674: }
2675: printf("\n");
2676: fprintf(ficlog,"\n");
2677:
2678: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2679: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2680:
2681: a=matrix(1,npar,1,npar);
2682: y=matrix(1,npar,1,npar);
2683: x=vector(1,npar);
2684: indx=ivector(1,npar);
2685: for (i=1;i<=npar;i++)
2686: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2687: ludcmp(a,npar,indx,&pd);
2688:
2689: for (j=1;j<=npar;j++) {
2690: for (i=1;i<=npar;i++) x[i]=0;
2691: x[j]=1;
2692: lubksb(a,npar,indx,x);
2693: for (i=1;i<=npar;i++){
2694: matcov[i][j]=x[i];
2695: }
2696: }
2697:
2698: printf("\n#Hessian matrix#\n");
2699: fprintf(ficlog,"\n#Hessian matrix#\n");
2700: for (i=1;i<=npar;i++) {
2701: for (j=1;j<=npar;j++) {
2702: printf("%.3e ",hess[i][j]);
2703: fprintf(ficlog,"%.3e ",hess[i][j]);
2704: }
2705: printf("\n");
2706: fprintf(ficlog,"\n");
2707: }
2708:
2709: /* Recompute Inverse */
2710: for (i=1;i<=npar;i++)
2711: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2712: ludcmp(a,npar,indx,&pd);
2713:
2714: /* printf("\n#Hessian matrix recomputed#\n");
2715:
2716: for (j=1;j<=npar;j++) {
2717: for (i=1;i<=npar;i++) x[i]=0;
2718: x[j]=1;
2719: lubksb(a,npar,indx,x);
2720: for (i=1;i<=npar;i++){
2721: y[i][j]=x[i];
2722: printf("%.3e ",y[i][j]);
2723: fprintf(ficlog,"%.3e ",y[i][j]);
2724: }
2725: printf("\n");
2726: fprintf(ficlog,"\n");
2727: }
2728: */
2729:
2730: free_matrix(a,1,npar,1,npar);
2731: free_matrix(y,1,npar,1,npar);
2732: free_vector(x,1,npar);
2733: free_ivector(indx,1,npar);
2734: free_matrix(hess,1,npar,1,npar);
2735:
2736:
2737: }
2738:
2739: /*************** hessian matrix ****************/
2740: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2741: {
2742: int i;
2743: int l=1, lmax=20;
2744: double k1,k2;
1.132 brouard 2745: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2746: double res;
2747: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2748: double fx;
2749: int k=0,kmax=10;
2750: double l1;
2751:
2752: fx=func(x);
2753: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2754: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2755: l1=pow(10,l);
2756: delts=delt;
2757: for(k=1 ; k <kmax; k=k+1){
2758: delt = delta*(l1*k);
2759: p2[theta]=x[theta] +delt;
1.145 brouard 2760: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2761: p2[theta]=x[theta]-delt;
2762: k2=func(p2)-fx;
2763: /*res= (k1-2.0*fx+k2)/delt/delt; */
2764: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2765:
1.132 brouard 2766: #ifdef DEBUGHESS
1.126 brouard 2767: 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);
2768: 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);
2769: #endif
2770: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2771: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2772: k=kmax;
2773: }
2774: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2775: k=kmax; l=lmax*10;
1.126 brouard 2776: }
2777: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2778: delts=delt;
2779: }
2780: }
2781: }
2782: delti[theta]=delts;
2783: return res;
2784:
2785: }
2786:
2787: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2788: {
2789: int i;
1.164 brouard 2790: int l=1, lmax=20;
1.126 brouard 2791: double k1,k2,k3,k4,res,fx;
1.132 brouard 2792: double p2[MAXPARM+1];
1.126 brouard 2793: int k;
2794:
2795: fx=func(x);
2796: for (k=1; k<=2; k++) {
2797: for (i=1;i<=npar;i++) p2[i]=x[i];
2798: p2[thetai]=x[thetai]+delti[thetai]/k;
2799: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2800: k1=func(p2)-fx;
2801:
2802: p2[thetai]=x[thetai]+delti[thetai]/k;
2803: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2804: k2=func(p2)-fx;
2805:
2806: p2[thetai]=x[thetai]-delti[thetai]/k;
2807: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2808: k3=func(p2)-fx;
2809:
2810: p2[thetai]=x[thetai]-delti[thetai]/k;
2811: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2812: k4=func(p2)-fx;
2813: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2814: #ifdef DEBUG
2815: 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);
2816: 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);
2817: #endif
2818: }
2819: return res;
2820: }
2821:
2822: /************** Inverse of matrix **************/
2823: void ludcmp(double **a, int n, int *indx, double *d)
2824: {
2825: int i,imax,j,k;
2826: double big,dum,sum,temp;
2827: double *vv;
2828:
2829: vv=vector(1,n);
2830: *d=1.0;
2831: for (i=1;i<=n;i++) {
2832: big=0.0;
2833: for (j=1;j<=n;j++)
2834: if ((temp=fabs(a[i][j])) > big) big=temp;
2835: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2836: vv[i]=1.0/big;
2837: }
2838: for (j=1;j<=n;j++) {
2839: for (i=1;i<j;i++) {
2840: sum=a[i][j];
2841: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2842: a[i][j]=sum;
2843: }
2844: big=0.0;
2845: for (i=j;i<=n;i++) {
2846: sum=a[i][j];
2847: for (k=1;k<j;k++)
2848: sum -= a[i][k]*a[k][j];
2849: a[i][j]=sum;
2850: if ( (dum=vv[i]*fabs(sum)) >= big) {
2851: big=dum;
2852: imax=i;
2853: }
2854: }
2855: if (j != imax) {
2856: for (k=1;k<=n;k++) {
2857: dum=a[imax][k];
2858: a[imax][k]=a[j][k];
2859: a[j][k]=dum;
2860: }
2861: *d = -(*d);
2862: vv[imax]=vv[j];
2863: }
2864: indx[j]=imax;
2865: if (a[j][j] == 0.0) a[j][j]=TINY;
2866: if (j != n) {
2867: dum=1.0/(a[j][j]);
2868: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2869: }
2870: }
2871: free_vector(vv,1,n); /* Doesn't work */
2872: ;
2873: }
2874:
2875: void lubksb(double **a, int n, int *indx, double b[])
2876: {
2877: int i,ii=0,ip,j;
2878: double sum;
2879:
2880: for (i=1;i<=n;i++) {
2881: ip=indx[i];
2882: sum=b[ip];
2883: b[ip]=b[i];
2884: if (ii)
2885: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2886: else if (sum) ii=i;
2887: b[i]=sum;
2888: }
2889: for (i=n;i>=1;i--) {
2890: sum=b[i];
2891: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2892: b[i]=sum/a[i][i];
2893: }
2894: }
2895:
2896: void pstamp(FILE *fichier)
2897: {
2898: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2899: }
2900:
2901: /************ Frequencies ********************/
2902: 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[])
2903: { /* Some frequencies */
2904:
1.164 brouard 2905: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2906: int first;
2907: double ***freq; /* Frequencies */
2908: double *pp, **prop;
2909: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2910: char fileresp[FILENAMELENGTH];
2911:
2912: pp=vector(1,nlstate);
2913: prop=matrix(1,nlstate,iagemin,iagemax+3);
2914: strcpy(fileresp,"p");
2915: strcat(fileresp,fileres);
2916: if((ficresp=fopen(fileresp,"w"))==NULL) {
2917: printf("Problem with prevalence resultfile: %s\n", fileresp);
2918: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2919: exit(0);
2920: }
2921: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2922: j1=0;
2923:
2924: j=cptcoveff;
2925: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2926:
2927: first=1;
2928:
1.169 brouard 2929: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2930: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2931: /* j1++; */
1.145 brouard 2932: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2933: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2934: scanf("%d", i);*/
2935: for (i=-5; i<=nlstate+ndeath; i++)
2936: for (jk=-5; jk<=nlstate+ndeath; jk++)
2937: for(m=iagemin; m <= iagemax+3; m++)
2938: freq[i][jk][m]=0;
1.143 brouard 2939:
2940: for (i=1; i<=nlstate; i++)
2941: for(m=iagemin; m <= iagemax+3; m++)
2942: prop[i][m]=0;
1.126 brouard 2943:
2944: dateintsum=0;
2945: k2cpt=0;
2946: for (i=1; i<=imx; i++) {
2947: bool=1;
1.144 brouard 2948: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2949: for (z1=1; z1<=cptcoveff; z1++)
2950: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2951: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2952: bool=0;
1.145 brouard 2953: /* 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",
2954: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2955: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2956: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2957: }
1.126 brouard 2958: }
1.144 brouard 2959:
1.126 brouard 2960: if (bool==1){
2961: for(m=firstpass; m<=lastpass; m++){
2962: k2=anint[m][i]+(mint[m][i]/12.);
2963: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2964: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2965: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2966: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2967: if (m<lastpass) {
2968: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2969: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2970: }
2971:
2972: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2973: dateintsum=dateintsum+k2;
2974: k2cpt++;
2975: }
2976: /*}*/
2977: }
2978: }
1.145 brouard 2979: } /* end i */
1.126 brouard 2980:
2981: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2982: pstamp(ficresp);
2983: if (cptcovn>0) {
2984: fprintf(ficresp, "\n#********** Variable ");
2985: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2986: fprintf(ficresp, "**********\n#");
1.143 brouard 2987: fprintf(ficlog, "\n#********** Variable ");
2988: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2989: fprintf(ficlog, "**********\n#");
1.126 brouard 2990: }
2991: for(i=1; i<=nlstate;i++)
2992: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2993: fprintf(ficresp, "\n");
2994:
2995: for(i=iagemin; i <= iagemax+3; i++){
2996: if(i==iagemax+3){
2997: fprintf(ficlog,"Total");
2998: }else{
2999: if(first==1){
3000: first=0;
3001: printf("See log file for details...\n");
3002: }
3003: fprintf(ficlog,"Age %d", i);
3004: }
3005: for(jk=1; jk <=nlstate ; jk++){
3006: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3007: pp[jk] += freq[jk][m][i];
3008: }
3009: for(jk=1; jk <=nlstate ; jk++){
3010: for(m=-1, pos=0; m <=0 ; m++)
3011: pos += freq[jk][m][i];
3012: if(pp[jk]>=1.e-10){
3013: if(first==1){
1.132 brouard 3014: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3015: }
3016: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3017: }else{
3018: if(first==1)
3019: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3020: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3021: }
3022: }
3023:
3024: for(jk=1; jk <=nlstate ; jk++){
3025: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3026: pp[jk] += freq[jk][m][i];
3027: }
3028: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3029: pos += pp[jk];
3030: posprop += prop[jk][i];
3031: }
3032: for(jk=1; jk <=nlstate ; jk++){
3033: if(pos>=1.e-5){
3034: if(first==1)
3035: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3036: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3037: }else{
3038: if(first==1)
3039: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3040: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3041: }
3042: if( i <= iagemax){
3043: if(pos>=1.e-5){
3044: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3045: /*probs[i][jk][j1]= pp[jk]/pos;*/
3046: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3047: }
3048: else
3049: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3050: }
3051: }
3052:
3053: for(jk=-1; jk <=nlstate+ndeath; jk++)
3054: for(m=-1; m <=nlstate+ndeath; m++)
3055: if(freq[jk][m][i] !=0 ) {
3056: if(first==1)
3057: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3058: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3059: }
3060: if(i <= iagemax)
3061: fprintf(ficresp,"\n");
3062: if(first==1)
3063: printf("Others in log...\n");
3064: fprintf(ficlog,"\n");
3065: }
1.145 brouard 3066: /*}*/
1.126 brouard 3067: }
3068: dateintmean=dateintsum/k2cpt;
3069:
3070: fclose(ficresp);
3071: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3072: free_vector(pp,1,nlstate);
3073: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3074: /* End of Freq */
3075: }
3076:
3077: /************ Prevalence ********************/
3078: 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)
3079: {
3080: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3081: in each health status at the date of interview (if between dateprev1 and dateprev2).
3082: We still use firstpass and lastpass as another selection.
3083: */
3084:
1.164 brouard 3085: int i, m, jk, j1, bool, z1,j;
3086:
3087: double **prop;
3088: double posprop;
1.126 brouard 3089: double y2; /* in fractional years */
3090: int iagemin, iagemax;
1.145 brouard 3091: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3092:
3093: iagemin= (int) agemin;
3094: iagemax= (int) agemax;
3095: /*pp=vector(1,nlstate);*/
3096: prop=matrix(1,nlstate,iagemin,iagemax+3);
3097: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3098: j1=0;
3099:
1.145 brouard 3100: /*j=cptcoveff;*/
1.126 brouard 3101: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3102:
1.145 brouard 3103: first=1;
3104: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3105: /*for(i1=1; i1<=ncodemax[k1];i1++){
3106: j1++;*/
1.126 brouard 3107:
3108: for (i=1; i<=nlstate; i++)
3109: for(m=iagemin; m <= iagemax+3; m++)
3110: prop[i][m]=0.0;
3111:
3112: for (i=1; i<=imx; i++) { /* Each individual */
3113: bool=1;
3114: if (cptcovn>0) {
3115: for (z1=1; z1<=cptcoveff; z1++)
3116: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
3117: bool=0;
3118: }
3119: if (bool==1) {
3120: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3121: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3122: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3123: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3124: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3125: 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);
3126: if (s[m][i]>0 && s[m][i]<=nlstate) {
3127: /*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]]);*/
3128: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3129: prop[s[m][i]][iagemax+3] += weight[i];
3130: }
3131: }
3132: } /* end selection of waves */
3133: }
3134: }
3135: for(i=iagemin; i <= iagemax+3; i++){
3136: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3137: posprop += prop[jk][i];
3138: }
1.145 brouard 3139:
1.126 brouard 3140: for(jk=1; jk <=nlstate ; jk++){
3141: if( i <= iagemax){
3142: if(posprop>=1.e-5){
3143: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3144: } else{
3145: if(first==1){
3146: first=0;
3147: 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]);
3148: }
3149: }
1.126 brouard 3150: }
3151: }/* end jk */
3152: }/* end i */
1.145 brouard 3153: /*} *//* end i1 */
3154: } /* end j1 */
1.126 brouard 3155:
3156: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3157: /*free_vector(pp,1,nlstate);*/
3158: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3159: } /* End of prevalence */
3160:
3161: /************* Waves Concatenation ***************/
3162:
3163: 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)
3164: {
3165: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3166: Death is a valid wave (if date is known).
3167: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3168: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3169: and mw[mi+1][i]. dh depends on stepm.
3170: */
3171:
3172: int i, mi, m;
3173: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3174: double sum=0., jmean=0.;*/
3175: int first;
3176: int j, k=0,jk, ju, jl;
3177: double sum=0.;
3178: first=0;
1.164 brouard 3179: jmin=100000;
1.126 brouard 3180: jmax=-1;
3181: jmean=0.;
3182: for(i=1; i<=imx; i++){
3183: mi=0;
3184: m=firstpass;
3185: while(s[m][i] <= nlstate){
3186: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3187: mw[++mi][i]=m;
3188: if(m >=lastpass)
3189: break;
3190: else
3191: m++;
3192: }/* end while */
3193: if (s[m][i] > nlstate){
3194: mi++; /* Death is another wave */
3195: /* if(mi==0) never been interviewed correctly before death */
3196: /* Only death is a correct wave */
3197: mw[mi][i]=m;
3198: }
3199:
3200: wav[i]=mi;
3201: if(mi==0){
3202: nbwarn++;
3203: if(first==0){
3204: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3205: first=1;
3206: }
3207: if(first==1){
3208: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3209: }
3210: } /* end mi==0 */
3211: } /* End individuals */
3212:
3213: for(i=1; i<=imx; i++){
3214: for(mi=1; mi<wav[i];mi++){
3215: if (stepm <=0)
3216: dh[mi][i]=1;
3217: else{
3218: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3219: if (agedc[i] < 2*AGESUP) {
3220: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3221: if(j==0) j=1; /* Survives at least one month after exam */
3222: else if(j<0){
3223: nberr++;
3224: 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]);
3225: j=1; /* Temporary Dangerous patch */
3226: 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);
3227: 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]);
3228: 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);
3229: }
3230: k=k+1;
3231: if (j >= jmax){
3232: jmax=j;
3233: ijmax=i;
3234: }
3235: if (j <= jmin){
3236: jmin=j;
3237: ijmin=i;
3238: }
3239: sum=sum+j;
3240: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3241: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3242: }
3243: }
3244: else{
3245: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3246: /* 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]); */
3247:
3248: k=k+1;
3249: if (j >= jmax) {
3250: jmax=j;
3251: ijmax=i;
3252: }
3253: else if (j <= jmin){
3254: jmin=j;
3255: ijmin=i;
3256: }
3257: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3258: /*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]);*/
3259: if(j<0){
3260: nberr++;
3261: 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]);
3262: 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]);
3263: }
3264: sum=sum+j;
3265: }
3266: jk= j/stepm;
3267: jl= j -jk*stepm;
3268: ju= j -(jk+1)*stepm;
3269: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3270: if(jl==0){
3271: dh[mi][i]=jk;
3272: bh[mi][i]=0;
3273: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3274: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3275: dh[mi][i]=jk+1;
3276: bh[mi][i]=ju;
3277: }
3278: }else{
3279: if(jl <= -ju){
3280: dh[mi][i]=jk;
3281: bh[mi][i]=jl; /* bias is positive if real duration
3282: * is higher than the multiple of stepm and negative otherwise.
3283: */
3284: }
3285: else{
3286: dh[mi][i]=jk+1;
3287: bh[mi][i]=ju;
3288: }
3289: if(dh[mi][i]==0){
3290: dh[mi][i]=1; /* At least one step */
3291: bh[mi][i]=ju; /* At least one step */
3292: /* 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);*/
3293: }
3294: } /* end if mle */
3295: }
3296: } /* end wave */
3297: }
3298: jmean=sum/k;
3299: 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 3300: 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 3301: }
3302:
3303: /*********** Tricode ****************************/
1.145 brouard 3304: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3305: {
1.144 brouard 3306: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3307: /* 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 3308: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3309: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3310: * nbcode[Tvar[j]][1]=
1.144 brouard 3311: */
1.130 brouard 3312:
1.145 brouard 3313: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3314: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3315: int cptcode=0; /* Modality max of covariates j */
3316: int modmincovj=0; /* Modality min of covariates j */
3317:
3318:
1.126 brouard 3319: cptcoveff=0;
3320:
1.144 brouard 3321: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3322:
1.145 brouard 3323: /* Loop on covariates without age and products */
1.186 brouard 3324: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3325: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3326: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3327: modality of this covariate Vj*/
1.145 brouard 3328: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3329: * If product of Vn*Vm, still boolean *:
3330: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3331: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3332: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3333: modality of the nth covariate of individual i. */
1.145 brouard 3334: if (ij > modmaxcovj)
3335: modmaxcovj=ij;
3336: else if (ij < modmincovj)
3337: modmincovj=ij;
3338: if ((ij < -1) && (ij > NCOVMAX)){
3339: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3340: exit(1);
3341: }else
1.136 brouard 3342: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3343: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3344: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3345: /* getting the maximum value of the modality of the covariate
3346: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3347: female is 1, then modmaxcovj=1.*/
1.192 brouard 3348: } /* end for loop on individuals i */
1.145 brouard 3349: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3350: 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 3351: cptcode=modmaxcovj;
1.137 brouard 3352: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3353: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3354: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3355: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3356: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3357: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3358: if( k != -1){
3359: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3360: covariate for which somebody answered excluding
3361: undefined. Usually 2: 0 and 1. */
3362: }
3363: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3364: covariate for which somebody answered including
3365: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3366: }
3367: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3368: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3369: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3370:
1.136 brouard 3371: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3372: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3373: 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 3374: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3375: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3376: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3377: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3378: nbcode[Tvar[j]][ij]=k;
3379: nbcode[Tvar[j]][1]=0;
3380: nbcode[Tvar[j]][2]=1;
3381: nbcode[Tvar[j]][3]=2;
3382: */
1.192 brouard 3383: ij=0; /* ij is similar to i but can jumps over null modalities */
3384: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 to 1*/
3385: if (Ndum[i] == 0) { /* If at least one individual responded to this modality k */
3386: break;
3387: }
3388: ij++;
3389: nbcode[Tvar[j]][ij]=i; /* stores the original modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
3390: cptcode = ij; /* New max modality for covar j */
3391: } /* end of loop on modality i=-1 to 1 or more */
3392:
3393: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3394: /* /\*recode from 0 *\/ */
3395: /* k is a modality. If we have model=V1+V1*sex */
3396: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3397: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3398: /* } */
3399: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3400: /* if (ij > ncodemax[j]) { */
3401: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3402: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3403: /* break; */
3404: /* } */
3405: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3406: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3407:
1.145 brouard 3408: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3409:
1.187 brouard 3410: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3411: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3412: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3413: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3414: }
1.126 brouard 3415:
1.192 brouard 3416: ij=0;
1.145 brouard 3417: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3418: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3419: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3420: ij++;
1.145 brouard 3421: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3422: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3423: }else{
3424: /* Tvaraff[ij]=0; */
3425: }
1.126 brouard 3426: }
1.192 brouard 3427: /* ij--; */
1.144 brouard 3428: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3429:
1.126 brouard 3430: }
3431:
1.145 brouard 3432:
1.126 brouard 3433: /*********** Health Expectancies ****************/
3434:
1.127 brouard 3435: 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 3436:
3437: {
3438: /* Health expectancies, no variances */
1.164 brouard 3439: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3440: int nhstepma, nstepma; /* Decreasing with age */
3441: double age, agelim, hf;
3442: double ***p3mat;
3443: double eip;
3444:
3445: pstamp(ficreseij);
3446: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3447: fprintf(ficreseij,"# Age");
3448: for(i=1; i<=nlstate;i++){
3449: for(j=1; j<=nlstate;j++){
3450: fprintf(ficreseij," e%1d%1d ",i,j);
3451: }
3452: fprintf(ficreseij," e%1d. ",i);
3453: }
3454: fprintf(ficreseij,"\n");
3455:
3456:
3457: if(estepm < stepm){
3458: printf ("Problem %d lower than %d\n",estepm, stepm);
3459: }
3460: else hstepm=estepm;
3461: /* We compute the life expectancy from trapezoids spaced every estepm months
3462: * This is mainly to measure the difference between two models: for example
3463: * if stepm=24 months pijx are given only every 2 years and by summing them
3464: * we are calculating an estimate of the Life Expectancy assuming a linear
3465: * progression in between and thus overestimating or underestimating according
3466: * to the curvature of the survival function. If, for the same date, we
3467: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3468: * to compare the new estimate of Life expectancy with the same linear
3469: * hypothesis. A more precise result, taking into account a more precise
3470: * curvature will be obtained if estepm is as small as stepm. */
3471:
3472: /* For example we decided to compute the life expectancy with the smallest unit */
3473: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3474: nhstepm is the number of hstepm from age to agelim
3475: nstepm is the number of stepm from age to agelin.
3476: Look at hpijx to understand the reason of that which relies in memory size
3477: and note for a fixed period like estepm months */
3478: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3479: survival function given by stepm (the optimization length). Unfortunately it
3480: means that if the survival funtion is printed only each two years of age and if
3481: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3482: results. So we changed our mind and took the option of the best precision.
3483: */
3484: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3485:
3486: agelim=AGESUP;
3487: /* If stepm=6 months */
3488: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3489: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3490:
3491: /* nhstepm age range expressed in number of stepm */
3492: nstepm=(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: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3496: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3497:
3498: for (age=bage; age<=fage; age ++){
3499: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3500: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3501: /* if (stepm >= YEARM) hstepm=1;*/
3502: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3503:
3504: /* If stepm=6 months */
3505: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3506: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3507:
3508: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3509:
3510: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3511:
3512: printf("%d|",(int)age);fflush(stdout);
3513: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3514:
3515: /* Computing expectancies */
3516: for(i=1; i<=nlstate;i++)
3517: for(j=1; j<=nlstate;j++)
3518: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3519: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3520:
3521: /* 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]);*/
3522:
3523: }
3524:
3525: fprintf(ficreseij,"%3.0f",age );
3526: for(i=1; i<=nlstate;i++){
3527: eip=0;
3528: for(j=1; j<=nlstate;j++){
3529: eip +=eij[i][j][(int)age];
3530: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3531: }
3532: fprintf(ficreseij,"%9.4f", eip );
3533: }
3534: fprintf(ficreseij,"\n");
3535:
3536: }
3537: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3538: printf("\n");
3539: fprintf(ficlog,"\n");
3540:
3541: }
3542:
1.127 brouard 3543: 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 3544:
3545: {
3546: /* Covariances of health expectancies eij and of total life expectancies according
3547: to initial status i, ei. .
3548: */
3549: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3550: int nhstepma, nstepma; /* Decreasing with age */
3551: double age, agelim, hf;
3552: double ***p3matp, ***p3matm, ***varhe;
3553: double **dnewm,**doldm;
3554: double *xp, *xm;
3555: double **gp, **gm;
3556: double ***gradg, ***trgradg;
3557: int theta;
3558:
3559: double eip, vip;
3560:
3561: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3562: xp=vector(1,npar);
3563: xm=vector(1,npar);
3564: dnewm=matrix(1,nlstate*nlstate,1,npar);
3565: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3566:
3567: pstamp(ficresstdeij);
3568: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3569: fprintf(ficresstdeij,"# Age");
3570: for(i=1; i<=nlstate;i++){
3571: for(j=1; j<=nlstate;j++)
3572: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3573: fprintf(ficresstdeij," e%1d. ",i);
3574: }
3575: fprintf(ficresstdeij,"\n");
3576:
3577: pstamp(ficrescveij);
3578: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3579: fprintf(ficrescveij,"# Age");
3580: for(i=1; i<=nlstate;i++)
3581: for(j=1; j<=nlstate;j++){
3582: cptj= (j-1)*nlstate+i;
3583: for(i2=1; i2<=nlstate;i2++)
3584: for(j2=1; j2<=nlstate;j2++){
3585: cptj2= (j2-1)*nlstate+i2;
3586: if(cptj2 <= cptj)
3587: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3588: }
3589: }
3590: fprintf(ficrescveij,"\n");
3591:
3592: if(estepm < stepm){
3593: printf ("Problem %d lower than %d\n",estepm, stepm);
3594: }
3595: else hstepm=estepm;
3596: /* We compute the life expectancy from trapezoids spaced every estepm months
3597: * This is mainly to measure the difference between two models: for example
3598: * if stepm=24 months pijx are given only every 2 years and by summing them
3599: * we are calculating an estimate of the Life Expectancy assuming a linear
3600: * progression in between and thus overestimating or underestimating according
3601: * to the curvature of the survival function. If, for the same date, we
3602: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3603: * to compare the new estimate of Life expectancy with the same linear
3604: * hypothesis. A more precise result, taking into account a more precise
3605: * curvature will be obtained if estepm is as small as stepm. */
3606:
3607: /* For example we decided to compute the life expectancy with the smallest unit */
3608: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3609: nhstepm is the number of hstepm from age to agelim
3610: nstepm is the number of stepm from age to agelin.
3611: Look at hpijx to understand the reason of that which relies in memory size
3612: and note for a fixed period like estepm months */
3613: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3614: survival function given by stepm (the optimization length). Unfortunately it
3615: means that if the survival funtion is printed only each two years of age and if
3616: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3617: results. So we changed our mind and took the option of the best precision.
3618: */
3619: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3620:
3621: /* If stepm=6 months */
3622: /* nhstepm age range expressed in number of stepm */
3623: agelim=AGESUP;
3624: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3625: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3626: /* if (stepm >= YEARM) hstepm=1;*/
3627: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3628:
3629: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3630: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3631: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3632: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3633: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3634: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3635:
3636: for (age=bage; age<=fage; age ++){
3637: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3638: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3639: /* if (stepm >= YEARM) hstepm=1;*/
3640: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3641:
3642: /* If stepm=6 months */
3643: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3644: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3645:
3646: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3647:
3648: /* Computing Variances of health expectancies */
3649: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3650: decrease memory allocation */
3651: for(theta=1; theta <=npar; theta++){
3652: for(i=1; i<=npar; i++){
3653: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3654: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3655: }
3656: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3657: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3658:
3659: for(j=1; j<= nlstate; j++){
3660: for(i=1; i<=nlstate; i++){
3661: for(h=0; h<=nhstepm-1; h++){
3662: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3663: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3664: }
3665: }
3666: }
3667:
3668: for(ij=1; ij<= nlstate*nlstate; ij++)
3669: for(h=0; h<=nhstepm-1; h++){
3670: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3671: }
3672: }/* End theta */
3673:
3674:
3675: for(h=0; h<=nhstepm-1; h++)
3676: for(j=1; j<=nlstate*nlstate;j++)
3677: for(theta=1; theta <=npar; theta++)
3678: trgradg[h][j][theta]=gradg[h][theta][j];
3679:
3680:
3681: for(ij=1;ij<=nlstate*nlstate;ij++)
3682: for(ji=1;ji<=nlstate*nlstate;ji++)
3683: varhe[ij][ji][(int)age] =0.;
3684:
3685: printf("%d|",(int)age);fflush(stdout);
3686: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3687: for(h=0;h<=nhstepm-1;h++){
3688: for(k=0;k<=nhstepm-1;k++){
3689: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3690: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3691: for(ij=1;ij<=nlstate*nlstate;ij++)
3692: for(ji=1;ji<=nlstate*nlstate;ji++)
3693: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3694: }
3695: }
3696:
3697: /* Computing expectancies */
3698: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3699: for(i=1; i<=nlstate;i++)
3700: for(j=1; j<=nlstate;j++)
3701: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3702: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3703:
3704: /* 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]);*/
3705:
3706: }
3707:
3708: fprintf(ficresstdeij,"%3.0f",age );
3709: for(i=1; i<=nlstate;i++){
3710: eip=0.;
3711: vip=0.;
3712: for(j=1; j<=nlstate;j++){
3713: eip += eij[i][j][(int)age];
3714: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3715: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3716: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3717: }
3718: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3719: }
3720: fprintf(ficresstdeij,"\n");
3721:
3722: fprintf(ficrescveij,"%3.0f",age );
3723: for(i=1; i<=nlstate;i++)
3724: for(j=1; j<=nlstate;j++){
3725: cptj= (j-1)*nlstate+i;
3726: for(i2=1; i2<=nlstate;i2++)
3727: for(j2=1; j2<=nlstate;j2++){
3728: cptj2= (j2-1)*nlstate+i2;
3729: if(cptj2 <= cptj)
3730: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3731: }
3732: }
3733: fprintf(ficrescveij,"\n");
3734:
3735: }
3736: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3737: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3738: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3739: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3740: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3741: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3742: printf("\n");
3743: fprintf(ficlog,"\n");
3744:
3745: free_vector(xm,1,npar);
3746: free_vector(xp,1,npar);
3747: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3748: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3749: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3750: }
3751:
3752: /************ Variance ******************/
3753: 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[])
3754: {
3755: /* Variance of health expectancies */
3756: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3757: /* double **newm;*/
1.169 brouard 3758: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3759:
3760: int movingaverage();
1.126 brouard 3761: double **dnewm,**doldm;
3762: double **dnewmp,**doldmp;
3763: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3764: int k;
1.126 brouard 3765: double *xp;
3766: double **gp, **gm; /* for var eij */
3767: double ***gradg, ***trgradg; /*for var eij */
3768: double **gradgp, **trgradgp; /* for var p point j */
3769: double *gpp, *gmp; /* for var p point j */
3770: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3771: double ***p3mat;
3772: double age,agelim, hf;
3773: double ***mobaverage;
3774: int theta;
3775: char digit[4];
3776: char digitp[25];
3777:
3778: char fileresprobmorprev[FILENAMELENGTH];
3779:
3780: if(popbased==1){
3781: if(mobilav!=0)
3782: strcpy(digitp,"-populbased-mobilav-");
3783: else strcpy(digitp,"-populbased-nomobil-");
3784: }
3785: else
3786: strcpy(digitp,"-stablbased-");
3787:
3788: if (mobilav!=0) {
3789: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3790: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3791: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3792: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3793: }
3794: }
3795:
3796: strcpy(fileresprobmorprev,"prmorprev");
3797: sprintf(digit,"%-d",ij);
3798: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3799: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3800: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3801: strcat(fileresprobmorprev,fileres);
3802: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3803: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3804: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3805: }
3806: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3807:
3808: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3809: pstamp(ficresprobmorprev);
3810: 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);
3811: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3812: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3813: fprintf(ficresprobmorprev," p.%-d SE",j);
3814: for(i=1; i<=nlstate;i++)
3815: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3816: }
3817: fprintf(ficresprobmorprev,"\n");
3818: fprintf(ficgp,"\n# Routine varevsij");
3819: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3820: 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");
3821: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3822: /* } */
3823: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3824: pstamp(ficresvij);
3825: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3826: if(popbased==1)
1.128 brouard 3827: 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 3828: else
3829: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3830: fprintf(ficresvij,"# Age");
3831: for(i=1; i<=nlstate;i++)
3832: for(j=1; j<=nlstate;j++)
3833: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3834: fprintf(ficresvij,"\n");
3835:
3836: xp=vector(1,npar);
3837: dnewm=matrix(1,nlstate,1,npar);
3838: doldm=matrix(1,nlstate,1,nlstate);
3839: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3840: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3841:
3842: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3843: gpp=vector(nlstate+1,nlstate+ndeath);
3844: gmp=vector(nlstate+1,nlstate+ndeath);
3845: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3846:
3847: if(estepm < stepm){
3848: printf ("Problem %d lower than %d\n",estepm, stepm);
3849: }
3850: else hstepm=estepm;
3851: /* For example we decided to compute the life expectancy with the smallest unit */
3852: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3853: nhstepm is the number of hstepm from age to agelim
3854: nstepm is the number of stepm from age to agelin.
1.128 brouard 3855: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3856: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3857: survival function given by stepm (the optimization length). Unfortunately it
3858: means that if the survival funtion is printed every two years of age and if
3859: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3860: results. So we changed our mind and took the option of the best precision.
3861: */
3862: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3863: agelim = AGESUP;
3864: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3865: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3866: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3867: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3868: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3869: gp=matrix(0,nhstepm,1,nlstate);
3870: gm=matrix(0,nhstepm,1,nlstate);
3871:
3872:
3873: for(theta=1; theta <=npar; theta++){
3874: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3875: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3876: }
3877: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3878: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3879:
3880: if (popbased==1) {
3881: if(mobilav ==0){
3882: for(i=1; i<=nlstate;i++)
3883: prlim[i][i]=probs[(int)age][i][ij];
3884: }else{ /* mobilav */
3885: for(i=1; i<=nlstate;i++)
3886: prlim[i][i]=mobaverage[(int)age][i][ij];
3887: }
3888: }
3889:
3890: for(j=1; j<= nlstate; j++){
3891: for(h=0; h<=nhstepm; h++){
3892: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3893: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3894: }
3895: }
3896: /* This for computing probability of death (h=1 means
3897: computed over hstepm matrices product = hstepm*stepm months)
3898: as a weighted average of prlim.
3899: */
3900: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3901: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3902: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3903: }
3904: /* end probability of death */
3905:
3906: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3907: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3908: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3909: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3910:
3911: if (popbased==1) {
3912: if(mobilav ==0){
3913: for(i=1; i<=nlstate;i++)
3914: prlim[i][i]=probs[(int)age][i][ij];
3915: }else{ /* mobilav */
3916: for(i=1; i<=nlstate;i++)
3917: prlim[i][i]=mobaverage[(int)age][i][ij];
3918: }
3919: }
3920:
1.128 brouard 3921: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3922: for(h=0; h<=nhstepm; h++){
3923: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3924: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3925: }
3926: }
3927: /* This for computing probability of death (h=1 means
3928: computed over hstepm matrices product = hstepm*stepm months)
3929: as a weighted average of prlim.
3930: */
3931: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3932: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3933: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3934: }
3935: /* end probability of death */
3936:
3937: for(j=1; j<= nlstate; j++) /* vareij */
3938: for(h=0; h<=nhstepm; h++){
3939: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3940: }
3941:
3942: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3943: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3944: }
3945:
3946: } /* End theta */
3947:
3948: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3949:
3950: for(h=0; h<=nhstepm; h++) /* veij */
3951: for(j=1; j<=nlstate;j++)
3952: for(theta=1; theta <=npar; theta++)
3953: trgradg[h][j][theta]=gradg[h][theta][j];
3954:
3955: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3956: for(theta=1; theta <=npar; theta++)
3957: trgradgp[j][theta]=gradgp[theta][j];
3958:
3959:
3960: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3961: for(i=1;i<=nlstate;i++)
3962: for(j=1;j<=nlstate;j++)
3963: vareij[i][j][(int)age] =0.;
3964:
3965: for(h=0;h<=nhstepm;h++){
3966: for(k=0;k<=nhstepm;k++){
3967: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3968: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3969: for(i=1;i<=nlstate;i++)
3970: for(j=1;j<=nlstate;j++)
3971: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3972: }
3973: }
3974:
3975: /* pptj */
3976: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3977: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3978: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3979: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3980: varppt[j][i]=doldmp[j][i];
3981: /* end ppptj */
3982: /* x centered again */
3983: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3984: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3985:
3986: if (popbased==1) {
3987: if(mobilav ==0){
3988: for(i=1; i<=nlstate;i++)
3989: prlim[i][i]=probs[(int)age][i][ij];
3990: }else{ /* mobilav */
3991: for(i=1; i<=nlstate;i++)
3992: prlim[i][i]=mobaverage[(int)age][i][ij];
3993: }
3994: }
3995:
3996: /* This for computing probability of death (h=1 means
3997: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3998: as a weighted average of prlim.
3999: */
4000: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4001: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4002: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4003: }
4004: /* end probability of death */
4005:
4006: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4007: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4008: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4009: for(i=1; i<=nlstate;i++){
4010: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4011: }
4012: }
4013: fprintf(ficresprobmorprev,"\n");
4014:
4015: fprintf(ficresvij,"%.0f ",age );
4016: for(i=1; i<=nlstate;i++)
4017: for(j=1; j<=nlstate;j++){
4018: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4019: }
4020: fprintf(ficresvij,"\n");
4021: free_matrix(gp,0,nhstepm,1,nlstate);
4022: free_matrix(gm,0,nhstepm,1,nlstate);
4023: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4024: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4025: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4026: } /* End age */
4027: free_vector(gpp,nlstate+1,nlstate+ndeath);
4028: free_vector(gmp,nlstate+1,nlstate+ndeath);
4029: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4030: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 4031: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 4032: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4033: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 4034: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4035: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4036: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4037: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4038: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4039: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4040: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4041: 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);
4042: /* 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);
4043: */
4044: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
4045: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4046:
4047: free_vector(xp,1,npar);
4048: free_matrix(doldm,1,nlstate,1,nlstate);
4049: free_matrix(dnewm,1,nlstate,1,npar);
4050: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4051: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4052: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4053: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4054: fclose(ficresprobmorprev);
4055: fflush(ficgp);
4056: fflush(fichtm);
4057: } /* end varevsij */
4058:
4059: /************ Variance of prevlim ******************/
4060: 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[])
4061: {
4062: /* Variance of prevalence limit */
4063: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4064:
1.126 brouard 4065: double **dnewm,**doldm;
4066: int i, j, nhstepm, hstepm;
4067: double *xp;
4068: double *gp, *gm;
4069: double **gradg, **trgradg;
4070: double age,agelim;
4071: int theta;
4072:
4073: pstamp(ficresvpl);
4074: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4075: fprintf(ficresvpl,"# Age");
4076: for(i=1; i<=nlstate;i++)
4077: fprintf(ficresvpl," %1d-%1d",i,i);
4078: fprintf(ficresvpl,"\n");
4079:
4080: xp=vector(1,npar);
4081: dnewm=matrix(1,nlstate,1,npar);
4082: doldm=matrix(1,nlstate,1,nlstate);
4083:
4084: hstepm=1*YEARM; /* Every year of age */
4085: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4086: agelim = AGESUP;
4087: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4088: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4089: if (stepm >= YEARM) hstepm=1;
4090: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4091: gradg=matrix(1,npar,1,nlstate);
4092: gp=vector(1,nlstate);
4093: gm=vector(1,nlstate);
4094:
4095: for(theta=1; theta <=npar; theta++){
4096: for(i=1; i<=npar; i++){ /* Computes gradient */
4097: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4098: }
4099: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4100: for(i=1;i<=nlstate;i++)
4101: gp[i] = prlim[i][i];
4102:
4103: for(i=1; i<=npar; i++) /* Computes gradient */
4104: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4105: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4106: for(i=1;i<=nlstate;i++)
4107: gm[i] = prlim[i][i];
4108:
4109: for(i=1;i<=nlstate;i++)
4110: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4111: } /* End theta */
4112:
4113: trgradg =matrix(1,nlstate,1,npar);
4114:
4115: for(j=1; j<=nlstate;j++)
4116: for(theta=1; theta <=npar; theta++)
4117: trgradg[j][theta]=gradg[theta][j];
4118:
4119: for(i=1;i<=nlstate;i++)
4120: varpl[i][(int)age] =0.;
4121: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4122: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4123: for(i=1;i<=nlstate;i++)
4124: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4125:
4126: fprintf(ficresvpl,"%.0f ",age );
4127: for(i=1; i<=nlstate;i++)
4128: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4129: fprintf(ficresvpl,"\n");
4130: free_vector(gp,1,nlstate);
4131: free_vector(gm,1,nlstate);
4132: free_matrix(gradg,1,npar,1,nlstate);
4133: free_matrix(trgradg,1,nlstate,1,npar);
4134: } /* End age */
4135:
4136: free_vector(xp,1,npar);
4137: free_matrix(doldm,1,nlstate,1,npar);
4138: free_matrix(dnewm,1,nlstate,1,nlstate);
4139:
4140: }
4141:
4142: /************ Variance of one-step probabilities ******************/
4143: 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[])
4144: {
1.164 brouard 4145: int i, j=0, k1, l1, tj;
1.126 brouard 4146: int k2, l2, j1, z1;
1.164 brouard 4147: int k=0, l;
1.145 brouard 4148: int first=1, first1, first2;
1.126 brouard 4149: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4150: double **dnewm,**doldm;
4151: double *xp;
4152: double *gp, *gm;
4153: double **gradg, **trgradg;
4154: double **mu;
1.164 brouard 4155: double age, cov[NCOVMAX+1];
1.126 brouard 4156: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4157: int theta;
4158: char fileresprob[FILENAMELENGTH];
4159: char fileresprobcov[FILENAMELENGTH];
4160: char fileresprobcor[FILENAMELENGTH];
4161: double ***varpij;
4162:
4163: strcpy(fileresprob,"prob");
4164: strcat(fileresprob,fileres);
4165: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4166: printf("Problem with resultfile: %s\n", fileresprob);
4167: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4168: }
4169: strcpy(fileresprobcov,"probcov");
4170: strcat(fileresprobcov,fileres);
4171: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4172: printf("Problem with resultfile: %s\n", fileresprobcov);
4173: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4174: }
4175: strcpy(fileresprobcor,"probcor");
4176: strcat(fileresprobcor,fileres);
4177: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4178: printf("Problem with resultfile: %s\n", fileresprobcor);
4179: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4180: }
4181: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4182: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4183: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4184: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4185: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4186: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4187: pstamp(ficresprob);
4188: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4189: fprintf(ficresprob,"# Age");
4190: pstamp(ficresprobcov);
4191: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4192: fprintf(ficresprobcov,"# Age");
4193: pstamp(ficresprobcor);
4194: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4195: fprintf(ficresprobcor,"# Age");
4196:
4197:
4198: for(i=1; i<=nlstate;i++)
4199: for(j=1; j<=(nlstate+ndeath);j++){
4200: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4201: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4202: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4203: }
4204: /* fprintf(ficresprob,"\n");
4205: fprintf(ficresprobcov,"\n");
4206: fprintf(ficresprobcor,"\n");
4207: */
1.131 brouard 4208: xp=vector(1,npar);
1.126 brouard 4209: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4210: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4211: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4212: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4213: first=1;
4214: fprintf(ficgp,"\n# Routine varprob");
4215: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4216: fprintf(fichtm,"\n");
4217:
4218: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
4219: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
4220: file %s<br>\n",optionfilehtmcov);
4221: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
4222: and drawn. It helps understanding how is the covariance between two incidences.\
4223: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4224: 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. \
4225: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4226: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4227: standard deviations wide on each axis. <br>\
4228: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4229: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4230: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4231:
4232: cov[1]=1;
1.145 brouard 4233: /* tj=cptcoveff; */
4234: tj = (int) pow(2,cptcoveff);
1.126 brouard 4235: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4236: j1=0;
1.145 brouard 4237: for(j1=1; j1<=tj;j1++){
4238: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4239: /*j1++;*/
1.126 brouard 4240: if (cptcovn>0) {
4241: fprintf(ficresprob, "\n#********** Variable ");
4242: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4243: fprintf(ficresprob, "**********\n#\n");
4244: fprintf(ficresprobcov, "\n#********** Variable ");
4245: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4246: fprintf(ficresprobcov, "**********\n#\n");
4247:
4248: fprintf(ficgp, "\n#********** Variable ");
4249: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4250: fprintf(ficgp, "**********\n#\n");
4251:
4252:
4253: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4254: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4255: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4256:
4257: fprintf(ficresprobcor, "\n#********** Variable ");
4258: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4259: fprintf(ficresprobcor, "**********\n#");
4260: }
4261:
1.145 brouard 4262: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4263: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4264: gp=vector(1,(nlstate)*(nlstate+ndeath));
4265: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4266: for (age=bage; age<=fage; age ++){
4267: cov[2]=age;
1.187 brouard 4268: if(nagesqr==1)
4269: cov[3]= age*age;
1.126 brouard 4270: for (k=1; k<=cptcovn;k++) {
1.187 brouard 4271: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145 brouard 4272: * 1 1 1 1 1
4273: * 2 2 1 1 1
4274: * 3 1 2 1 1
4275: */
4276: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4277: }
1.186 brouard 4278: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4279: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126 brouard 4280: for (k=1; k<=cptcovprod;k++)
1.187 brouard 4281: 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 4282:
4283:
4284: for(theta=1; theta <=npar; theta++){
4285: for(i=1; i<=npar; i++)
4286: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4287:
4288: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4289:
4290: k=0;
4291: for(i=1; i<= (nlstate); i++){
4292: for(j=1; j<=(nlstate+ndeath);j++){
4293: k=k+1;
4294: gp[k]=pmmij[i][j];
4295: }
4296: }
4297:
4298: for(i=1; i<=npar; i++)
4299: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4300:
4301: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4302: k=0;
4303: for(i=1; i<=(nlstate); i++){
4304: for(j=1; j<=(nlstate+ndeath);j++){
4305: k=k+1;
4306: gm[k]=pmmij[i][j];
4307: }
4308: }
4309:
4310: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4311: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4312: }
4313:
4314: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4315: for(theta=1; theta <=npar; theta++)
4316: trgradg[j][theta]=gradg[theta][j];
4317:
4318: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4319: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4320:
4321: pmij(pmmij,cov,ncovmodel,x,nlstate);
4322:
4323: k=0;
4324: for(i=1; i<=(nlstate); i++){
4325: for(j=1; j<=(nlstate+ndeath);j++){
4326: k=k+1;
4327: mu[k][(int) age]=pmmij[i][j];
4328: }
4329: }
4330: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4331: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4332: varpij[i][j][(int)age] = doldm[i][j];
4333:
4334: /*printf("\n%d ",(int)age);
4335: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4336: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4337: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4338: }*/
4339:
4340: fprintf(ficresprob,"\n%d ",(int)age);
4341: fprintf(ficresprobcov,"\n%d ",(int)age);
4342: fprintf(ficresprobcor,"\n%d ",(int)age);
4343:
4344: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4345: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4346: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4347: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4348: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4349: }
4350: i=0;
4351: for (k=1; k<=(nlstate);k++){
4352: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4353: i++;
1.126 brouard 4354: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4355: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4356: for (j=1; j<=i;j++){
1.145 brouard 4357: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4358: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4359: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4360: }
4361: }
4362: }/* end of loop for state */
4363: } /* end of loop for age */
1.145 brouard 4364: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4365: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4366: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4367: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4368:
1.126 brouard 4369: /* Confidence intervalle of pij */
4370: /*
1.131 brouard 4371: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4372: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4373: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4374: 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);
4375: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4376: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4377: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4378: */
4379:
4380: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4381: first1=1;first2=2;
1.126 brouard 4382: for (k2=1; k2<=(nlstate);k2++){
4383: for (l2=1; l2<=(nlstate+ndeath);l2++){
4384: if(l2==k2) continue;
4385: j=(k2-1)*(nlstate+ndeath)+l2;
4386: for (k1=1; k1<=(nlstate);k1++){
4387: for (l1=1; l1<=(nlstate+ndeath);l1++){
4388: if(l1==k1) continue;
4389: i=(k1-1)*(nlstate+ndeath)+l1;
4390: if(i<=j) continue;
4391: for (age=bage; age<=fage; age ++){
4392: if ((int)age %5==0){
4393: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4394: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4395: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4396: mu1=mu[i][(int) age]/stepm*YEARM ;
4397: mu2=mu[j][(int) age]/stepm*YEARM;
4398: c12=cv12/sqrt(v1*v2);
4399: /* Computing eigen value of matrix of covariance */
4400: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4401: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4402: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4403: if(first2==1){
4404: first1=0;
4405: 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);
4406: }
4407: 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);
4408: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4409: /* lc2=fabs(lc2); */
1.135 brouard 4410: }
4411:
1.126 brouard 4412: /* Eigen vectors */
4413: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4414: /*v21=sqrt(1.-v11*v11); *//* error */
4415: v21=(lc1-v1)/cv12*v11;
4416: v12=-v21;
4417: v22=v11;
4418: tnalp=v21/v11;
4419: if(first1==1){
4420: first1=0;
4421: 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);
4422: }
4423: 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);
4424: /*printf(fignu*/
4425: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4426: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4427: if(first==1){
4428: first=0;
4429: fprintf(ficgp,"\nset parametric;unset label");
4430: 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 4431: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4432: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4433: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4434: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4435: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4436: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4437: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4438: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4439: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4440: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4441: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4442: 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",\
4443: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4444: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4445: }else{
4446: first=0;
4447: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4448: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4449: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4450: 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",\
4451: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4452: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4453: }/* if first */
4454: } /* age mod 5 */
4455: } /* end loop age */
4456: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4457: first=1;
4458: } /*l12 */
4459: } /* k12 */
4460: } /*l1 */
4461: }/* k1 */
1.169 brouard 4462: /* } */ /* loop covariates */
1.126 brouard 4463: }
4464: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4465: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4466: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4467: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4468: free_vector(xp,1,npar);
4469: fclose(ficresprob);
4470: fclose(ficresprobcov);
4471: fclose(ficresprobcor);
4472: fflush(ficgp);
4473: fflush(fichtmcov);
4474: }
4475:
4476:
4477: /******************* Printing html file ***********/
4478: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4479: int lastpass, int stepm, int weightopt, char model[],\
4480: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4481: int popforecast, int estepm ,\
4482: double jprev1, double mprev1,double anprev1, \
4483: double jprev2, double mprev2,double anprev2){
4484: int jj1, k1, i1, cpt;
4485:
4486: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4487: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4488: </ul>");
4489: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4490: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4491: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4492: fprintf(fichtm,"\
4493: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4494: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4495: fprintf(fichtm,"\
4496: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4497: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4498: fprintf(fichtm,"\
1.128 brouard 4499: - (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 4500: <a href=\"%s\">%s</a> <br>\n",
4501: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4502: fprintf(fichtm,"\
4503: - Population projections by age and states: \
4504: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4505:
4506: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4507:
1.145 brouard 4508: m=pow(2,cptcoveff);
1.126 brouard 4509: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4510:
4511: jj1=0;
4512: for(k1=1; k1<=m;k1++){
1.192 brouard 4513: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4514: jj1++;
4515: if (cptcovn > 0) {
4516: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4517: for (cpt=1; cpt<=cptcoveff;cpt++){
1.126 brouard 4518: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
1.192 brouard 4519: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
4520: }
1.126 brouard 4521: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4522: }
4523: /* Pij */
1.145 brouard 4524: 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> \
4525: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4526: /* Quasi-incidences */
4527: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4528: 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> \
4529: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4530: /* Period (stable) prevalence in each health state */
1.154 brouard 4531: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4532: 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> \
4533: <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 4534: }
4535: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4536: 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> \
4537: <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 4538: }
1.192 brouard 4539: /* } /\* end i1 *\/ */
1.126 brouard 4540: }/* End k1 */
4541: fprintf(fichtm,"</ul>");
4542:
4543: fprintf(fichtm,"\
4544: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4545: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
4546: - 95%% confidence intervals and T statistics are in the log file.<br>\n", rfileres,rfileres);
1.126 brouard 4547:
1.193 brouard 4548: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126 brouard 4549: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4550: fprintf(fichtm,"\
4551: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4552: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4553:
4554: fprintf(fichtm,"\
4555: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4556: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4557: fprintf(fichtm,"\
4558: - 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): \
4559: <a href=\"%s\">%s</a> <br>\n</li>",
4560: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4561: fprintf(fichtm,"\
4562: - (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): \
4563: <a href=\"%s\">%s</a> <br>\n</li>",
4564: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4565: fprintf(fichtm,"\
1.128 brouard 4566: - 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 4567: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4568: fprintf(fichtm,"\
1.128 brouard 4569: - 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",
4570: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4571: fprintf(fichtm,"\
4572: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4573: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4574:
4575: /* if(popforecast==1) fprintf(fichtm,"\n */
4576: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4577: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4578: /* <br>",fileres,fileres,fileres,fileres); */
4579: /* else */
4580: /* 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); */
4581: fflush(fichtm);
4582: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4583:
1.145 brouard 4584: m=pow(2,cptcoveff);
1.126 brouard 4585: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4586:
4587: jj1=0;
4588: for(k1=1; k1<=m;k1++){
1.192 brouard 4589: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4590: jj1++;
4591: if (cptcovn > 0) {
4592: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4593: for (cpt=1; cpt<=cptcoveff;cpt++)
4594: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4595: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4596: }
4597: for(cpt=1; cpt<=nlstate;cpt++) {
4598: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4599: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4600: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4601: }
4602: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4603: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4604: true period expectancies (those weighted with period prevalences are also\
4605: drawn in addition to the population based expectancies computed using\
4606: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4607: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192 brouard 4608: /* } /\* end i1 *\/ */
1.126 brouard 4609: }/* End k1 */
4610: fprintf(fichtm,"</ul>");
4611: fflush(fichtm);
4612: }
4613:
4614: /******************* Gnuplot file **************/
4615: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4616:
4617: char dirfileres[132],optfileres[132];
1.164 brouard 4618: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4619: int ng=0;
1.126 brouard 4620: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4621: /* printf("Problem with file %s",optionfilegnuplot); */
4622: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4623: /* } */
4624:
4625: /*#ifdef windows */
4626: fprintf(ficgp,"cd \"%s\" \n",pathc);
4627: /*#endif */
4628: m=pow(2,cptcoveff);
4629:
4630: strcpy(dirfileres,optionfilefiname);
4631: strcpy(optfileres,"vpl");
4632: /* 1eme*/
1.153 brouard 4633: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4634: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4635: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4636: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4637: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4638: fprintf(ficgp,"set xlabel \"Age\" \n\
4639: set ylabel \"Probability\" \n\
1.145 brouard 4640: set ter png small size 320, 240\n\
1.170 brouard 4641: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4642:
4643: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4644: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4645: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4646: }
1.170 brouard 4647: 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 4648: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4649: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4650: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4651: }
1.170 brouard 4652: 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 4653: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4654: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4655: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4656: }
1.145 brouard 4657: 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 4658: }
4659: }
4660: /*2 eme*/
1.153 brouard 4661: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4662: for (k1=1; k1<= m ; k1 ++) {
4663: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4664: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4665:
4666: for (i=1; i<= nlstate+1 ; i ++) {
4667: k=2*i;
1.170 brouard 4668: fprintf(ficgp,"\"%s\" every :::%d::%d u 1: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: }
4673: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4674: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4675: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4676: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4677: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4678: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4679: }
1.145 brouard 4680: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4681: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4682: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4683: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4684: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4685: }
1.145 brouard 4686: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4687: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4688: }
4689: }
4690:
4691: /*3eme*/
4692:
4693: for (k1=1; k1<= m ; k1 ++) {
4694: for (cpt=1; cpt<= nlstate ; cpt ++) {
4695: /* k=2+nlstate*(2*cpt-2); */
4696: k=2+(nlstate+1)*(cpt-1);
4697: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4698: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4699: 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);
4700: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4701: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4702: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4703: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4704: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4705: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4706:
4707: */
4708: for (i=1; i< nlstate ; i ++) {
4709: 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);
4710: /* 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);*/
4711:
4712: }
4713: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4714: }
4715: }
4716:
4717: /* CV preval stable (period) */
1.153 brouard 4718: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4719: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4720: k=3;
1.153 brouard 4721: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4722: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4723: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4724: set ter png small size 320, 240\n\
1.126 brouard 4725: unset log y\n\
1.153 brouard 4726: plot [%.f:%.f] ", ageminpar, agemaxpar);
4727: for (i=1; i<= nlstate ; i ++){
4728: if(i==1)
4729: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4730: else
4731: fprintf(ficgp,", '' ");
1.154 brouard 4732: l=(nlstate+ndeath)*(i-1)+1;
4733: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4734: for (j=1; j<= (nlstate-1) ; j ++)
4735: fprintf(ficgp,"+$%d",k+l+j);
4736: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4737: } /* nlstate */
4738: fprintf(ficgp,"\n");
4739: } /* end cpt state*/
4740: } /* end covariate */
1.126 brouard 4741:
4742: /* proba elementaires */
1.187 brouard 4743: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 4744: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 4745: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 4746: for(k=1; k <=(nlstate+ndeath); k++){
4747: if (k != i) {
1.187 brouard 4748: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 4749: for(j=1; j <=ncovmodel; j++){
1.187 brouard 4750: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 4751: jk++;
4752: }
1.187 brouard 4753: fprintf(ficgp,"\n");
1.126 brouard 4754: }
4755: }
4756: }
1.187 brouard 4757: fprintf(ficgp,"##############\n#\n");
4758:
1.145 brouard 4759: /*goto avoid;*/
1.187 brouard 4760: fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
4761: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4762: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4763: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4764: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4765: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4766: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4767: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4768: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4769: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4770: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4771: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4772: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4773: fprintf(ficgp,"#\n");
1.126 brouard 4774: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187 brouard 4775: fprintf(ficgp,"# ng=%d\n",ng);
4776: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 4777: for(jk=1; jk <=m; jk++) {
1.187 brouard 4778: fprintf(ficgp,"# jk=%d\n",jk);
1.145 brouard 4779: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4780: if (ng==2)
4781: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4782: else
4783: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4784: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4785: i=1;
4786: for(k2=1; k2<=nlstate; k2++) {
4787: k3=i;
4788: for(k=1; k<=(nlstate+ndeath); k++) {
4789: if (k != k2){
4790: if(ng==2)
1.187 brouard 4791: if(nagesqr==0)
4792: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4793: else /* nagesqr =1 */
4794: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126 brouard 4795: else
1.187 brouard 4796: if(nagesqr==0)
4797: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4798: else /* nagesqr =1 */
4799: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141 brouard 4800: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 4801: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186 brouard 4802: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187 brouard 4803: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186 brouard 4804: ij++;
4805: }
4806: else
1.187 brouard 4807: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4808: }
4809: fprintf(ficgp,")/(1");
4810:
1.187 brouard 4811: for(k1=1; k1 <=nlstate; k1++){
4812: if(nagesqr==0)
4813: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4814: else /* nagesqr =1 */
4815: 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);
4816:
1.126 brouard 4817: ij=1;
1.187 brouard 4818: for(j=3; j <=ncovmodel-nagesqr; j++){
1.186 brouard 4819: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187 brouard 4820: 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 4821: ij++;
4822: }
4823: else
1.187 brouard 4824: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4825: }
4826: fprintf(ficgp,")");
4827: }
4828: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4829: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4830: i=i+ncovmodel;
4831: }
4832: } /* end k */
4833: } /* end k2 */
4834: } /* end jk */
4835: } /* end ng */
1.164 brouard 4836: /* avoid: */
1.126 brouard 4837: fflush(ficgp);
4838: } /* end gnuplot */
4839:
4840:
4841: /*************** Moving average **************/
4842: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4843:
4844: int i, cpt, cptcod;
4845: int modcovmax =1;
4846: int mobilavrange, mob;
4847: double age;
4848:
4849: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4850: a covariate has 2 modalities */
4851: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4852:
4853: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4854: if(mobilav==1) mobilavrange=5; /* default */
4855: else mobilavrange=mobilav;
4856: for (age=bage; age<=fage; age++)
4857: for (i=1; i<=nlstate;i++)
4858: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4859: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4860: /* We keep the original values on the extreme ages bage, fage and for
4861: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4862: we use a 5 terms etc. until the borders are no more concerned.
4863: */
4864: for (mob=3;mob <=mobilavrange;mob=mob+2){
4865: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4866: for (i=1; i<=nlstate;i++){
4867: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4868: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4869: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4870: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4871: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4872: }
4873: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4874: }
4875: }
4876: }/* end age */
4877: }/* end mob */
4878: }else return -1;
4879: return 0;
4880: }/* End movingaverage */
4881:
4882:
4883: /************** Forecasting ******************/
1.169 brouard 4884: 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 4885: /* proj1, year, month, day of starting projection
4886: agemin, agemax range of age
4887: dateprev1 dateprev2 range of dates during which prevalence is computed
4888: anproj2 year of en of projection (same day and month as proj1).
4889: */
1.164 brouard 4890: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4891: double agec; /* generic age */
4892: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4893: double *popeffectif,*popcount;
4894: double ***p3mat;
4895: double ***mobaverage;
4896: char fileresf[FILENAMELENGTH];
4897:
4898: agelim=AGESUP;
4899: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4900:
4901: strcpy(fileresf,"f");
4902: strcat(fileresf,fileres);
4903: if((ficresf=fopen(fileresf,"w"))==NULL) {
4904: printf("Problem with forecast resultfile: %s\n", fileresf);
4905: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4906: }
4907: printf("Computing forecasting: result on file '%s' \n", fileresf);
4908: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4909:
4910: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4911:
4912: if (mobilav!=0) {
4913: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4914: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4915: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4916: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4917: }
4918: }
4919:
4920: stepsize=(int) (stepm+YEARM-1)/YEARM;
4921: if (stepm<=12) stepsize=1;
4922: if(estepm < stepm){
4923: printf ("Problem %d lower than %d\n",estepm, stepm);
4924: }
4925: else hstepm=estepm;
4926:
4927: hstepm=hstepm/stepm;
4928: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4929: fractional in yp1 */
4930: anprojmean=yp;
4931: yp2=modf((yp1*12),&yp);
4932: mprojmean=yp;
4933: yp1=modf((yp2*30.5),&yp);
4934: jprojmean=yp;
4935: if(jprojmean==0) jprojmean=1;
4936: if(mprojmean==0) jprojmean=1;
4937:
4938: i1=cptcoveff;
4939: if (cptcovn < 1){i1=1;}
4940:
4941: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4942:
4943: fprintf(ficresf,"#****** Routine prevforecast **\n");
4944:
4945: /* if (h==(int)(YEARM*yearp)){ */
4946: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4947: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4948: k=k+1;
4949: fprintf(ficresf,"\n#******");
4950: for(j=1;j<=cptcoveff;j++) {
4951: 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]]);
4952: }
4953: fprintf(ficresf,"******\n");
4954: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4955: for(j=1; j<=nlstate+ndeath;j++){
4956: for(i=1; i<=nlstate;i++)
4957: fprintf(ficresf," p%d%d",i,j);
4958: fprintf(ficresf," p.%d",j);
4959: }
4960: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4961: fprintf(ficresf,"\n");
4962: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4963:
4964: for (agec=fage; agec>=(ageminpar-1); agec--){
4965: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4966: nhstepm = nhstepm/hstepm;
4967: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4968: oldm=oldms;savm=savms;
4969: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4970:
4971: for (h=0; h<=nhstepm; h++){
4972: if (h*hstepm/YEARM*stepm ==yearp) {
4973: fprintf(ficresf,"\n");
4974: for(j=1;j<=cptcoveff;j++)
4975: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4976: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4977: }
4978: for(j=1; j<=nlstate+ndeath;j++) {
4979: ppij=0.;
4980: for(i=1; i<=nlstate;i++) {
4981: if (mobilav==1)
4982: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4983: else {
4984: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4985: }
4986: if (h*hstepm/YEARM*stepm== yearp) {
4987: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4988: }
4989: } /* end i */
4990: if (h*hstepm/YEARM*stepm==yearp) {
4991: fprintf(ficresf," %.3f", ppij);
4992: }
4993: }/* end j */
4994: } /* end h */
4995: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4996: } /* end agec */
4997: } /* end yearp */
4998: } /* end cptcod */
4999: } /* end cptcov */
5000:
5001: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5002:
5003: fclose(ficresf);
5004: }
5005:
5006: /************** Forecasting *****not tested NB*************/
1.169 brouard 5007: 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 5008:
5009: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5010: int *popage;
5011: double calagedatem, agelim, kk1, kk2;
5012: double *popeffectif,*popcount;
5013: double ***p3mat,***tabpop,***tabpopprev;
5014: double ***mobaverage;
5015: char filerespop[FILENAMELENGTH];
5016:
5017: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5018: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5019: agelim=AGESUP;
5020: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5021:
5022: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5023:
5024:
5025: strcpy(filerespop,"pop");
5026: strcat(filerespop,fileres);
5027: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5028: printf("Problem with forecast resultfile: %s\n", filerespop);
5029: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5030: }
5031: printf("Computing forecasting: result on file '%s' \n", filerespop);
5032: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5033:
5034: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5035:
5036: if (mobilav!=0) {
5037: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5038: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5039: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5040: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5041: }
5042: }
5043:
5044: stepsize=(int) (stepm+YEARM-1)/YEARM;
5045: if (stepm<=12) stepsize=1;
5046:
5047: agelim=AGESUP;
5048:
5049: hstepm=1;
5050: hstepm=hstepm/stepm;
5051:
5052: if (popforecast==1) {
5053: if((ficpop=fopen(popfile,"r"))==NULL) {
5054: printf("Problem with population file : %s\n",popfile);exit(0);
5055: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5056: }
5057: popage=ivector(0,AGESUP);
5058: popeffectif=vector(0,AGESUP);
5059: popcount=vector(0,AGESUP);
5060:
5061: i=1;
5062: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5063:
5064: imx=i;
5065: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5066: }
5067:
5068: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5069: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5070: k=k+1;
5071: fprintf(ficrespop,"\n#******");
5072: for(j=1;j<=cptcoveff;j++) {
5073: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5074: }
5075: fprintf(ficrespop,"******\n");
5076: fprintf(ficrespop,"# Age");
5077: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5078: if (popforecast==1) fprintf(ficrespop," [Population]");
5079:
5080: for (cpt=0; cpt<=0;cpt++) {
5081: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5082:
5083: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5084: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5085: nhstepm = nhstepm/hstepm;
5086:
5087: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5088: oldm=oldms;savm=savms;
5089: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5090:
5091: for (h=0; h<=nhstepm; h++){
5092: if (h==(int) (calagedatem+YEARM*cpt)) {
5093: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5094: }
5095: for(j=1; j<=nlstate+ndeath;j++) {
5096: kk1=0.;kk2=0;
5097: for(i=1; i<=nlstate;i++) {
5098: if (mobilav==1)
5099: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5100: else {
5101: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5102: }
5103: }
5104: if (h==(int)(calagedatem+12*cpt)){
5105: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5106: /*fprintf(ficrespop," %.3f", kk1);
5107: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5108: }
5109: }
5110: for(i=1; i<=nlstate;i++){
5111: kk1=0.;
5112: for(j=1; j<=nlstate;j++){
5113: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5114: }
5115: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5116: }
5117:
5118: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5119: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5120: }
5121: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5122: }
5123: }
5124:
5125: /******/
5126:
5127: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5128: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5129: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5130: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5131: nhstepm = nhstepm/hstepm;
5132:
5133: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5134: oldm=oldms;savm=savms;
5135: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5136: for (h=0; h<=nhstepm; h++){
5137: if (h==(int) (calagedatem+YEARM*cpt)) {
5138: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5139: }
5140: for(j=1; j<=nlstate+ndeath;j++) {
5141: kk1=0.;kk2=0;
5142: for(i=1; i<=nlstate;i++) {
5143: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5144: }
5145: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5146: }
5147: }
5148: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5149: }
5150: }
5151: }
5152: }
5153:
5154: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5155:
5156: if (popforecast==1) {
5157: free_ivector(popage,0,AGESUP);
5158: free_vector(popeffectif,0,AGESUP);
5159: free_vector(popcount,0,AGESUP);
5160: }
5161: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5162: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5163: fclose(ficrespop);
5164: } /* End of popforecast */
5165:
5166: int fileappend(FILE *fichier, char *optionfich)
5167: {
5168: if((fichier=fopen(optionfich,"a"))==NULL) {
5169: printf("Problem with file: %s\n", optionfich);
5170: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5171: return (0);
5172: }
5173: fflush(fichier);
5174: return (1);
5175: }
5176:
5177:
5178: /**************** function prwizard **********************/
5179: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5180: {
5181:
5182: /* Wizard to print covariance matrix template */
5183:
1.164 brouard 5184: char ca[32], cb[32];
5185: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5186: int numlinepar;
5187:
5188: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5189: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5190: for(i=1; i <=nlstate; i++){
5191: jj=0;
5192: for(j=1; j <=nlstate+ndeath; j++){
5193: if(j==i) continue;
5194: jj++;
5195: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5196: printf("%1d%1d",i,j);
5197: fprintf(ficparo,"%1d%1d",i,j);
5198: for(k=1; k<=ncovmodel;k++){
5199: /* printf(" %lf",param[i][j][k]); */
5200: /* fprintf(ficparo," %lf",param[i][j][k]); */
5201: printf(" 0.");
5202: fprintf(ficparo," 0.");
5203: }
5204: printf("\n");
5205: fprintf(ficparo,"\n");
5206: }
5207: }
5208: printf("# Scales (for hessian or gradient estimation)\n");
5209: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5210: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5211: for(i=1; i <=nlstate; i++){
5212: jj=0;
5213: for(j=1; j <=nlstate+ndeath; j++){
5214: if(j==i) continue;
5215: jj++;
5216: fprintf(ficparo,"%1d%1d",i,j);
5217: printf("%1d%1d",i,j);
5218: fflush(stdout);
5219: for(k=1; k<=ncovmodel;k++){
5220: /* printf(" %le",delti3[i][j][k]); */
5221: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5222: printf(" 0.");
5223: fprintf(ficparo," 0.");
5224: }
5225: numlinepar++;
5226: printf("\n");
5227: fprintf(ficparo,"\n");
5228: }
5229: }
5230: printf("# Covariance matrix\n");
5231: /* # 121 Var(a12)\n\ */
5232: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5233: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5234: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5235: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5236: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5237: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5238: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5239: fflush(stdout);
5240: fprintf(ficparo,"# Covariance matrix\n");
5241: /* # 121 Var(a12)\n\ */
5242: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5243: /* # ...\n\ */
5244: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5245:
5246: for(itimes=1;itimes<=2;itimes++){
5247: jj=0;
5248: for(i=1; i <=nlstate; i++){
5249: for(j=1; j <=nlstate+ndeath; j++){
5250: if(j==i) continue;
5251: for(k=1; k<=ncovmodel;k++){
5252: jj++;
5253: ca[0]= k+'a'-1;ca[1]='\0';
5254: if(itimes==1){
5255: printf("#%1d%1d%d",i,j,k);
5256: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5257: }else{
5258: printf("%1d%1d%d",i,j,k);
5259: fprintf(ficparo,"%1d%1d%d",i,j,k);
5260: /* printf(" %.5le",matcov[i][j]); */
5261: }
5262: ll=0;
5263: for(li=1;li <=nlstate; li++){
5264: for(lj=1;lj <=nlstate+ndeath; lj++){
5265: if(lj==li) continue;
5266: for(lk=1;lk<=ncovmodel;lk++){
5267: ll++;
5268: if(ll<=jj){
5269: cb[0]= lk +'a'-1;cb[1]='\0';
5270: if(ll<jj){
5271: if(itimes==1){
5272: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5273: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5274: }else{
5275: printf(" 0.");
5276: fprintf(ficparo," 0.");
5277: }
5278: }else{
5279: if(itimes==1){
5280: printf(" Var(%s%1d%1d)",ca,i,j);
5281: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5282: }else{
5283: printf(" 0.");
5284: fprintf(ficparo," 0.");
5285: }
5286: }
5287: }
5288: } /* end lk */
5289: } /* end lj */
5290: } /* end li */
5291: printf("\n");
5292: fprintf(ficparo,"\n");
5293: numlinepar++;
5294: } /* end k*/
5295: } /*end j */
5296: } /* end i */
5297: } /* end itimes */
5298:
5299: } /* end of prwizard */
5300: /******************* Gompertz Likelihood ******************************/
5301: double gompertz(double x[])
5302: {
5303: double A,B,L=0.0,sump=0.,num=0.;
5304: int i,n=0; /* n is the size of the sample */
5305:
5306: for (i=0;i<=imx-1 ; i++) {
5307: sump=sump+weight[i];
5308: /* sump=sump+1;*/
5309: num=num+1;
5310: }
5311:
5312:
5313: /* for (i=0; i<=imx; i++)
5314: 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]);*/
5315:
5316: for (i=1;i<=imx ; i++)
5317: {
5318: if (cens[i] == 1 && wav[i]>1)
5319: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5320:
5321: if (cens[i] == 0 && wav[i]>1)
5322: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5323: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5324:
5325: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5326: if (wav[i] > 1 ) { /* ??? */
5327: L=L+A*weight[i];
5328: /* 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]);*/
5329: }
5330: }
5331:
5332: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5333:
5334: return -2*L*num/sump;
5335: }
5336:
1.136 brouard 5337: #ifdef GSL
5338: /******************* Gompertz_f Likelihood ******************************/
5339: double gompertz_f(const gsl_vector *v, void *params)
5340: {
5341: double A,B,LL=0.0,sump=0.,num=0.;
5342: double *x= (double *) v->data;
5343: int i,n=0; /* n is the size of the sample */
5344:
5345: for (i=0;i<=imx-1 ; i++) {
5346: sump=sump+weight[i];
5347: /* sump=sump+1;*/
5348: num=num+1;
5349: }
5350:
5351:
5352: /* for (i=0; i<=imx; i++)
5353: 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]);*/
5354: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5355: for (i=1;i<=imx ; i++)
5356: {
5357: if (cens[i] == 1 && wav[i]>1)
5358: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5359:
5360: if (cens[i] == 0 && wav[i]>1)
5361: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5362: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5363:
5364: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5365: if (wav[i] > 1 ) { /* ??? */
5366: LL=LL+A*weight[i];
5367: /* 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]);*/
5368: }
5369: }
5370:
5371: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5372: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5373:
5374: return -2*LL*num/sump;
5375: }
5376: #endif
5377:
1.126 brouard 5378: /******************* Printing html file ***********/
5379: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5380: int lastpass, int stepm, int weightopt, char model[],\
5381: int imx, double p[],double **matcov,double agemortsup){
5382: int i,k;
5383:
5384: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5385: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5386: for (i=1;i<=2;i++)
5387: 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]));
5388: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5389: fprintf(fichtm,"</ul>");
5390:
5391: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5392:
5393: 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>");
5394:
5395: for (k=agegomp;k<(agemortsup-2);k++)
5396: 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]);
5397:
5398:
5399: fflush(fichtm);
5400: }
5401:
5402: /******************* Gnuplot file **************/
5403: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5404:
5405: char dirfileres[132],optfileres[132];
1.164 brouard 5406:
1.126 brouard 5407: int ng;
5408:
5409:
5410: /*#ifdef windows */
5411: fprintf(ficgp,"cd \"%s\" \n",pathc);
5412: /*#endif */
5413:
5414:
5415: strcpy(dirfileres,optionfilefiname);
5416: strcpy(optfileres,"vpl");
5417: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5418: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5419: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5420: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5421: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5422:
5423: }
5424:
1.136 brouard 5425: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5426: {
1.126 brouard 5427:
1.136 brouard 5428: /*-------- data file ----------*/
5429: FILE *fic;
5430: char dummy[]=" ";
1.164 brouard 5431: int i=0, j=0, n=0;
1.136 brouard 5432: int linei, month, year,iout;
5433: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5434: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5435: char *stratrunc;
5436: int lstra;
1.126 brouard 5437:
5438:
1.136 brouard 5439: if((fic=fopen(datafile,"r"))==NULL) {
5440: printf("Problem while opening datafile: %s\n", datafile);return 1;
5441: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5442: }
1.126 brouard 5443:
1.136 brouard 5444: i=1;
5445: linei=0;
5446: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5447: linei=linei+1;
5448: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5449: if(line[j] == '\t')
5450: line[j] = ' ';
5451: }
5452: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5453: ;
5454: };
5455: line[j+1]=0; /* Trims blanks at end of line */
5456: if(line[0]=='#'){
5457: fprintf(ficlog,"Comment line\n%s\n",line);
5458: printf("Comment line\n%s\n",line);
5459: continue;
5460: }
5461: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5462: strcpy(line, linetmp);
1.136 brouard 5463:
1.126 brouard 5464:
1.136 brouard 5465: for (j=maxwav;j>=1;j--){
1.137 brouard 5466: cutv(stra, strb, line, ' ');
1.136 brouard 5467: if(strb[0]=='.') { /* Missing status */
5468: lval=-1;
5469: }else{
5470: errno=0;
5471: lval=strtol(strb,&endptr,10);
5472: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5473: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5474: 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);
5475: 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 5476: return 1;
5477: }
5478: }
5479: s[j][i]=lval;
5480:
5481: strcpy(line,stra);
5482: cutv(stra, strb,line,' ');
1.169 brouard 5483: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5484: }
1.169 brouard 5485: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5486: month=99;
5487: year=9999;
5488: }else{
1.141 brouard 5489: 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);
5490: 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 5491: return 1;
5492: }
5493: anint[j][i]= (double) year;
5494: mint[j][i]= (double)month;
5495: strcpy(line,stra);
5496: } /* ENd Waves */
5497:
5498: cutv(stra, strb,line,' ');
1.169 brouard 5499: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5500: }
1.169 brouard 5501: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5502: month=99;
5503: year=9999;
5504: }else{
1.141 brouard 5505: 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);
5506: 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 5507: return 1;
5508: }
5509: andc[i]=(double) year;
5510: moisdc[i]=(double) month;
5511: strcpy(line,stra);
5512:
5513: cutv(stra, strb,line,' ');
1.169 brouard 5514: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5515: }
1.169 brouard 5516: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5517: month=99;
5518: year=9999;
5519: }else{
1.141 brouard 5520: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);
5521: 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 5522: return 1;
5523: }
5524: if (year==9999) {
1.141 brouard 5525: 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);
5526: 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 5527: return 1;
1.126 brouard 5528:
1.136 brouard 5529: }
5530: annais[i]=(double)(year);
5531: moisnais[i]=(double)(month);
5532: strcpy(line,stra);
5533:
5534: cutv(stra, strb,line,' ');
5535: errno=0;
5536: dval=strtod(strb,&endptr);
5537: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5538: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5539: 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 5540: fflush(ficlog);
5541: return 1;
5542: }
5543: weight[i]=dval;
5544: strcpy(line,stra);
5545:
5546: for (j=ncovcol;j>=1;j--){
5547: cutv(stra, strb,line,' ');
5548: if(strb[0]=='.') { /* Missing status */
5549: lval=-1;
5550: }else{
5551: errno=0;
5552: lval=strtol(strb,&endptr,10);
5553: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5554: 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);
5555: 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 5556: return 1;
5557: }
5558: }
5559: if(lval <-1 || lval >1){
1.141 brouard 5560: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5561: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5562: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5563: For example, for multinomial values like 1, 2 and 3,\n \
5564: build V1=0 V2=0 for the reference value (1),\n \
5565: V1=1 V2=0 for (2) \n \
5566: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5567: output of IMaCh is often meaningless.\n \
5568: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5569: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5570: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5571: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5572: For example, for multinomial values like 1, 2 and 3,\n \
5573: build V1=0 V2=0 for the reference value (1),\n \
5574: V1=1 V2=0 for (2) \n \
5575: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5576: output of IMaCh is often meaningless.\n \
5577: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5578: return 1;
5579: }
5580: covar[j][i]=(double)(lval);
5581: strcpy(line,stra);
5582: }
5583: lstra=strlen(stra);
5584:
5585: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5586: stratrunc = &(stra[lstra-9]);
5587: num[i]=atol(stratrunc);
5588: }
5589: else
5590: num[i]=atol(stra);
5591: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5592: 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;}*/
5593:
5594: i=i+1;
5595: } /* End loop reading data */
1.126 brouard 5596:
1.136 brouard 5597: *imax=i-1; /* Number of individuals */
5598: fclose(fic);
5599:
5600: return (0);
1.164 brouard 5601: /* endread: */
1.136 brouard 5602: printf("Exiting readdata: ");
5603: fclose(fic);
5604: return (1);
1.126 brouard 5605:
5606:
5607:
1.136 brouard 5608: }
1.145 brouard 5609: void removespace(char *str) {
5610: char *p1 = str, *p2 = str;
5611: do
5612: while (*p2 == ' ')
5613: p2++;
1.169 brouard 5614: while (*p1++ == *p2++);
1.145 brouard 5615: }
5616:
5617: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5618: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5619: * - nagesqr = 1 if age*age in the model, otherwise 0.
5620: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5621: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5622: * - cptcovage number of covariates with age*products =2
5623: * - cptcovs number of simple covariates
5624: * - 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
5625: * which is a new column after the 9 (ncovcol) variables.
5626: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5627: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5628: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5629: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5630: */
1.136 brouard 5631: {
1.145 brouard 5632: int i, j, k, ks;
1.164 brouard 5633: int j1, k1, k2;
1.136 brouard 5634: char modelsav[80];
1.145 brouard 5635: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 5636: char *strpt;
1.136 brouard 5637:
1.145 brouard 5638: /*removespace(model);*/
1.136 brouard 5639: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5640: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 5641: if (strstr(model,"AGE") !=0){
1.192 brouard 5642: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
5643: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 5644: return 1;
5645: }
1.141 brouard 5646: if (strstr(model,"v") !=0){
5647: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5648: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5649: return 1;
5650: }
1.187 brouard 5651: strcpy(modelsav,model);
5652: if ((strpt=strstr(model,"age*age")) !=0){
5653: printf(" strpt=%s, model=%s\n",strpt, model);
5654: if(strpt != model){
5655: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5656: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5657: corresponding column of parameters.\n",model);
5658: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5659: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5660: corresponding column of parameters.\n",model); fflush(ficlog);
5661: return 1;
5662: }
5663:
5664: nagesqr=1;
5665: if (strstr(model,"+age*age") !=0)
5666: substrchaine(modelsav, model, "+age*age");
5667: else if (strstr(model,"age*age+") !=0)
5668: substrchaine(modelsav, model, "age*age+");
5669: else
5670: substrchaine(modelsav, model, "age*age");
5671: }else
5672: nagesqr=0;
5673: if (strlen(modelsav) >1){
5674: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5675: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5676: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5677: cptcovt= j+1; /* Number of total covariates in the model, not including
5678: * cst, age and age*age
5679: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5680: /* including age products which are counted in cptcovage.
5681: * but the covariates which are products must be treated
5682: * separately: ncovn=4- 2=2 (V1+V3). */
5683: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5684: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5685:
5686:
5687: /* Design
5688: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5689: * < ncovcol=8 >
5690: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5691: * k= 1 2 3 4 5 6 7 8
5692: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5693: * covar[k,i], value of kth covariate if not including age for individual i:
5694: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5695: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5696: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5697: * Tage[++cptcovage]=k
5698: * if products, new covar are created after ncovcol with k1
5699: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5700: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5701: * 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
5702: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5703: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5704: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5705: * < ncovcol=8 >
5706: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5707: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5708: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5709: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5710: * p Tprod[1]@2={ 6, 5}
5711: *p Tvard[1][1]@4= {7, 8, 5, 6}
5712: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5713: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5714: *How to reorganize?
5715: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5716: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5717: * {2, 1, 4, 8, 5, 6, 3, 7}
5718: * Struct []
5719: */
1.145 brouard 5720:
1.187 brouard 5721: /* This loop fills the array Tvar from the string 'model'.*/
5722: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5723: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5724: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5725: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5726: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5727: /* k=1 Tvar[1]=2 (from V2) */
5728: /* k=5 Tvar[5] */
5729: /* for (k=1; k<=cptcovn;k++) { */
5730: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5731: /* } */
5732: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
5733: /*
5734: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5735: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 5736: Tvar[k]=0;
1.187 brouard 5737: cptcovage=0;
5738: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5739: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5740: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5741: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5742: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5743: /*scanf("%d",i);*/
5744: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5745: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5746: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5747: /* covar is not filled and then is empty */
5748: cptcovprod--;
5749: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5750: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5751: cptcovage++; /* Sums the number of covariates which include age as a product */
5752: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5753: /*printf("stre=%s ", stre);*/
5754: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5755: cptcovprod--;
5756: cutl(stre,strb,strc,'V');
5757: Tvar[k]=atoi(stre);
5758: cptcovage++;
5759: Tage[cptcovage]=k;
5760: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5761: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5762: cptcovn++;
5763: cptcovprodnoage++;k1++;
5764: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5765: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5766: because this model-covariate is a construction we invent a new column
5767: ncovcol + k1
5768: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5769: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5770: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5771: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5772: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5773: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5774: k2=k2+2;
5775: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5776: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5777: for (i=1; i<=lastobs;i++){
5778: /* Computes the new covariate which is a product of
5779: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5780: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5781: }
5782: } /* End age is not in the model */
5783: } /* End if model includes a product */
5784: else { /* no more sum */
5785: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5786: /* scanf("%d",i);*/
5787: cutl(strd,strc,strb,'V');
5788: ks++; /**< Number of simple covariates */
1.145 brouard 5789: cptcovn++;
1.187 brouard 5790: Tvar[k]=atoi(strd);
5791: }
5792: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5793: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5794: scanf("%d",i);*/
5795: } /* end of loop + on total covariates */
5796: } /* end if strlen(modelsave == 0) age*age might exist */
5797: } /* end if strlen(model == 0) */
1.136 brouard 5798:
5799: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5800: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5801:
5802: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5803: printf("cptcovprod=%d ", cptcovprod);
5804: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5805:
5806: scanf("%d ",i);*/
5807:
5808:
1.137 brouard 5809: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5810: /*endread:*/
1.136 brouard 5811: printf("Exiting decodemodel: ");
5812: return (1);
5813: }
5814:
1.169 brouard 5815: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5816: {
5817: int i, m;
5818:
5819: for (i=1; i<=imx; i++) {
5820: for(m=2; (m<= maxwav); m++) {
5821: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5822: anint[m][i]=9999;
5823: s[m][i]=-1;
5824: }
5825: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5826: *nberr = *nberr + 1;
5827: 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);
5828: 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 5829: s[m][i]=-1;
5830: }
5831: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5832: (*nberr)++;
1.136 brouard 5833: 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]);
5834: 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]);
5835: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5836: }
5837: }
5838: }
5839:
5840: for (i=1; i<=imx; i++) {
5841: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5842: for(m=firstpass; (m<= lastpass); m++){
5843: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5844: if (s[m][i] >= nlstate+1) {
1.169 brouard 5845: if(agedc[i]>0){
5846: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5847: agev[m][i]=agedc[i];
5848: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5849: }else {
1.136 brouard 5850: if ((int)andc[i]!=9999){
5851: nbwarn++;
5852: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5853: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5854: agev[m][i]=-1;
5855: }
5856: }
1.169 brouard 5857: } /* agedc > 0 */
1.136 brouard 5858: }
5859: else if(s[m][i] !=9){ /* Standard case, age in fractional
5860: years but with the precision of a month */
5861: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5862: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5863: agev[m][i]=1;
5864: else if(agev[m][i] < *agemin){
5865: *agemin=agev[m][i];
5866: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5867: }
5868: else if(agev[m][i] >*agemax){
5869: *agemax=agev[m][i];
1.156 brouard 5870: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5871: }
5872: /*agev[m][i]=anint[m][i]-annais[i];*/
5873: /* agev[m][i] = age[i]+2*m;*/
5874: }
5875: else { /* =9 */
5876: agev[m][i]=1;
5877: s[m][i]=-1;
5878: }
5879: }
5880: else /*= 0 Unknown */
5881: agev[m][i]=1;
5882: }
5883:
5884: }
5885: for (i=1; i<=imx; i++) {
5886: for(m=firstpass; (m<=lastpass); m++){
5887: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5888: (*nberr)++;
1.136 brouard 5889: 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);
5890: 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);
5891: return 1;
5892: }
5893: }
5894: }
5895:
5896: /*for (i=1; i<=imx; i++){
5897: for (m=firstpass; (m<lastpass); m++){
5898: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5899: }
5900:
5901: }*/
5902:
5903:
1.139 brouard 5904: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5905: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5906:
5907: return (0);
1.164 brouard 5908: /* endread:*/
1.136 brouard 5909: printf("Exiting calandcheckages: ");
5910: return (1);
5911: }
5912:
1.172 brouard 5913: #if defined(_MSC_VER)
5914: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5915: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5916: //#include "stdafx.h"
5917: //#include <stdio.h>
5918: //#include <tchar.h>
5919: //#include <windows.h>
5920: //#include <iostream>
5921: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5922:
5923: LPFN_ISWOW64PROCESS fnIsWow64Process;
5924:
5925: BOOL IsWow64()
5926: {
5927: BOOL bIsWow64 = FALSE;
5928:
5929: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5930: // (HANDLE, PBOOL);
5931:
5932: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5933:
5934: HMODULE module = GetModuleHandle(_T("kernel32"));
5935: const char funcName[] = "IsWow64Process";
5936: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5937: GetProcAddress(module, funcName);
5938:
5939: if (NULL != fnIsWow64Process)
5940: {
5941: if (!fnIsWow64Process(GetCurrentProcess(),
5942: &bIsWow64))
5943: //throw std::exception("Unknown error");
5944: printf("Unknown error\n");
5945: }
5946: return bIsWow64 != FALSE;
5947: }
5948: #endif
1.177 brouard 5949:
1.191 brouard 5950: void syscompilerinfo(int logged)
1.167 brouard 5951: {
5952: /* #include "syscompilerinfo.h"*/
1.185 brouard 5953: /* command line Intel compiler 32bit windows, XP compatible:*/
5954: /* /GS /W3 /Gy
5955: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5956: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5957: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 5958: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5959: */
5960: /* 64 bits */
1.185 brouard 5961: /*
5962: /GS /W3 /Gy
5963: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5964: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5965: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5966: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5967: /* Optimization are useless and O3 is slower than O2 */
5968: /*
5969: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
5970: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
5971: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
5972: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
5973: */
1.186 brouard 5974: /* Link is */ /* /OUT:"visual studio
1.185 brouard 5975: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
5976: /PDB:"visual studio
5977: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
5978: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
5979: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
5980: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
5981: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
5982: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
5983: uiAccess='false'"
5984: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
5985: /NOLOGO /TLBID:1
5986: */
1.177 brouard 5987: #if defined __INTEL_COMPILER
1.178 brouard 5988: #if defined(__GNUC__)
5989: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5990: #endif
1.177 brouard 5991: #elif defined(__GNUC__)
1.179 brouard 5992: #ifndef __APPLE__
1.174 brouard 5993: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5994: #endif
1.177 brouard 5995: struct utsname sysInfo;
1.178 brouard 5996: int cross = CROSS;
5997: if (cross){
5998: printf("Cross-");
1.191 brouard 5999: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6000: }
1.174 brouard 6001: #endif
6002:
1.171 brouard 6003: #include <stdint.h>
1.178 brouard 6004:
1.191 brouard 6005: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6006: #if defined(__clang__)
1.191 brouard 6007: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6008: #endif
6009: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6010: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6011: #endif
6012: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6013: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6014: #endif
6015: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6016: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6017: #endif
6018: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6019: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6020: #endif
6021: #if defined(_MSC_VER)
1.191 brouard 6022: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6023: #endif
6024: #if defined(__PGI)
1.191 brouard 6025: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6026: #endif
6027: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6028: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6029: #endif
1.191 brouard 6030: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6031:
1.167 brouard 6032: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6033: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6034: // Windows (x64 and x86)
1.191 brouard 6035: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6036: #elif __unix__ // all unices, not all compilers
6037: // Unix
1.191 brouard 6038: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6039: #elif __linux__
6040: // linux
1.191 brouard 6041: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6042: #elif __APPLE__
1.174 brouard 6043: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6044: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6045: #endif
6046:
6047: /* __MINGW32__ */
6048: /* __CYGWIN__ */
6049: /* __MINGW64__ */
6050: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6051: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6052: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6053: /* _WIN64 // Defined for applications for Win64. */
6054: /* _M_X64 // Defined for compilations that target x64 processors. */
6055: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6056:
1.167 brouard 6057: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6058: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6059: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6060: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6061: #else
1.191 brouard 6062: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6063: #endif
6064:
1.169 brouard 6065: #if defined(__GNUC__)
6066: # if defined(__GNUC_PATCHLEVEL__)
6067: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6068: + __GNUC_MINOR__ * 100 \
6069: + __GNUC_PATCHLEVEL__)
6070: # else
6071: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6072: + __GNUC_MINOR__ * 100)
6073: # endif
1.174 brouard 6074: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6075: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6076:
6077: if (uname(&sysInfo) != -1) {
6078: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6079: 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 6080: }
6081: else
6082: perror("uname() error");
1.179 brouard 6083: //#ifndef __INTEL_COMPILER
6084: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6085: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6086: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6087: #endif
1.169 brouard 6088: #endif
1.172 brouard 6089:
6090: // void main()
6091: // {
1.169 brouard 6092: #if defined(_MSC_VER)
1.174 brouard 6093: if (IsWow64()){
1.191 brouard 6094: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6095: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6096: }
6097: else{
1.191 brouard 6098: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6099: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6100: }
1.172 brouard 6101: // printf("\nPress Enter to continue...");
6102: // getchar();
6103: // }
6104:
1.169 brouard 6105: #endif
6106:
1.167 brouard 6107:
6108: }
1.136 brouard 6109:
1.180 brouard 6110: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6111: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6112: int i, j, k, i1 ;
6113: double ftolpl = 1.e-10;
6114: double age, agebase, agelim;
6115:
6116: strcpy(filerespl,"pl");
6117: strcat(filerespl,fileres);
6118: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6119: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6120: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6121: }
6122: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6123: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6124: pstamp(ficrespl);
6125: fprintf(ficrespl,"# Period (stable) prevalence \n");
6126: fprintf(ficrespl,"#Age ");
6127: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6128: fprintf(ficrespl,"\n");
6129:
6130: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6131:
6132: agebase=ageminpar;
6133: agelim=agemaxpar;
6134:
6135: i1=pow(2,cptcoveff);
6136: if (cptcovn < 1){i1=1;}
6137:
6138: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6139: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6140: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6141: k=k+1;
6142: /* to clean */
6143: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
6144: fprintf(ficrespl,"\n#******");
6145: printf("\n#******");
6146: fprintf(ficlog,"\n#******");
6147: for(j=1;j<=cptcoveff;j++) {
6148: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6149: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6150: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6151: }
6152: fprintf(ficrespl,"******\n");
6153: printf("******\n");
6154: fprintf(ficlog,"******\n");
6155:
6156: fprintf(ficrespl,"#Age ");
6157: for(j=1;j<=cptcoveff;j++) {
6158: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6159: }
6160: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6161: fprintf(ficrespl,"\n");
6162:
6163: for (age=agebase; age<=agelim; age++){
6164: /* for (age=agebase; age<=agebase; age++){ */
6165: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6166: fprintf(ficrespl,"%.0f ",age );
6167: for(j=1;j<=cptcoveff;j++)
6168: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6169: for(i=1; i<=nlstate;i++)
6170: fprintf(ficrespl," %.5f", prlim[i][i]);
6171: fprintf(ficrespl,"\n");
6172: } /* Age */
6173: /* was end of cptcod */
6174: } /* cptcov */
1.184 brouard 6175: return 0;
1.180 brouard 6176: }
6177:
6178: int hPijx(double *p, int bage, int fage){
6179: /*------------- h Pij x at various ages ------------*/
6180:
6181: int stepsize;
6182: int agelim;
6183: int hstepm;
6184: int nhstepm;
6185: int h, i, i1, j, k;
6186:
6187: double agedeb;
6188: double ***p3mat;
6189:
6190: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6191: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6192: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6193: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6194: }
6195: printf("Computing pij: result on file '%s' \n", filerespij);
6196: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6197:
6198: stepsize=(int) (stepm+YEARM-1)/YEARM;
6199: /*if (stepm<=24) stepsize=2;*/
6200:
6201: agelim=AGESUP;
6202: hstepm=stepsize*YEARM; /* Every year of age */
6203: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6204:
6205: /* hstepm=1; aff par mois*/
6206: pstamp(ficrespij);
6207: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6208: i1= pow(2,cptcoveff);
1.183 brouard 6209: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6210: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6211: /* k=k+1; */
6212: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6213: fprintf(ficrespij,"\n#****** ");
6214: for(j=1;j<=cptcoveff;j++)
6215: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6216: fprintf(ficrespij,"******\n");
6217:
6218: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6219: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6220: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6221:
6222: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6223:
1.183 brouard 6224: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6225: oldm=oldms;savm=savms;
6226: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6227: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6228: for(i=1; i<=nlstate;i++)
6229: for(j=1; j<=nlstate+ndeath;j++)
6230: fprintf(ficrespij," %1d-%1d",i,j);
6231: fprintf(ficrespij,"\n");
6232: for (h=0; h<=nhstepm; h++){
6233: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6234: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6235: for(i=1; i<=nlstate;i++)
6236: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6237: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6238: fprintf(ficrespij,"\n");
6239: }
1.183 brouard 6240: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6241: fprintf(ficrespij,"\n");
6242: }
1.180 brouard 6243: /*}*/
6244: }
1.184 brouard 6245: return 0;
1.180 brouard 6246: }
6247:
6248:
1.136 brouard 6249: /***********************************************/
6250: /**************** Main Program *****************/
6251: /***********************************************/
6252:
6253: int main(int argc, char *argv[])
6254: {
6255: #ifdef GSL
6256: const gsl_multimin_fminimizer_type *T;
6257: size_t iteri = 0, it;
6258: int rval = GSL_CONTINUE;
6259: int status = GSL_SUCCESS;
6260: double ssval;
6261: #endif
6262: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6263: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6264:
6265: int jj, ll, li, lj, lk;
1.136 brouard 6266: int numlinepar=0; /* Current linenumber of parameter file */
6267: int itimes;
6268: int NDIM=2;
6269: int vpopbased=0;
6270:
1.164 brouard 6271: char ca[32], cb[32];
1.136 brouard 6272: /* FILE *fichtm; *//* Html File */
6273: /* FILE *ficgp;*/ /*Gnuplot File */
6274: struct stat info;
1.191 brouard 6275: double agedeb=0.;
1.194 ! brouard 6276:
! 6277: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6278:
1.165 brouard 6279: double fret;
1.191 brouard 6280: double dum=0.; /* Dummy variable */
1.136 brouard 6281: double ***p3mat;
6282: double ***mobaverage;
1.164 brouard 6283:
6284: char line[MAXLINE];
1.136 brouard 6285: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
6286: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6287: char *tok, *val; /* pathtot */
1.136 brouard 6288: int firstobs=1, lastobs=10;
1.164 brouard 6289: int c, h , cpt;
1.191 brouard 6290: int jl=0;
6291: int i1, j1, jk, stepsize=0;
1.194 ! brouard 6292: int count=0;
! 6293:
1.164 brouard 6294: int *tab;
1.136 brouard 6295: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6296: int mobilav=0,popforecast=0;
1.191 brouard 6297: int hstepm=0, nhstepm=0;
1.136 brouard 6298: int agemortsup;
6299: float sumlpop=0.;
6300: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6301: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6302:
1.191 brouard 6303: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6304: double ftolpl=FTOL;
6305: double **prlim;
6306: double ***param; /* Matrix of parameters */
6307: double *p;
6308: double **matcov; /* Matrix of covariance */
6309: double ***delti3; /* Scale */
6310: double *delti; /* Scale */
6311: double ***eij, ***vareij;
6312: double **varpl; /* Variances of prevalence limits by age */
6313: double *epj, vepp;
1.164 brouard 6314:
1.136 brouard 6315: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6316: double **ximort;
1.145 brouard 6317: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6318: int *dcwave;
6319:
1.164 brouard 6320: char z[1]="c";
1.136 brouard 6321:
6322: /*char *strt;*/
6323: char strtend[80];
1.126 brouard 6324:
1.164 brouard 6325:
1.126 brouard 6326: /* setlocale (LC_ALL, ""); */
6327: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6328: /* textdomain (PACKAGE); */
6329: /* setlocale (LC_CTYPE, ""); */
6330: /* setlocale (LC_MESSAGES, ""); */
6331:
6332: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6333: rstart_time = time(NULL);
6334: /* (void) gettimeofday(&start_time,&tzp);*/
6335: start_time = *localtime(&rstart_time);
1.126 brouard 6336: curr_time=start_time;
1.157 brouard 6337: /*tml = *localtime(&start_time.tm_sec);*/
6338: /* strcpy(strstart,asctime(&tml)); */
6339: strcpy(strstart,asctime(&start_time));
1.126 brouard 6340:
6341: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6342: /* tp.tm_sec = tp.tm_sec +86400; */
6343: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6344: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6345: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6346: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6347: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6348: /* strt=asctime(&tmg); */
6349: /* printf("Time(after) =%s",strstart); */
6350: /* (void) time (&time_value);
6351: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6352: * tm = *localtime(&time_value);
6353: * strstart=asctime(&tm);
6354: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6355: */
6356:
6357: nberr=0; /* Number of errors and warnings */
6358: nbwarn=0;
1.184 brouard 6359: #ifdef WIN32
6360: _getcwd(pathcd, size);
6361: #else
1.126 brouard 6362: getcwd(pathcd, size);
1.184 brouard 6363: #endif
1.191 brouard 6364: syscompilerinfo(0);
1.126 brouard 6365: printf("\n%s\n%s",version,fullversion);
6366: if(argc <=1){
6367: printf("\nEnter the parameter file name: ");
6368: fgets(pathr,FILENAMELENGTH,stdin);
6369: i=strlen(pathr);
6370: if(pathr[i-1]=='\n')
6371: pathr[i-1]='\0';
1.156 brouard 6372: i=strlen(pathr);
6373: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6374: pathr[i-1]='\0';
1.126 brouard 6375: for (tok = pathr; tok != NULL; ){
6376: printf("Pathr |%s|\n",pathr);
6377: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6378: printf("val= |%s| pathr=%s\n",val,pathr);
6379: strcpy (pathtot, val);
6380: if(pathr[0] == '\0') break; /* Dirty */
6381: }
6382: }
6383: else{
6384: strcpy(pathtot,argv[1]);
6385: }
6386: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6387: /*cygwin_split_path(pathtot,path,optionfile);
6388: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6389: /* cutv(path,optionfile,pathtot,'\\');*/
6390:
6391: /* Split argv[0], imach program to get pathimach */
6392: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6393: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6394: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6395: /* strcpy(pathimach,argv[0]); */
6396: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6397: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6398: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6399: #ifdef WIN32
6400: _chdir(path); /* Can be a relative path */
6401: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6402: #else
1.126 brouard 6403: chdir(path); /* Can be a relative path */
1.184 brouard 6404: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6405: #endif
6406: printf("Current directory %s!\n",pathcd);
1.126 brouard 6407: strcpy(command,"mkdir ");
6408: strcat(command,optionfilefiname);
6409: if((outcmd=system(command)) != 0){
1.169 brouard 6410: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6411: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6412: /* fclose(ficlog); */
6413: /* exit(1); */
6414: }
6415: /* if((imk=mkdir(optionfilefiname))<0){ */
6416: /* perror("mkdir"); */
6417: /* } */
6418:
6419: /*-------- arguments in the command line --------*/
6420:
1.186 brouard 6421: /* Main Log file */
1.126 brouard 6422: strcat(filelog, optionfilefiname);
6423: strcat(filelog,".log"); /* */
6424: if((ficlog=fopen(filelog,"w"))==NULL) {
6425: printf("Problem with logfile %s\n",filelog);
6426: goto end;
6427: }
6428: fprintf(ficlog,"Log filename:%s\n",filelog);
6429: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6430: fprintf(ficlog,"\nEnter the parameter file name: \n");
6431: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6432: path=%s \n\
6433: optionfile=%s\n\
6434: optionfilext=%s\n\
1.156 brouard 6435: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6436:
1.191 brouard 6437: syscompilerinfo(0);
1.167 brouard 6438:
1.126 brouard 6439: printf("Local time (at start):%s",strstart);
6440: fprintf(ficlog,"Local time (at start): %s",strstart);
6441: fflush(ficlog);
6442: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6443: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6444:
6445: /* */
6446: strcpy(fileres,"r");
6447: strcat(fileres, optionfilefiname);
6448: strcat(fileres,".txt"); /* Other files have txt extension */
6449:
1.186 brouard 6450: /* Main ---------arguments file --------*/
1.126 brouard 6451:
6452: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6453: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6454: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6455: fflush(ficlog);
1.149 brouard 6456: /* goto end; */
6457: exit(70);
1.126 brouard 6458: }
6459:
6460:
6461:
6462: strcpy(filereso,"o");
6463: strcat(filereso,fileres);
6464: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6465: printf("Problem with Output resultfile: %s\n", filereso);
6466: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6467: fflush(ficlog);
6468: goto end;
6469: }
6470:
6471: /* Reads comments: lines beginning with '#' */
6472: numlinepar=0;
6473: while((c=getc(ficpar))=='#' && c!= EOF){
6474: ungetc(c,ficpar);
6475: fgets(line, MAXLINE, ficpar);
6476: numlinepar++;
1.141 brouard 6477: fputs(line,stdout);
1.126 brouard 6478: fputs(line,ficparo);
6479: fputs(line,ficlog);
6480: }
6481: ungetc(c,ficpar);
6482:
1.187 brouard 6483: 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.194 ! brouard 6484: numlinepar=numlinepar+3; /* In general */
1.187 brouard 6485: 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);
6486: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6487: model[strlen(model)-1]='\0';
6488: 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);
6489: 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 6490: fflush(ficlog);
1.190 brouard 6491: /* if(model[0]=='#'|| model[0]== '\0'){ */
6492: if(model[0]=='#'){
1.187 brouard 6493: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6494: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6495: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6496: if(mle != -1){
6497: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6498: exit(1);
6499: }
6500: }
1.126 brouard 6501: while((c=getc(ficpar))=='#' && c!= EOF){
6502: ungetc(c,ficpar);
6503: fgets(line, MAXLINE, ficpar);
6504: numlinepar++;
1.141 brouard 6505: fputs(line, stdout);
6506: //puts(line);
1.126 brouard 6507: fputs(line,ficparo);
6508: fputs(line,ficlog);
6509: }
6510: ungetc(c,ficpar);
6511:
6512:
1.145 brouard 6513: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6514: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6515: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6516: v1+v2*age+v2*v3 makes cptcovn = 3
6517: */
6518: if (strlen(model)>1)
1.187 brouard 6519: 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 6520: else
1.187 brouard 6521: ncovmodel=2; /* Constant and age */
1.133 brouard 6522: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6523: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6524: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6525: 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);
6526: 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);
6527: fflush(stdout);
6528: fclose (ficlog);
6529: goto end;
6530: }
1.126 brouard 6531: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6532: delti=delti3[1][1];
6533: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6534: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6535: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 6536: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6537: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6538: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6539: fclose (ficparo);
6540: fclose (ficlog);
6541: goto end;
6542: exit(0);
6543: }
1.186 brouard 6544: else if(mle==-3) { /* Main Wizard */
1.126 brouard 6545: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 6546: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6547: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6548: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6549: matcov=matrix(1,npar,1,npar);
6550: }
6551: else{
1.145 brouard 6552: /* Read guessed parameters */
1.126 brouard 6553: /* Reads comments: lines beginning with '#' */
6554: while((c=getc(ficpar))=='#' && c!= EOF){
6555: ungetc(c,ficpar);
6556: fgets(line, MAXLINE, ficpar);
6557: numlinepar++;
1.141 brouard 6558: fputs(line,stdout);
1.126 brouard 6559: fputs(line,ficparo);
6560: fputs(line,ficlog);
6561: }
6562: ungetc(c,ficpar);
6563:
6564: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6565: for(i=1; i <=nlstate; i++){
6566: j=0;
6567: for(jj=1; jj <=nlstate+ndeath; jj++){
6568: if(jj==i) continue;
6569: j++;
6570: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 6571: if ((i1 != i) || (j1 != jj)){
1.126 brouard 6572: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6573: It might be a problem of design; if ncovcol and the model are correct\n \
6574: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6575: exit(1);
6576: }
6577: fprintf(ficparo,"%1d%1d",i1,j1);
6578: if(mle==1)
1.193 brouard 6579: printf("%1d%1d",i,jj);
6580: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 6581: for(k=1; k<=ncovmodel;k++){
6582: fscanf(ficpar," %lf",¶m[i][j][k]);
6583: if(mle==1){
6584: printf(" %lf",param[i][j][k]);
6585: fprintf(ficlog," %lf",param[i][j][k]);
6586: }
6587: else
6588: fprintf(ficlog," %lf",param[i][j][k]);
6589: fprintf(ficparo," %lf",param[i][j][k]);
6590: }
6591: fscanf(ficpar,"\n");
6592: numlinepar++;
6593: if(mle==1)
6594: printf("\n");
6595: fprintf(ficlog,"\n");
6596: fprintf(ficparo,"\n");
6597: }
6598: }
6599: fflush(ficlog);
6600:
1.145 brouard 6601: /* Reads scales values */
1.126 brouard 6602: p=param[1][1];
6603:
6604: /* Reads comments: lines beginning with '#' */
6605: while((c=getc(ficpar))=='#' && c!= EOF){
6606: ungetc(c,ficpar);
6607: fgets(line, MAXLINE, ficpar);
6608: numlinepar++;
1.141 brouard 6609: fputs(line,stdout);
1.126 brouard 6610: fputs(line,ficparo);
6611: fputs(line,ficlog);
6612: }
6613: ungetc(c,ficpar);
6614:
6615: for(i=1; i <=nlstate; i++){
6616: for(j=1; j <=nlstate+ndeath-1; j++){
6617: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6618: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6619: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6620: exit(1);
6621: }
6622: printf("%1d%1d",i,j);
6623: fprintf(ficparo,"%1d%1d",i1,j1);
6624: fprintf(ficlog,"%1d%1d",i1,j1);
6625: for(k=1; k<=ncovmodel;k++){
6626: fscanf(ficpar,"%le",&delti3[i][j][k]);
6627: printf(" %le",delti3[i][j][k]);
6628: fprintf(ficparo," %le",delti3[i][j][k]);
6629: fprintf(ficlog," %le",delti3[i][j][k]);
6630: }
6631: fscanf(ficpar,"\n");
6632: numlinepar++;
6633: printf("\n");
6634: fprintf(ficparo,"\n");
6635: fprintf(ficlog,"\n");
6636: }
6637: }
6638: fflush(ficlog);
6639:
1.145 brouard 6640: /* Reads covariance matrix */
1.126 brouard 6641: delti=delti3[1][1];
6642:
6643:
6644: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6645:
6646: /* Reads comments: lines beginning with '#' */
6647: while((c=getc(ficpar))=='#' && c!= EOF){
6648: ungetc(c,ficpar);
6649: fgets(line, MAXLINE, ficpar);
6650: numlinepar++;
1.141 brouard 6651: fputs(line,stdout);
1.126 brouard 6652: fputs(line,ficparo);
6653: fputs(line,ficlog);
6654: }
6655: ungetc(c,ficpar);
6656:
6657: matcov=matrix(1,npar,1,npar);
1.131 brouard 6658: for(i=1; i <=npar; i++)
6659: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6660:
1.194 ! brouard 6661: /* Scans npar lines */
1.126 brouard 6662: for(i=1; i <=npar; i++){
1.194 ! brouard 6663: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
! 6664: if(count != 3){
! 6665: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
! 6666: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
! 6667: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
! 6668: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
! 6669: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
! 6670: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
! 6671: exit(1);
! 6672: }else
1.126 brouard 6673: if(mle==1)
1.194 ! brouard 6674: printf("%1d%1d%1d",i1,j1,jk);
! 6675: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
! 6676: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 6677: for(j=1; j <=i; j++){
6678: fscanf(ficpar," %le",&matcov[i][j]);
6679: if(mle==1){
6680: printf(" %.5le",matcov[i][j]);
6681: }
6682: fprintf(ficlog," %.5le",matcov[i][j]);
6683: fprintf(ficparo," %.5le",matcov[i][j]);
6684: }
6685: fscanf(ficpar,"\n");
6686: numlinepar++;
6687: if(mle==1)
6688: printf("\n");
6689: fprintf(ficlog,"\n");
6690: fprintf(ficparo,"\n");
6691: }
1.194 ! brouard 6692: /* End of read covariance matrix npar lines */
1.126 brouard 6693: for(i=1; i <=npar; i++)
6694: for(j=i+1;j<=npar;j++)
6695: matcov[i][j]=matcov[j][i];
6696:
6697: if(mle==1)
6698: printf("\n");
6699: fprintf(ficlog,"\n");
6700:
6701: fflush(ficlog);
6702:
6703: /*-------- Rewriting parameter file ----------*/
6704: strcpy(rfileres,"r"); /* "Rparameterfile */
6705: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6706: strcat(rfileres,"."); /* */
6707: strcat(rfileres,optionfilext); /* Other files have txt extension */
6708: if((ficres =fopen(rfileres,"w"))==NULL) {
6709: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6710: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6711: }
6712: fprintf(ficres,"#%s\n",version);
6713: } /* End of mle != -3 */
6714:
1.186 brouard 6715: /* Main data
6716: */
1.126 brouard 6717: n= lastobs;
6718: num=lvector(1,n);
6719: moisnais=vector(1,n);
6720: annais=vector(1,n);
6721: moisdc=vector(1,n);
6722: andc=vector(1,n);
6723: agedc=vector(1,n);
6724: cod=ivector(1,n);
6725: weight=vector(1,n);
6726: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6727: mint=matrix(1,maxwav,1,n);
6728: anint=matrix(1,maxwav,1,n);
1.131 brouard 6729: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6730: tab=ivector(1,NCOVMAX);
1.144 brouard 6731: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 6732: 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 6733:
1.136 brouard 6734: /* Reads data from file datafile */
6735: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6736: goto end;
6737:
6738: /* Calculation of the number of parameters from char model */
1.137 brouard 6739: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6740: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6741: k=3 V4 Tvar[k=3]= 4 (from V4)
6742: k=2 V1 Tvar[k=2]= 1 (from V1)
6743: k=1 Tvar[1]=2 (from V2)
6744: */
6745: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6746: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6747: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6748: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6749: */
6750: /* For model-covariate k tells which data-covariate to use but
6751: because this model-covariate is a construction we invent a new column
6752: ncovcol + k1
6753: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6754: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6755: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6756: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6757: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6758: */
1.145 brouard 6759: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6760: 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 6761: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6762: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6763: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6764: 4 covariates (3 plus signs)
6765: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6766: */
1.136 brouard 6767:
1.186 brouard 6768: /* Main decodemodel */
6769:
1.187 brouard 6770:
1.136 brouard 6771: if(decodemodel(model, lastobs) == 1)
6772: goto end;
6773:
1.137 brouard 6774: if((double)(lastobs-imx)/(double)imx > 1.10){
6775: nbwarn++;
6776: 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);
6777: 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);
6778: }
1.136 brouard 6779: /* if(mle==1){*/
1.137 brouard 6780: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6781: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6782: }
6783:
6784: /*-calculation of age at interview from date of interview and age at death -*/
6785: agev=matrix(1,maxwav,1,imx);
6786:
6787: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6788: goto end;
6789:
1.126 brouard 6790:
1.136 brouard 6791: agegomp=(int)agemin;
6792: free_vector(moisnais,1,n);
6793: free_vector(annais,1,n);
1.126 brouard 6794: /* free_matrix(mint,1,maxwav,1,n);
6795: free_matrix(anint,1,maxwav,1,n);*/
6796: free_vector(moisdc,1,n);
6797: free_vector(andc,1,n);
1.145 brouard 6798: /* */
6799:
1.126 brouard 6800: wav=ivector(1,imx);
6801: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6802: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6803: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6804:
6805: /* Concatenates waves */
6806: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6807: /* */
6808:
1.126 brouard 6809: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6810:
6811: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6812: ncodemax[1]=1;
1.145 brouard 6813: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 6814: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 6815: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 6816: /* Nbcode gives the value of the lth modality of jth covariate, in
6817: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6818: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 6819:
6820: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6821: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186 brouard 6822: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 6823: h=0;
6824:
6825:
6826: /*if (cptcovn > 0) */
1.126 brouard 6827:
1.145 brouard 6828:
1.126 brouard 6829: m=pow(2,cptcoveff);
6830:
1.131 brouard 6831: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6832: 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 */
6833: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6834: 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 6835: h++;
1.141 brouard 6836: if (h>m)
1.136 brouard 6837: h=1;
1.144 brouard 6838: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 6839: * For k=4 covariates, h goes from 1 to 2**k
6840: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6841: * h\k 1 2 3 4
1.143 brouard 6842: *______________________________
6843: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6844: * 2 2 1 1 1
6845: * 3 i=2 1 2 1 1
6846: * 4 2 2 1 1
6847: * 5 i=3 1 i=2 1 2 1
6848: * 6 2 1 2 1
6849: * 7 i=4 1 2 2 1
6850: * 8 2 2 2 1
6851: * 9 i=5 1 i=3 1 i=2 1 1
6852: * 10 2 1 1 1
6853: * 11 i=6 1 2 1 1
6854: * 12 2 2 1 1
6855: * 13 i=7 1 i=4 1 2 1
6856: * 14 2 1 2 1
6857: * 15 i=8 1 2 2 1
6858: * 16 2 2 2 1
6859: */
1.141 brouard 6860: codtab[h][k]=j;
1.186 brouard 6861: /* codtab[12][3]=1; */
1.145 brouard 6862: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6863: 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 6864: }
6865: }
6866: }
6867: }
6868: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6869: codtab[1][2]=1;codtab[2][2]=2; */
6870: /* for(i=1; i <=m ;i++){
6871: for(k=1; k <=cptcovn; k++){
1.131 brouard 6872: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6873: }
6874: printf("\n");
6875: }
6876: scanf("%d",i);*/
1.145 brouard 6877:
6878: free_ivector(Ndum,-1,NCOVMAX);
6879:
6880:
1.126 brouard 6881:
1.186 brouard 6882: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 6883: strcpy(optionfilegnuplot,optionfilefiname);
6884: if(mle==-3)
6885: strcat(optionfilegnuplot,"-mort");
6886: strcat(optionfilegnuplot,".gp");
6887:
6888: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6889: printf("Problem with file %s",optionfilegnuplot);
6890: }
6891: else{
6892: fprintf(ficgp,"\n# %s\n", version);
6893: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6894: //fprintf(ficgp,"set missing 'NaNq'\n");
6895: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6896: }
6897: /* fclose(ficgp);*/
1.186 brouard 6898:
6899:
6900: /* Initialisation of --------- index.htm --------*/
1.126 brouard 6901:
6902: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6903: if(mle==-3)
6904: strcat(optionfilehtm,"-mort");
6905: strcat(optionfilehtm,".htm");
6906: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6907: printf("Problem with %s \n",optionfilehtm);
6908: exit(0);
1.126 brouard 6909: }
6910:
6911: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6912: strcat(optionfilehtmcov,"-cov.htm");
6913: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6914: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6915: }
6916: else{
6917: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6918: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6919: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6920: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6921: }
6922:
6923: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6924: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6925: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6926: \n\
6927: <hr size=\"2\" color=\"#EC5E5E\">\
6928: <ul><li><h4>Parameter files</h4>\n\
6929: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6930: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6931: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6932: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6933: - Date and time at start: %s</ul>\n",\
6934: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6935: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6936: fileres,fileres,\
6937: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6938: fflush(fichtm);
6939:
6940: strcpy(pathr,path);
6941: strcat(pathr,optionfilefiname);
1.184 brouard 6942: #ifdef WIN32
6943: _chdir(optionfilefiname); /* Move to directory named optionfile */
6944: #else
1.126 brouard 6945: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 6946: #endif
6947:
1.126 brouard 6948:
6949: /* Calculates basic frequencies. Computes observed prevalence at single age
6950: and prints on file fileres'p'. */
6951: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6952:
6953: fprintf(fichtm,"\n");
6954: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6955: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6956: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6957: imx,agemin,agemax,jmin,jmax,jmean);
6958: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6959: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6960: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6961: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6962: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6963:
6964:
6965: /* For Powell, parameters are in a vector p[] starting at p[1]
6966: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6967: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6968:
6969: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 6970: /* For mortality only */
1.126 brouard 6971: if (mle==-3){
1.136 brouard 6972: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 6973: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6974: cens=ivector(1,n);
6975: ageexmed=vector(1,n);
6976: agecens=vector(1,n);
6977: dcwave=ivector(1,n);
6978:
6979: for (i=1; i<=imx; i++){
6980: dcwave[i]=-1;
6981: for (m=firstpass; m<=lastpass; m++)
6982: if (s[m][i]>nlstate) {
6983: dcwave[i]=m;
6984: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6985: break;
6986: }
6987: }
6988:
6989: for (i=1; i<=imx; i++) {
6990: if (wav[i]>0){
6991: ageexmed[i]=agev[mw[1][i]][i];
6992: j=wav[i];
6993: agecens[i]=1.;
6994:
6995: if (ageexmed[i]> 1 && wav[i] > 0){
6996: agecens[i]=agev[mw[j][i]][i];
6997: cens[i]= 1;
6998: }else if (ageexmed[i]< 1)
6999: cens[i]= -1;
7000: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7001: cens[i]=0 ;
7002: }
7003: else cens[i]=-1;
7004: }
7005:
7006: for (i=1;i<=NDIM;i++) {
7007: for (j=1;j<=NDIM;j++)
7008: ximort[i][j]=(i == j ? 1.0 : 0.0);
7009: }
7010:
1.145 brouard 7011: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7012: /*printf("%lf %lf", p[1], p[2]);*/
7013:
7014:
1.136 brouard 7015: #ifdef GSL
7016: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7017: #else
1.126 brouard 7018: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7019: #endif
1.126 brouard 7020: strcpy(filerespow,"pow-mort");
7021: strcat(filerespow,fileres);
7022: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7023: printf("Problem with resultfile: %s\n", filerespow);
7024: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7025: }
1.136 brouard 7026: #ifdef GSL
7027: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7028: #else
1.126 brouard 7029: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7030: #endif
1.126 brouard 7031: /* for (i=1;i<=nlstate;i++)
7032: for(j=1;j<=nlstate+ndeath;j++)
7033: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7034: */
7035: fprintf(ficrespow,"\n");
1.136 brouard 7036: #ifdef GSL
7037: /* gsl starts here */
7038: T = gsl_multimin_fminimizer_nmsimplex;
7039: gsl_multimin_fminimizer *sfm = NULL;
7040: gsl_vector *ss, *x;
7041: gsl_multimin_function minex_func;
7042:
7043: /* Initial vertex size vector */
7044: ss = gsl_vector_alloc (NDIM);
7045:
7046: if (ss == NULL){
7047: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7048: }
7049: /* Set all step sizes to 1 */
7050: gsl_vector_set_all (ss, 0.001);
7051:
7052: /* Starting point */
1.126 brouard 7053:
1.136 brouard 7054: x = gsl_vector_alloc (NDIM);
7055:
7056: if (x == NULL){
7057: gsl_vector_free(ss);
7058: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7059: }
7060:
7061: /* Initialize method and iterate */
7062: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7063: /* gsl_vector_set(x, 0, 0.0268); */
7064: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7065: gsl_vector_set(x, 0, p[1]);
7066: gsl_vector_set(x, 1, p[2]);
7067:
7068: minex_func.f = &gompertz_f;
7069: minex_func.n = NDIM;
7070: minex_func.params = (void *)&p; /* ??? */
7071:
7072: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7073: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7074:
7075: printf("Iterations beginning .....\n\n");
7076: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7077:
7078: iteri=0;
7079: while (rval == GSL_CONTINUE){
7080: iteri++;
7081: status = gsl_multimin_fminimizer_iterate(sfm);
7082:
7083: if (status) printf("error: %s\n", gsl_strerror (status));
7084: fflush(0);
7085:
7086: if (status)
7087: break;
7088:
7089: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7090: ssval = gsl_multimin_fminimizer_size (sfm);
7091:
7092: if (rval == GSL_SUCCESS)
7093: printf ("converged to a local maximum at\n");
7094:
7095: printf("%5d ", iteri);
7096: for (it = 0; it < NDIM; it++){
7097: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7098: }
7099: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7100: }
7101:
7102: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7103:
7104: gsl_vector_free(x); /* initial values */
7105: gsl_vector_free(ss); /* inital step size */
7106: for (it=0; it<NDIM; it++){
7107: p[it+1]=gsl_vector_get(sfm->x,it);
7108: fprintf(ficrespow," %.12lf", p[it]);
7109: }
7110: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7111: #endif
7112: #ifdef POWELL
7113: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7114: #endif
1.126 brouard 7115: fclose(ficrespow);
7116:
7117: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7118:
7119: for(i=1; i <=NDIM; i++)
7120: for(j=i+1;j<=NDIM;j++)
7121: matcov[i][j]=matcov[j][i];
7122:
7123: printf("\nCovariance matrix\n ");
7124: for(i=1; i <=NDIM; i++) {
7125: for(j=1;j<=NDIM;j++){
7126: printf("%f ",matcov[i][j]);
7127: }
7128: printf("\n ");
7129: }
7130:
7131: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7132: for (i=1;i<=NDIM;i++) {
1.126 brouard 7133: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7134: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7135: }
1.126 brouard 7136: lsurv=vector(1,AGESUP);
7137: lpop=vector(1,AGESUP);
7138: tpop=vector(1,AGESUP);
7139: lsurv[agegomp]=100000;
7140:
7141: for (k=agegomp;k<=AGESUP;k++) {
7142: agemortsup=k;
7143: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7144: }
7145:
7146: for (k=agegomp;k<agemortsup;k++)
7147: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7148:
7149: for (k=agegomp;k<agemortsup;k++){
7150: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7151: sumlpop=sumlpop+lpop[k];
7152: }
7153:
7154: tpop[agegomp]=sumlpop;
7155: for (k=agegomp;k<(agemortsup-3);k++){
7156: /* tpop[k+1]=2;*/
7157: tpop[k+1]=tpop[k]-lpop[k];
7158: }
7159:
7160:
7161: printf("\nAge lx qx dx Lx Tx e(x)\n");
7162: for (k=agegomp;k<(agemortsup-2);k++)
7163: 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]);
7164:
7165:
7166: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 ! brouard 7167: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
! 7168: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
! 7169: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
! 7170: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
! 7171: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
! 7172: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
! 7173: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
! 7174: }else
! 7175: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7176: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7177: stepm, weightopt,\
7178: model,imx,p,matcov,agemortsup);
7179:
7180: free_vector(lsurv,1,AGESUP);
7181: free_vector(lpop,1,AGESUP);
7182: free_vector(tpop,1,AGESUP);
1.136 brouard 7183: #ifdef GSL
7184: free_ivector(cens,1,n);
7185: free_vector(agecens,1,n);
7186: free_ivector(dcwave,1,n);
7187: free_matrix(ximort,1,NDIM,1,NDIM);
7188: #endif
1.186 brouard 7189: } /* Endof if mle==-3 mortality only */
7190: /* Standard maximisation */
1.126 brouard 7191: else{ /* For mle >=1 */
1.132 brouard 7192: globpr=0;/* debug */
1.186 brouard 7193: /* Computes likelihood for initial parameters */
1.132 brouard 7194: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7195: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7196: for (k=1; k<=npar;k++)
7197: printf(" %d %8.5f",k,p[k]);
7198: printf("\n");
1.186 brouard 7199: globpr=1; /* again, to print the contributions */
1.126 brouard 7200: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7201: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7202: for (k=1; k<=npar;k++)
7203: printf(" %d %8.5f",k,p[k]);
7204: printf("\n");
1.186 brouard 7205: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126 brouard 7206: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7207: }
7208:
7209: /*--------- results files --------------*/
1.192 brouard 7210: 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 7211:
7212:
7213: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7214: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7215: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7216: for(i=1,jk=1; i <=nlstate; i++){
7217: for(k=1; k <=(nlstate+ndeath); k++){
7218: if (k != i) {
7219: printf("%d%d ",i,k);
7220: fprintf(ficlog,"%d%d ",i,k);
7221: fprintf(ficres,"%1d%1d ",i,k);
7222: for(j=1; j <=ncovmodel; j++){
1.190 brouard 7223: printf("%12.7f ",p[jk]);
7224: fprintf(ficlog,"%12.7f ",p[jk]);
7225: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 7226: jk++;
7227: }
7228: printf("\n");
7229: fprintf(ficlog,"\n");
7230: fprintf(ficres,"\n");
7231: }
7232: }
7233: }
7234: if(mle!=0){
7235: /* Computing hessian and covariance matrix */
7236: ftolhess=ftol; /* Usually correct */
7237: hesscov(matcov, p, npar, delti, ftolhess, func);
7238: }
1.193 brouard 7239: printf("Parameters and 95%% confidence intervals\n");
7240: fprintf(ficlog, "Parameters, T and confidence intervals\n");
7241: for(i=1,jk=1; i <=nlstate; i++){
7242: for(k=1; k <=(nlstate+ndeath); k++){
7243: if (k != i) {
7244: printf("%d%d ",i,k);
7245: fprintf(ficlog,"%d%d ",i,k);
7246: for(j=1; j <=ncovmodel; j++){
7247: printf("%12.7f T=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-2*sqrt(matcov[jk][jk]),p[jk]+2*sqrt(matcov[jk][jk]));
7248: fprintf(ficlog,"%12.7f T=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-2*sqrt(matcov[jk][jk]),p[jk]+2*sqrt(matcov[jk][jk]));
7249: jk++;
7250: }
7251: printf("\n");
7252: fprintf(ficlog,"\n");
7253: }
7254: }
7255: }
7256:
1.126 brouard 7257: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7258: printf("# Scales (for hessian or gradient estimation)\n");
7259: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7260: for(i=1,jk=1; i <=nlstate; i++){
7261: for(j=1; j <=nlstate+ndeath; j++){
7262: if (j!=i) {
7263: fprintf(ficres,"%1d%1d",i,j);
7264: printf("%1d%1d",i,j);
7265: fprintf(ficlog,"%1d%1d",i,j);
7266: for(k=1; k<=ncovmodel;k++){
7267: printf(" %.5e",delti[jk]);
7268: fprintf(ficlog," %.5e",delti[jk]);
7269: fprintf(ficres," %.5e",delti[jk]);
7270: jk++;
7271: }
7272: printf("\n");
7273: fprintf(ficlog,"\n");
7274: fprintf(ficres,"\n");
7275: }
7276: }
7277: }
7278:
7279: 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");
7280: if(mle>=1)
7281: 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");
7282: 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");
7283: /* # 121 Var(a12)\n\ */
7284: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7285: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7286: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7287: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7288: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7289: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7290: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7291:
7292:
7293: /* Just to have a covariance matrix which will be more understandable
7294: even is we still don't want to manage dictionary of variables
7295: */
7296: for(itimes=1;itimes<=2;itimes++){
7297: jj=0;
7298: for(i=1; i <=nlstate; i++){
7299: for(j=1; j <=nlstate+ndeath; j++){
7300: if(j==i) continue;
7301: for(k=1; k<=ncovmodel;k++){
7302: jj++;
7303: ca[0]= k+'a'-1;ca[1]='\0';
7304: if(itimes==1){
7305: if(mle>=1)
7306: printf("#%1d%1d%d",i,j,k);
7307: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7308: fprintf(ficres,"#%1d%1d%d",i,j,k);
7309: }else{
7310: if(mle>=1)
7311: printf("%1d%1d%d",i,j,k);
7312: fprintf(ficlog,"%1d%1d%d",i,j,k);
7313: fprintf(ficres,"%1d%1d%d",i,j,k);
7314: }
7315: ll=0;
7316: for(li=1;li <=nlstate; li++){
7317: for(lj=1;lj <=nlstate+ndeath; lj++){
7318: if(lj==li) continue;
7319: for(lk=1;lk<=ncovmodel;lk++){
7320: ll++;
7321: if(ll<=jj){
7322: cb[0]= lk +'a'-1;cb[1]='\0';
7323: if(ll<jj){
7324: if(itimes==1){
7325: if(mle>=1)
7326: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7327: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7328: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7329: }else{
7330: if(mle>=1)
7331: printf(" %.5e",matcov[jj][ll]);
7332: fprintf(ficlog," %.5e",matcov[jj][ll]);
7333: fprintf(ficres," %.5e",matcov[jj][ll]);
7334: }
7335: }else{
7336: if(itimes==1){
7337: if(mle>=1)
7338: printf(" Var(%s%1d%1d)",ca,i,j);
7339: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7340: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7341: }else{
7342: if(mle>=1)
7343: printf(" %.5e",matcov[jj][ll]);
7344: fprintf(ficlog," %.5e",matcov[jj][ll]);
7345: fprintf(ficres," %.5e",matcov[jj][ll]);
7346: }
7347: }
7348: }
7349: } /* end lk */
7350: } /* end lj */
7351: } /* end li */
7352: if(mle>=1)
7353: printf("\n");
7354: fprintf(ficlog,"\n");
7355: fprintf(ficres,"\n");
7356: numlinepar++;
7357: } /* end k*/
7358: } /*end j */
7359: } /* end i */
7360: } /* end itimes */
7361:
7362: fflush(ficlog);
7363: fflush(ficres);
7364:
7365: while((c=getc(ficpar))=='#' && c!= EOF){
7366: ungetc(c,ficpar);
7367: fgets(line, MAXLINE, ficpar);
1.141 brouard 7368: fputs(line,stdout);
1.126 brouard 7369: fputs(line,ficparo);
7370: }
7371: ungetc(c,ficpar);
7372:
7373: estepm=0;
7374: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7375: if (estepm==0 || estepm < stepm) estepm=stepm;
7376: if (fage <= 2) {
7377: bage = ageminpar;
7378: fage = agemaxpar;
7379: }
7380:
7381: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7382: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7383: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7384:
7385: /* Other stuffs, more or less useful */
1.126 brouard 7386: while((c=getc(ficpar))=='#' && c!= EOF){
7387: ungetc(c,ficpar);
7388: fgets(line, MAXLINE, ficpar);
1.141 brouard 7389: fputs(line,stdout);
1.126 brouard 7390: fputs(line,ficparo);
7391: }
7392: ungetc(c,ficpar);
7393:
7394: 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);
7395: 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);
7396: 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);
7397: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7398: 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);
7399:
7400: while((c=getc(ficpar))=='#' && c!= EOF){
7401: ungetc(c,ficpar);
7402: fgets(line, MAXLINE, ficpar);
1.141 brouard 7403: fputs(line,stdout);
1.126 brouard 7404: fputs(line,ficparo);
7405: }
7406: ungetc(c,ficpar);
7407:
7408:
7409: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7410: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7411:
7412: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 7413: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 7414: fprintf(ficparo,"pop_based=%d\n",popbased);
7415: fprintf(ficres,"pop_based=%d\n",popbased);
7416:
7417: while((c=getc(ficpar))=='#' && c!= EOF){
7418: ungetc(c,ficpar);
7419: fgets(line, MAXLINE, ficpar);
1.141 brouard 7420: fputs(line,stdout);
1.126 brouard 7421: fputs(line,ficparo);
7422: }
7423: ungetc(c,ficpar);
7424:
7425: 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);
7426: 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);
7427: 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);
7428: 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);
7429: 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);
7430: /* day and month of proj2 are not used but only year anproj2.*/
7431:
7432:
7433:
1.145 brouard 7434: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7435: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7436:
7437: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 ! brouard 7438: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
! 7439: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
! 7440: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
! 7441: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
! 7442: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
! 7443: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
! 7444: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
! 7445: }else
! 7446: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7447:
7448: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7449: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7450: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7451:
7452: /*------------ free_vector -------------*/
7453: /* chdir(path); */
7454:
7455: free_ivector(wav,1,imx);
7456: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7457: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7458: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7459: free_lvector(num,1,n);
7460: free_vector(agedc,1,n);
7461: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7462: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7463: fclose(ficparo);
7464: fclose(ficres);
7465:
7466:
1.186 brouard 7467: /* Other results (useful)*/
7468:
7469:
1.126 brouard 7470: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7471: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7472: prlim=matrix(1,nlstate,1,nlstate);
7473: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7474: fclose(ficrespl);
7475:
1.145 brouard 7476: #ifdef FREEEXIT2
7477: #include "freeexit2.h"
7478: #endif
7479:
1.126 brouard 7480: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7481: /*#include "hpijx.h"*/
7482: hPijx(p, bage, fage);
1.145 brouard 7483: fclose(ficrespij);
1.126 brouard 7484:
1.145 brouard 7485: /*-------------- Variance of one-step probabilities---*/
7486: k=1;
1.126 brouard 7487: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7488:
7489:
7490: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7491: for(i=1;i<=AGESUP;i++)
7492: for(j=1;j<=NCOVMAX;j++)
7493: for(k=1;k<=NCOVMAX;k++)
7494: probs[i][j][k]=0.;
7495:
7496: /*---------- Forecasting ------------------*/
7497: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7498: if(prevfcast==1){
7499: /* if(stepm ==1){*/
7500: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7501: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7502: /* } */
7503: /* else{ */
7504: /* erreur=108; */
7505: /* 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); */
7506: /* 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); */
7507: /* } */
7508: }
1.186 brouard 7509:
7510: /* ------ Other prevalence ratios------------ */
1.126 brouard 7511:
1.127 brouard 7512: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7513:
7514: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7515: /* 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",\
7516: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7517: */
1.126 brouard 7518:
1.127 brouard 7519: if (mobilav!=0) {
7520: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7521: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7522: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7523: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7524: }
1.126 brouard 7525: }
7526:
7527:
1.127 brouard 7528: /*---------- Health expectancies, no variances ------------*/
7529:
1.126 brouard 7530: strcpy(filerese,"e");
7531: strcat(filerese,fileres);
7532: if((ficreseij=fopen(filerese,"w"))==NULL) {
7533: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7534: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7535: }
7536: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7537: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7538: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7539: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7540:
7541: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7542: fprintf(ficreseij,"\n#****** ");
7543: for(j=1;j<=cptcoveff;j++) {
7544: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7545: }
7546: fprintf(ficreseij,"******\n");
7547:
7548: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7549: oldm=oldms;savm=savms;
7550: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7551:
7552: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7553: /*}*/
1.127 brouard 7554: }
7555: fclose(ficreseij);
7556:
7557:
7558: /*---------- Health expectancies and variances ------------*/
7559:
7560:
7561: strcpy(filerest,"t");
7562: strcat(filerest,fileres);
7563: if((ficrest=fopen(filerest,"w"))==NULL) {
7564: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7565: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7566: }
7567: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7568: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7569:
1.126 brouard 7570:
7571: strcpy(fileresstde,"stde");
7572: strcat(fileresstde,fileres);
7573: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7574: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7575: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7576: }
7577: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7578: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7579:
7580: strcpy(filerescve,"cve");
7581: strcat(filerescve,fileres);
7582: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7583: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7584: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7585: }
7586: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7587: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7588:
7589: strcpy(fileresv,"v");
7590: strcat(fileresv,fileres);
7591: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7592: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7593: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7594: }
7595: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7596: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7597:
1.145 brouard 7598: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7599: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7600:
7601: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7602: fprintf(ficrest,"\n#****** ");
1.126 brouard 7603: for(j=1;j<=cptcoveff;j++)
7604: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7605: fprintf(ficrest,"******\n");
7606:
7607: fprintf(ficresstdeij,"\n#****** ");
7608: fprintf(ficrescveij,"\n#****** ");
7609: for(j=1;j<=cptcoveff;j++) {
7610: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7611: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7612: }
7613: fprintf(ficresstdeij,"******\n");
7614: fprintf(ficrescveij,"******\n");
7615:
7616: fprintf(ficresvij,"\n#****** ");
7617: for(j=1;j<=cptcoveff;j++)
7618: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7619: fprintf(ficresvij,"******\n");
7620:
7621: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7622: oldm=oldms;savm=savms;
1.127 brouard 7623: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7624: /*
7625: */
7626: /* goto endfree; */
1.126 brouard 7627:
7628: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7629: pstamp(ficrest);
1.145 brouard 7630:
7631:
1.128 brouard 7632: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7633: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7634: cptcod= 0; /* To be deleted */
7635: 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 7636: 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 7637: if(vpopbased==1)
7638: 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);
7639: else
7640: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7641: fprintf(ficrest,"# Age e.. (std) ");
7642: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7643: fprintf(ficrest,"\n");
1.126 brouard 7644:
1.128 brouard 7645: epj=vector(1,nlstate+1);
7646: for(age=bage; age <=fage ;age++){
7647: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7648: if (vpopbased==1) {
7649: if(mobilav ==0){
7650: for(i=1; i<=nlstate;i++)
7651: prlim[i][i]=probs[(int)age][i][k];
7652: }else{ /* mobilav */
7653: for(i=1; i<=nlstate;i++)
7654: prlim[i][i]=mobaverage[(int)age][i][k];
7655: }
1.126 brouard 7656: }
7657:
1.128 brouard 7658: fprintf(ficrest," %4.0f",age);
7659: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7660: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7661: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7662: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7663: }
7664: epj[nlstate+1] +=epj[j];
1.126 brouard 7665: }
7666:
1.128 brouard 7667: for(i=1, vepp=0.;i <=nlstate;i++)
7668: for(j=1;j <=nlstate;j++)
7669: vepp += vareij[i][j][(int)age];
7670: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7671: for(j=1;j <=nlstate;j++){
7672: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7673: }
7674: fprintf(ficrest,"\n");
1.126 brouard 7675: }
7676: }
7677: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7678: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7679: free_vector(epj,1,nlstate+1);
1.145 brouard 7680: /*}*/
1.126 brouard 7681: }
7682: free_vector(weight,1,n);
1.145 brouard 7683: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7684: free_imatrix(s,1,maxwav+1,1,n);
7685: free_matrix(anint,1,maxwav,1,n);
7686: free_matrix(mint,1,maxwav,1,n);
7687: free_ivector(cod,1,n);
7688: free_ivector(tab,1,NCOVMAX);
7689: fclose(ficresstdeij);
7690: fclose(ficrescveij);
7691: fclose(ficresvij);
7692: fclose(ficrest);
7693: fclose(ficpar);
7694:
7695: /*------- Variance of period (stable) prevalence------*/
7696:
7697: strcpy(fileresvpl,"vpl");
7698: strcat(fileresvpl,fileres);
7699: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7700: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7701: exit(0);
7702: }
7703: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7704:
1.145 brouard 7705: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7706: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7707:
7708: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7709: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7710: for(j=1;j<=cptcoveff;j++)
7711: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7712: fprintf(ficresvpl,"******\n");
7713:
7714: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7715: oldm=oldms;savm=savms;
7716: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7717: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7718: /*}*/
1.126 brouard 7719: }
7720:
7721: fclose(ficresvpl);
7722:
7723: /*---------- End : free ----------------*/
7724: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7725: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7726: } /* mle==-3 arrives here for freeing */
1.164 brouard 7727: /* endfree:*/
1.141 brouard 7728: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7729: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7730: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7731: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7732: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7733: free_matrix(covar,0,NCOVMAX,1,n);
7734: free_matrix(matcov,1,npar,1,npar);
7735: /*free_vector(delti,1,npar);*/
7736: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7737: free_matrix(agev,1,maxwav,1,imx);
7738: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7739:
1.145 brouard 7740: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 7741: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 7742: free_ivector(Tvar,1,NCOVMAX);
7743: free_ivector(Tprod,1,NCOVMAX);
7744: free_ivector(Tvaraff,1,NCOVMAX);
7745: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7746:
7747: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7748: free_imatrix(codtab,1,100,1,10);
7749: fflush(fichtm);
7750: fflush(ficgp);
7751:
7752:
7753: if((nberr >0) || (nbwarn>0)){
7754: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7755: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7756: }else{
7757: printf("End of Imach\n");
7758: fprintf(ficlog,"End of Imach\n");
7759: }
7760: printf("See log file on %s\n",filelog);
7761: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7762: /*(void) gettimeofday(&end_time,&tzp);*/
7763: rend_time = time(NULL);
7764: end_time = *localtime(&rend_time);
7765: /* tml = *localtime(&end_time.tm_sec); */
7766: strcpy(strtend,asctime(&end_time));
1.126 brouard 7767: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7768: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7769: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7770:
1.157 brouard 7771: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7772: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7773: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7774: /* printf("Total time was %d uSec.\n", total_usecs);*/
7775: /* if(fileappend(fichtm,optionfilehtm)){ */
7776: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7777: fclose(fichtm);
7778: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7779: fclose(fichtmcov);
7780: fclose(ficgp);
7781: fclose(ficlog);
7782: /*------ End -----------*/
7783:
7784:
7785: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 7786: #ifdef WIN32
7787: if (_chdir(pathcd) != 0)
7788: printf("Can't move to directory %s!\n",path);
7789: if(_getcwd(pathcd,MAXLINE) > 0)
7790: #else
1.126 brouard 7791: if(chdir(pathcd) != 0)
1.184 brouard 7792: printf("Can't move to directory %s!\n", path);
7793: if (getcwd(pathcd, MAXLINE) > 0)
7794: #endif
1.126 brouard 7795: printf("Current directory %s!\n",pathcd);
7796: /*strcat(plotcmd,CHARSEPARATOR);*/
7797: sprintf(plotcmd,"gnuplot");
1.157 brouard 7798: #ifdef _WIN32
1.126 brouard 7799: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7800: #endif
7801: if(!stat(plotcmd,&info)){
1.158 brouard 7802: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7803: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7804: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7805: }else
7806: strcpy(pplotcmd,plotcmd);
1.157 brouard 7807: #ifdef __unix
1.126 brouard 7808: strcpy(plotcmd,GNUPLOTPROGRAM);
7809: if(!stat(plotcmd,&info)){
1.158 brouard 7810: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7811: }else
7812: strcpy(pplotcmd,plotcmd);
7813: #endif
7814: }else
7815: strcpy(pplotcmd,plotcmd);
7816:
7817: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7818: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7819:
7820: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7821: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7822: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7823: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7824: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7825: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7826: }
1.158 brouard 7827: printf(" Successful, please wait...");
1.126 brouard 7828: while (z[0] != 'q') {
7829: /* chdir(path); */
1.154 brouard 7830: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7831: scanf("%s",z);
7832: /* if (z[0] == 'c') system("./imach"); */
7833: if (z[0] == 'e') {
1.158 brouard 7834: #ifdef __APPLE__
1.152 brouard 7835: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7836: #elif __linux
7837: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7838: #else
1.152 brouard 7839: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7840: #endif
7841: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7842: system(pplotcmd);
1.126 brouard 7843: }
7844: else if (z[0] == 'g') system(plotcmd);
7845: else if (z[0] == 'q') exit(0);
7846: }
7847: end:
7848: while (z[0] != 'q') {
7849: printf("\nType q for exiting: ");
7850: scanf("%s",z);
7851: }
7852: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>