Annotation of imach/src/imach.c, revision 1.189
1.189 ! brouard 1: /* $Id: imach.c,v 1.188 2015/04/30 08:27:53 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.189 ! brouard 4: Revision 1.188 2015/04/30 08:27:53 brouard
! 5: *** empty log message ***
! 6:
1.188 brouard 7: Revision 1.187 2015/04/29 09:11:15 brouard
8: *** empty log message ***
9:
1.187 brouard 10: Revision 1.186 2015/04/23 12:01:52 brouard
11: Summary: V1*age is working now, version 0.98q1
12:
13: Some codes had been disabled in order to simplify and Vn*age was
14: working in the optimization phase, ie, giving correct MLE parameters,
15: but, as usual, outputs were not correct and program core dumped.
16:
1.186 brouard 17: Revision 1.185 2015/03/11 13:26:42 brouard
18: Summary: Inclusion of compile and links command line for Intel Compiler
19:
1.185 brouard 20: Revision 1.184 2015/03/11 11:52:39 brouard
21: Summary: Back from Windows 8. Intel Compiler
22:
1.184 brouard 23: Revision 1.183 2015/03/10 20:34:32 brouard
24: Summary: 0.98q0, trying with directest, mnbrak fixed
25:
26: We use directest instead of original Powell test; probably no
27: incidence on the results, but better justifications;
28: We fixed Numerical Recipes mnbrak routine which was wrong and gave
29: wrong results.
30:
1.183 brouard 31: Revision 1.182 2015/02/12 08:19:57 brouard
32: Summary: Trying to keep directest which seems simpler and more general
33: Author: Nicolas Brouard
34:
1.182 brouard 35: Revision 1.181 2015/02/11 23:22:24 brouard
36: Summary: Comments on Powell added
37:
38: Author:
39:
1.181 brouard 40: Revision 1.180 2015/02/11 17:33:45 brouard
41: Summary: Finishing move from main to function (hpijx and prevalence_limit)
42:
1.180 brouard 43: Revision 1.179 2015/01/04 09:57:06 brouard
44: Summary: back to OS/X
45:
1.179 brouard 46: Revision 1.178 2015/01/04 09:35:48 brouard
47: *** empty log message ***
48:
1.178 brouard 49: Revision 1.177 2015/01/03 18:40:56 brouard
50: Summary: Still testing ilc32 on OSX
51:
1.177 brouard 52: Revision 1.176 2015/01/03 16:45:04 brouard
53: *** empty log message ***
54:
1.176 brouard 55: Revision 1.175 2015/01/03 16:33:42 brouard
56: *** empty log message ***
57:
1.175 brouard 58: Revision 1.174 2015/01/03 16:15:49 brouard
59: Summary: Still in cross-compilation
60:
1.174 brouard 61: Revision 1.173 2015/01/03 12:06:26 brouard
62: Summary: trying to detect cross-compilation
63:
1.173 brouard 64: Revision 1.172 2014/12/27 12:07:47 brouard
65: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
66:
1.172 brouard 67: Revision 1.171 2014/12/23 13:26:59 brouard
68: Summary: Back from Visual C
69:
70: Still problem with utsname.h on Windows
71:
1.171 brouard 72: Revision 1.170 2014/12/23 11:17:12 brouard
73: Summary: Cleaning some \%% back to %%
74:
75: The escape was mandatory for a specific compiler (which one?), but too many warnings.
76:
1.170 brouard 77: Revision 1.169 2014/12/22 23:08:31 brouard
78: Summary: 0.98p
79:
80: Outputs some informations on compiler used, OS etc. Testing on different platforms.
81:
1.169 brouard 82: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 83: Summary: update
1.169 brouard 84:
1.168 brouard 85: Revision 1.167 2014/12/22 13:50:56 brouard
86: Summary: Testing uname and compiler version and if compiled 32 or 64
87:
88: Testing on Linux 64
89:
1.167 brouard 90: Revision 1.166 2014/12/22 11:40:47 brouard
91: *** empty log message ***
92:
1.166 brouard 93: Revision 1.165 2014/12/16 11:20:36 brouard
94: Summary: After compiling on Visual C
95:
96: * imach.c (Module): Merging 1.61 to 1.162
97:
1.165 brouard 98: Revision 1.164 2014/12/16 10:52:11 brouard
99: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
100:
101: * imach.c (Module): Merging 1.61 to 1.162
102:
1.164 brouard 103: Revision 1.163 2014/12/16 10:30:11 brouard
104: * imach.c (Module): Merging 1.61 to 1.162
105:
1.163 brouard 106: Revision 1.162 2014/09/25 11:43:39 brouard
107: Summary: temporary backup 0.99!
108:
1.162 brouard 109: Revision 1.1 2014/09/16 11:06:58 brouard
110: Summary: With some code (wrong) for nlopt
111:
112: Author:
113:
114: Revision 1.161 2014/09/15 20:41:41 brouard
115: Summary: Problem with macro SQR on Intel compiler
116:
1.161 brouard 117: Revision 1.160 2014/09/02 09:24:05 brouard
118: *** empty log message ***
119:
1.160 brouard 120: Revision 1.159 2014/09/01 10:34:10 brouard
121: Summary: WIN32
122: Author: Brouard
123:
1.159 brouard 124: Revision 1.158 2014/08/27 17:11:51 brouard
125: *** empty log message ***
126:
1.158 brouard 127: Revision 1.157 2014/08/27 16:26:55 brouard
128: Summary: Preparing windows Visual studio version
129: Author: Brouard
130:
131: In order to compile on Visual studio, time.h is now correct and time_t
132: and tm struct should be used. difftime should be used but sometimes I
133: just make the differences in raw time format (time(&now).
134: Trying to suppress #ifdef LINUX
135: Add xdg-open for __linux in order to open default browser.
136:
1.157 brouard 137: Revision 1.156 2014/08/25 20:10:10 brouard
138: *** empty log message ***
139:
1.156 brouard 140: Revision 1.155 2014/08/25 18:32:34 brouard
141: Summary: New compile, minor changes
142: Author: Brouard
143:
1.155 brouard 144: Revision 1.154 2014/06/20 17:32:08 brouard
145: Summary: Outputs now all graphs of convergence to period prevalence
146:
1.154 brouard 147: Revision 1.153 2014/06/20 16:45:46 brouard
148: Summary: If 3 live state, convergence to period prevalence on same graph
149: Author: Brouard
150:
1.153 brouard 151: Revision 1.152 2014/06/18 17:54:09 brouard
152: Summary: open browser, use gnuplot on same dir than imach if not found in the path
153:
1.152 brouard 154: Revision 1.151 2014/06/18 16:43:30 brouard
155: *** empty log message ***
156:
1.151 brouard 157: Revision 1.150 2014/06/18 16:42:35 brouard
158: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
159: Author: brouard
160:
1.150 brouard 161: Revision 1.149 2014/06/18 15:51:14 brouard
162: Summary: Some fixes in parameter files errors
163: Author: Nicolas Brouard
164:
1.149 brouard 165: Revision 1.148 2014/06/17 17:38:48 brouard
166: Summary: Nothing new
167: Author: Brouard
168:
169: Just a new packaging for OS/X version 0.98nS
170:
1.148 brouard 171: Revision 1.147 2014/06/16 10:33:11 brouard
172: *** empty log message ***
173:
1.147 brouard 174: Revision 1.146 2014/06/16 10:20:28 brouard
175: Summary: Merge
176: Author: Brouard
177:
178: Merge, before building revised version.
179:
1.146 brouard 180: Revision 1.145 2014/06/10 21:23:15 brouard
181: Summary: Debugging with valgrind
182: Author: Nicolas Brouard
183:
184: Lot of changes in order to output the results with some covariates
185: After the Edimburgh REVES conference 2014, it seems mandatory to
186: improve the code.
187: No more memory valgrind error but a lot has to be done in order to
188: continue the work of splitting the code into subroutines.
189: Also, decodemodel has been improved. Tricode is still not
190: optimal. nbcode should be improved. Documentation has been added in
191: the source code.
192:
1.144 brouard 193: Revision 1.143 2014/01/26 09:45:38 brouard
194: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
195:
196: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
197: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
198:
1.143 brouard 199: Revision 1.142 2014/01/26 03:57:36 brouard
200: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
201:
202: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
203:
1.142 brouard 204: Revision 1.141 2014/01/26 02:42:01 brouard
205: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
206:
1.141 brouard 207: Revision 1.140 2011/09/02 10:37:54 brouard
208: Summary: times.h is ok with mingw32 now.
209:
1.140 brouard 210: Revision 1.139 2010/06/14 07:50:17 brouard
211: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
212: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
213:
1.139 brouard 214: Revision 1.138 2010/04/30 18:19:40 brouard
215: *** empty log message ***
216:
1.138 brouard 217: Revision 1.137 2010/04/29 18:11:38 brouard
218: (Module): Checking covariates for more complex models
219: than V1+V2. A lot of change to be done. Unstable.
220:
1.137 brouard 221: Revision 1.136 2010/04/26 20:30:53 brouard
222: (Module): merging some libgsl code. Fixing computation
223: of likelione (using inter/intrapolation if mle = 0) in order to
224: get same likelihood as if mle=1.
225: Some cleaning of code and comments added.
226:
1.136 brouard 227: Revision 1.135 2009/10/29 15:33:14 brouard
228: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
229:
1.135 brouard 230: Revision 1.134 2009/10/29 13:18:53 brouard
231: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
232:
1.134 brouard 233: Revision 1.133 2009/07/06 10:21:25 brouard
234: just nforces
235:
1.133 brouard 236: Revision 1.132 2009/07/06 08:22:05 brouard
237: Many tings
238:
1.132 brouard 239: Revision 1.131 2009/06/20 16:22:47 brouard
240: Some dimensions resccaled
241:
1.131 brouard 242: Revision 1.130 2009/05/26 06:44:34 brouard
243: (Module): Max Covariate is now set to 20 instead of 8. A
244: lot of cleaning with variables initialized to 0. Trying to make
245: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
246:
1.130 brouard 247: Revision 1.129 2007/08/31 13:49:27 lievre
248: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
249:
1.129 lievre 250: Revision 1.128 2006/06/30 13:02:05 brouard
251: (Module): Clarifications on computing e.j
252:
1.128 brouard 253: Revision 1.127 2006/04/28 18:11:50 brouard
254: (Module): Yes the sum of survivors was wrong since
255: imach-114 because nhstepm was no more computed in the age
256: loop. Now we define nhstepma in the age loop.
257: (Module): In order to speed up (in case of numerous covariates) we
258: compute health expectancies (without variances) in a first step
259: and then all the health expectancies with variances or standard
260: deviation (needs data from the Hessian matrices) which slows the
261: computation.
262: In the future we should be able to stop the program is only health
263: expectancies and graph are needed without standard deviations.
264:
1.127 brouard 265: Revision 1.126 2006/04/28 17:23:28 brouard
266: (Module): Yes the sum of survivors was wrong since
267: imach-114 because nhstepm was no more computed in the age
268: loop. Now we define nhstepma in the age loop.
269: Version 0.98h
270:
1.126 brouard 271: Revision 1.125 2006/04/04 15:20:31 lievre
272: Errors in calculation of health expectancies. Age was not initialized.
273: Forecasting file added.
274:
275: Revision 1.124 2006/03/22 17:13:53 lievre
276: Parameters are printed with %lf instead of %f (more numbers after the comma).
277: The log-likelihood is printed in the log file
278:
279: Revision 1.123 2006/03/20 10:52:43 brouard
280: * imach.c (Module): <title> changed, corresponds to .htm file
281: name. <head> headers where missing.
282:
283: * imach.c (Module): Weights can have a decimal point as for
284: English (a comma might work with a correct LC_NUMERIC environment,
285: otherwise the weight is truncated).
286: Modification of warning when the covariates values are not 0 or
287: 1.
288: Version 0.98g
289:
290: Revision 1.122 2006/03/20 09:45:41 brouard
291: (Module): Weights can have a decimal point as for
292: English (a comma might work with a correct LC_NUMERIC environment,
293: otherwise the weight is truncated).
294: Modification of warning when the covariates values are not 0 or
295: 1.
296: Version 0.98g
297:
298: Revision 1.121 2006/03/16 17:45:01 lievre
299: * imach.c (Module): Comments concerning covariates added
300:
301: * imach.c (Module): refinements in the computation of lli if
302: status=-2 in order to have more reliable computation if stepm is
303: not 1 month. Version 0.98f
304:
305: Revision 1.120 2006/03/16 15:10:38 lievre
306: (Module): refinements in the computation of lli if
307: status=-2 in order to have more reliable computation if stepm is
308: not 1 month. Version 0.98f
309:
310: Revision 1.119 2006/03/15 17:42:26 brouard
311: (Module): Bug if status = -2, the loglikelihood was
312: computed as likelihood omitting the logarithm. Version O.98e
313:
314: Revision 1.118 2006/03/14 18:20:07 brouard
315: (Module): varevsij Comments added explaining the second
316: table of variances if popbased=1 .
317: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
318: (Module): Function pstamp added
319: (Module): Version 0.98d
320:
321: Revision 1.117 2006/03/14 17:16:22 brouard
322: (Module): varevsij Comments added explaining the second
323: table of variances if popbased=1 .
324: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
325: (Module): Function pstamp added
326: (Module): Version 0.98d
327:
328: Revision 1.116 2006/03/06 10:29:27 brouard
329: (Module): Variance-covariance wrong links and
330: varian-covariance of ej. is needed (Saito).
331:
332: Revision 1.115 2006/02/27 12:17:45 brouard
333: (Module): One freematrix added in mlikeli! 0.98c
334:
335: Revision 1.114 2006/02/26 12:57:58 brouard
336: (Module): Some improvements in processing parameter
337: filename with strsep.
338:
339: Revision 1.113 2006/02/24 14:20:24 brouard
340: (Module): Memory leaks checks with valgrind and:
341: datafile was not closed, some imatrix were not freed and on matrix
342: allocation too.
343:
344: Revision 1.112 2006/01/30 09:55:26 brouard
345: (Module): Back to gnuplot.exe instead of wgnuplot.exe
346:
347: Revision 1.111 2006/01/25 20:38:18 brouard
348: (Module): Lots of cleaning and bugs added (Gompertz)
349: (Module): Comments can be added in data file. Missing date values
350: can be a simple dot '.'.
351:
352: Revision 1.110 2006/01/25 00:51:50 brouard
353: (Module): Lots of cleaning and bugs added (Gompertz)
354:
355: Revision 1.109 2006/01/24 19:37:15 brouard
356: (Module): Comments (lines starting with a #) are allowed in data.
357:
358: Revision 1.108 2006/01/19 18:05:42 lievre
359: Gnuplot problem appeared...
360: To be fixed
361:
362: Revision 1.107 2006/01/19 16:20:37 brouard
363: Test existence of gnuplot in imach path
364:
365: Revision 1.106 2006/01/19 13:24:36 brouard
366: Some cleaning and links added in html output
367:
368: Revision 1.105 2006/01/05 20:23:19 lievre
369: *** empty log message ***
370:
371: Revision 1.104 2005/09/30 16:11:43 lievre
372: (Module): sump fixed, loop imx fixed, and simplifications.
373: (Module): If the status is missing at the last wave but we know
374: that the person is alive, then we can code his/her status as -2
375: (instead of missing=-1 in earlier versions) and his/her
376: contributions to the likelihood is 1 - Prob of dying from last
377: health status (= 1-p13= p11+p12 in the easiest case of somebody in
378: the healthy state at last known wave). Version is 0.98
379:
380: Revision 1.103 2005/09/30 15:54:49 lievre
381: (Module): sump fixed, loop imx fixed, and simplifications.
382:
383: Revision 1.102 2004/09/15 17:31:30 brouard
384: Add the possibility to read data file including tab characters.
385:
386: Revision 1.101 2004/09/15 10:38:38 brouard
387: Fix on curr_time
388:
389: Revision 1.100 2004/07/12 18:29:06 brouard
390: Add version for Mac OS X. Just define UNIX in Makefile
391:
392: Revision 1.99 2004/06/05 08:57:40 brouard
393: *** empty log message ***
394:
395: Revision 1.98 2004/05/16 15:05:56 brouard
396: New version 0.97 . First attempt to estimate force of mortality
397: directly from the data i.e. without the need of knowing the health
398: state at each age, but using a Gompertz model: log u =a + b*age .
399: This is the basic analysis of mortality and should be done before any
400: other analysis, in order to test if the mortality estimated from the
401: cross-longitudinal survey is different from the mortality estimated
402: from other sources like vital statistic data.
403:
404: The same imach parameter file can be used but the option for mle should be -3.
405:
1.133 brouard 406: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 407: former routines in order to include the new code within the former code.
408:
409: The output is very simple: only an estimate of the intercept and of
410: the slope with 95% confident intervals.
411:
412: Current limitations:
413: A) Even if you enter covariates, i.e. with the
414: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
415: B) There is no computation of Life Expectancy nor Life Table.
416:
417: Revision 1.97 2004/02/20 13:25:42 lievre
418: Version 0.96d. Population forecasting command line is (temporarily)
419: suppressed.
420:
421: Revision 1.96 2003/07/15 15:38:55 brouard
422: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
423: rewritten within the same printf. Workaround: many printfs.
424:
425: Revision 1.95 2003/07/08 07:54:34 brouard
426: * imach.c (Repository):
427: (Repository): Using imachwizard code to output a more meaningful covariance
428: matrix (cov(a12,c31) instead of numbers.
429:
430: Revision 1.94 2003/06/27 13:00:02 brouard
431: Just cleaning
432:
433: Revision 1.93 2003/06/25 16:33:55 brouard
434: (Module): On windows (cygwin) function asctime_r doesn't
435: exist so I changed back to asctime which exists.
436: (Module): Version 0.96b
437:
438: Revision 1.92 2003/06/25 16:30:45 brouard
439: (Module): On windows (cygwin) function asctime_r doesn't
440: exist so I changed back to asctime which exists.
441:
442: Revision 1.91 2003/06/25 15:30:29 brouard
443: * imach.c (Repository): Duplicated warning errors corrected.
444: (Repository): Elapsed time after each iteration is now output. It
445: helps to forecast when convergence will be reached. Elapsed time
446: is stamped in powell. We created a new html file for the graphs
447: concerning matrix of covariance. It has extension -cov.htm.
448:
449: Revision 1.90 2003/06/24 12:34:15 brouard
450: (Module): Some bugs corrected for windows. Also, when
451: mle=-1 a template is output in file "or"mypar.txt with the design
452: of the covariance matrix to be input.
453:
454: Revision 1.89 2003/06/24 12:30:52 brouard
455: (Module): Some bugs corrected for windows. Also, when
456: mle=-1 a template is output in file "or"mypar.txt with the design
457: of the covariance matrix to be input.
458:
459: Revision 1.88 2003/06/23 17:54:56 brouard
460: * 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.
461:
462: Revision 1.87 2003/06/18 12:26:01 brouard
463: Version 0.96
464:
465: Revision 1.86 2003/06/17 20:04:08 brouard
466: (Module): Change position of html and gnuplot routines and added
467: routine fileappend.
468:
469: Revision 1.85 2003/06/17 13:12:43 brouard
470: * imach.c (Repository): Check when date of death was earlier that
471: current date of interview. It may happen when the death was just
472: prior to the death. In this case, dh was negative and likelihood
473: was wrong (infinity). We still send an "Error" but patch by
474: assuming that the date of death was just one stepm after the
475: interview.
476: (Repository): Because some people have very long ID (first column)
477: we changed int to long in num[] and we added a new lvector for
478: memory allocation. But we also truncated to 8 characters (left
479: truncation)
480: (Repository): No more line truncation errors.
481:
482: Revision 1.84 2003/06/13 21:44:43 brouard
483: * imach.c (Repository): Replace "freqsummary" at a correct
484: place. It differs from routine "prevalence" which may be called
485: many times. Probs is memory consuming and must be used with
486: parcimony.
487: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
488:
489: Revision 1.83 2003/06/10 13:39:11 lievre
490: *** empty log message ***
491:
492: Revision 1.82 2003/06/05 15:57:20 brouard
493: Add log in imach.c and fullversion number is now printed.
494:
495: */
496: /*
497: Interpolated Markov Chain
498:
499: Short summary of the programme:
500:
501: This program computes Healthy Life Expectancies from
502: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
503: first survey ("cross") where individuals from different ages are
504: interviewed on their health status or degree of disability (in the
505: case of a health survey which is our main interest) -2- at least a
506: second wave of interviews ("longitudinal") which measure each change
507: (if any) in individual health status. Health expectancies are
508: computed from the time spent in each health state according to a
509: model. More health states you consider, more time is necessary to reach the
510: Maximum Likelihood of the parameters involved in the model. The
511: simplest model is the multinomial logistic model where pij is the
512: probability to be observed in state j at the second wave
513: conditional to be observed in state i at the first wave. Therefore
514: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
515: 'age' is age and 'sex' is a covariate. If you want to have a more
516: complex model than "constant and age", you should modify the program
517: where the markup *Covariates have to be included here again* invites
518: you to do it. More covariates you add, slower the
519: convergence.
520:
521: The advantage of this computer programme, compared to a simple
522: multinomial logistic model, is clear when the delay between waves is not
523: identical for each individual. Also, if a individual missed an
524: intermediate interview, the information is lost, but taken into
525: account using an interpolation or extrapolation.
526:
527: hPijx is the probability to be observed in state i at age x+h
528: conditional to the observed state i at age x. The delay 'h' can be
529: split into an exact number (nh*stepm) of unobserved intermediate
530: states. This elementary transition (by month, quarter,
531: semester or year) is modelled as a multinomial logistic. The hPx
532: matrix is simply the matrix product of nh*stepm elementary matrices
533: and the contribution of each individual to the likelihood is simply
534: hPijx.
535:
536: Also this programme outputs the covariance matrix of the parameters but also
537: of the life expectancies. It also computes the period (stable) prevalence.
538:
1.133 brouard 539: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
540: Institut national d'études démographiques, Paris.
1.126 brouard 541: This software have been partly granted by Euro-REVES, a concerted action
542: from the European Union.
543: It is copyrighted identically to a GNU software product, ie programme and
544: software can be distributed freely for non commercial use. Latest version
545: can be accessed at http://euroreves.ined.fr/imach .
546:
547: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
548: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
549:
550: **********************************************************************/
551: /*
552: main
553: read parameterfile
554: read datafile
555: concatwav
556: freqsummary
557: if (mle >= 1)
558: mlikeli
559: print results files
560: if mle==1
561: computes hessian
562: read end of parameter file: agemin, agemax, bage, fage, estepm
563: begin-prev-date,...
564: open gnuplot file
565: open html file
1.145 brouard 566: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
567: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
568: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
569: freexexit2 possible for memory heap.
570:
571: h Pij x | pij_nom ficrestpij
572: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
573: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
574: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
575:
576: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
577: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
578: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
579: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
580: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
581:
1.126 brouard 582: forecasting if prevfcast==1 prevforecast call prevalence()
583: health expectancies
584: Variance-covariance of DFLE
585: prevalence()
586: movingaverage()
587: varevsij()
588: if popbased==1 varevsij(,popbased)
589: total life expectancies
590: Variance of period (stable) prevalence
591: end
592: */
593:
1.187 brouard 594: /* #define DEBUG */
595: /* #define DEBUGBRENT */
1.165 brouard 596: #define POWELL /* Instead of NLOPT */
1.186 brouard 597: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
598: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 599:
600: #include <math.h>
601: #include <stdio.h>
602: #include <stdlib.h>
603: #include <string.h>
1.159 brouard 604:
605: #ifdef _WIN32
606: #include <io.h>
1.172 brouard 607: #include <windows.h>
608: #include <tchar.h>
1.159 brouard 609: #else
1.126 brouard 610: #include <unistd.h>
1.159 brouard 611: #endif
1.126 brouard 612:
613: #include <limits.h>
614: #include <sys/types.h>
1.171 brouard 615:
616: #if defined(__GNUC__)
617: #include <sys/utsname.h> /* Doesn't work on Windows */
618: #endif
619:
1.126 brouard 620: #include <sys/stat.h>
621: #include <errno.h>
1.159 brouard 622: /* extern int errno; */
1.126 brouard 623:
1.157 brouard 624: /* #ifdef LINUX */
625: /* #include <time.h> */
626: /* #include "timeval.h" */
627: /* #else */
628: /* #include <sys/time.h> */
629: /* #endif */
630:
1.126 brouard 631: #include <time.h>
632:
1.136 brouard 633: #ifdef GSL
634: #include <gsl/gsl_errno.h>
635: #include <gsl/gsl_multimin.h>
636: #endif
637:
1.167 brouard 638:
1.162 brouard 639: #ifdef NLOPT
640: #include <nlopt.h>
641: typedef struct {
642: double (* function)(double [] );
643: } myfunc_data ;
644: #endif
645:
1.126 brouard 646: /* #include <libintl.h> */
647: /* #define _(String) gettext (String) */
648:
1.141 brouard 649: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 650:
651: #define GNUPLOTPROGRAM "gnuplot"
652: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
653: #define FILENAMELENGTH 132
654:
655: #define GLOCK_ERROR_NOPATH -1 /* empty path */
656: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
657:
1.144 brouard 658: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
659: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 660:
661: #define NINTERVMAX 8
1.144 brouard 662: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
663: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
664: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 665: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 666: #define MAXN 20000
1.144 brouard 667: #define YEARM 12. /**< Number of months per year */
1.126 brouard 668: #define AGESUP 130
669: #define AGEBASE 40
1.164 brouard 670: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 671: #ifdef _WIN32
672: #define DIRSEPARATOR '\\'
673: #define CHARSEPARATOR "\\"
674: #define ODIRSEPARATOR '/'
675: #else
1.126 brouard 676: #define DIRSEPARATOR '/'
677: #define CHARSEPARATOR "/"
678: #define ODIRSEPARATOR '\\'
679: #endif
680:
1.189 ! brouard 681: /* $Id: imach.c,v 1.188 2015/04/30 08:27:53 brouard Exp $ */
1.126 brouard 682: /* $State: Exp $ */
683:
1.189 ! brouard 684: char version[]="Imach version 0.98q2, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
! 685: char fullversion[]="$Revision: 1.188 $ $Date: 2015/04/30 08:27:53 $";
1.126 brouard 686: char strstart[80];
687: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 688: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 689: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 690: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
691: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
692: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
693: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
694: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
695: int cptcovprodnoage=0; /**< Number of covariate products without age */
696: int cptcoveff=0; /* Total number of covariates to vary for printing results */
697: int cptcov=0; /* Working variable */
1.126 brouard 698: int npar=NPARMAX;
699: int nlstate=2; /* Number of live states */
700: int ndeath=1; /* Number of dead states */
1.130 brouard 701: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 702: int popbased=0;
703:
704: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 705: int maxwav=0; /* Maxim number of waves */
706: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
707: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
708: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 709: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 710: int mle=1, weightopt=0;
1.126 brouard 711: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
712: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
713: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
714: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 715: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 716: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 717: double **matprod2(); /* test */
1.126 brouard 718: double **oldm, **newm, **savm; /* Working pointers to matrices */
719: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 720: /*FILE *fic ; */ /* Used in readdata only */
721: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 722: FILE *ficlog, *ficrespow;
1.130 brouard 723: int globpr=0; /* Global variable for printing or not */
1.126 brouard 724: double fretone; /* Only one call to likelihood */
1.130 brouard 725: long ipmx=0; /* Number of contributions */
1.126 brouard 726: double sw; /* Sum of weights */
727: char filerespow[FILENAMELENGTH];
728: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
729: FILE *ficresilk;
730: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
731: FILE *ficresprobmorprev;
732: FILE *fichtm, *fichtmcov; /* Html File */
733: FILE *ficreseij;
734: char filerese[FILENAMELENGTH];
735: FILE *ficresstdeij;
736: char fileresstde[FILENAMELENGTH];
737: FILE *ficrescveij;
738: char filerescve[FILENAMELENGTH];
739: FILE *ficresvij;
740: char fileresv[FILENAMELENGTH];
741: FILE *ficresvpl;
742: char fileresvpl[FILENAMELENGTH];
743: char title[MAXLINE];
744: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
745: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
746: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
747: char command[FILENAMELENGTH];
748: int outcmd=0;
749:
750: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
751:
752: char filelog[FILENAMELENGTH]; /* Log file */
753: char filerest[FILENAMELENGTH];
754: char fileregp[FILENAMELENGTH];
755: char popfile[FILENAMELENGTH];
756:
757: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
758:
1.157 brouard 759: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
760: /* struct timezone tzp; */
761: /* extern int gettimeofday(); */
762: struct tm tml, *gmtime(), *localtime();
763:
764: extern time_t time();
765:
766: struct tm start_time, end_time, curr_time, last_time, forecast_time;
767: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
768: struct tm tm;
769:
1.126 brouard 770: char strcurr[80], strfor[80];
771:
772: char *endptr;
773: long lval;
774: double dval;
775:
776: #define NR_END 1
777: #define FREE_ARG char*
778: #define FTOL 1.0e-10
779:
780: #define NRANSI
781: #define ITMAX 200
782:
783: #define TOL 2.0e-4
784:
785: #define CGOLD 0.3819660
786: #define ZEPS 1.0e-10
787: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
788:
789: #define GOLD 1.618034
790: #define GLIMIT 100.0
791: #define TINY 1.0e-20
792:
793: static double maxarg1,maxarg2;
794: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
795: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
796:
797: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
798: #define rint(a) floor(a+0.5)
1.166 brouard 799: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 800: #define mytinydouble 1.0e-16
1.166 brouard 801: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
802: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
803: /* static double dsqrarg; */
804: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 805: static double sqrarg;
806: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
807: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
808: int agegomp= AGEGOMP;
809:
810: int imx;
811: int stepm=1;
812: /* Stepm, step in month: minimum step interpolation*/
813:
814: int estepm;
815: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
816:
817: int m,nb;
818: long *num;
819: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
820: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
821: double **pmmij, ***probs;
822: double *ageexmed,*agecens;
823: double dateintmean=0;
824:
825: double *weight;
826: int **s; /* Status */
1.141 brouard 827: double *agedc;
1.145 brouard 828: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 829: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 830: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 831: double idx;
832: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 833: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 834: int **codtab; /**< codtab=imatrix(1,100,1,10); */
835: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 836: double *lsurv, *lpop, *tpop;
837:
1.143 brouard 838: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
839: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 840:
841: /**************** split *************************/
842: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
843: {
844: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
845: the name of the file (name), its extension only (ext) and its first part of the name (finame)
846: */
847: char *ss; /* pointer */
1.186 brouard 848: int l1=0, l2=0; /* length counters */
1.126 brouard 849:
850: l1 = strlen(path ); /* length of path */
851: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
852: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
853: if ( ss == NULL ) { /* no directory, so determine current directory */
854: strcpy( name, path ); /* we got the fullname name because no directory */
855: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
856: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
857: /* get current working directory */
858: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 859: #ifdef WIN32
860: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
861: #else
862: if (getcwd(dirc, FILENAME_MAX) == NULL) {
863: #endif
1.126 brouard 864: return( GLOCK_ERROR_GETCWD );
865: }
866: /* got dirc from getcwd*/
867: printf(" DIRC = %s \n",dirc);
868: } else { /* strip direcotry from path */
869: ss++; /* after this, the filename */
870: l2 = strlen( ss ); /* length of filename */
871: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
872: strcpy( name, ss ); /* save file name */
873: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 874: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 875: printf(" DIRC2 = %s \n",dirc);
876: }
877: /* We add a separator at the end of dirc if not exists */
878: l1 = strlen( dirc ); /* length of directory */
879: if( dirc[l1-1] != DIRSEPARATOR ){
880: dirc[l1] = DIRSEPARATOR;
881: dirc[l1+1] = 0;
882: printf(" DIRC3 = %s \n",dirc);
883: }
884: ss = strrchr( name, '.' ); /* find last / */
885: if (ss >0){
886: ss++;
887: strcpy(ext,ss); /* save extension */
888: l1= strlen( name);
889: l2= strlen(ss)+1;
890: strncpy( finame, name, l1-l2);
891: finame[l1-l2]= 0;
892: }
893:
894: return( 0 ); /* we're done */
895: }
896:
897:
898: /******************************************/
899:
900: void replace_back_to_slash(char *s, char*t)
901: {
902: int i;
903: int lg=0;
904: i=0;
905: lg=strlen(t);
906: for(i=0; i<= lg; i++) {
907: (s[i] = t[i]);
908: if (t[i]== '\\') s[i]='/';
909: }
910: }
911:
1.132 brouard 912: char *trimbb(char *out, char *in)
1.137 brouard 913: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 914: char *s;
915: s=out;
916: while (*in != '\0'){
1.137 brouard 917: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 918: in++;
919: }
920: *out++ = *in++;
921: }
922: *out='\0';
923: return s;
924: }
925:
1.187 brouard 926: /* char *substrchaine(char *out, char *in, char *chain) */
927: /* { */
928: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
929: /* char *s, *t; */
930: /* t=in;s=out; */
931: /* while ((*in != *chain) && (*in != '\0')){ */
932: /* *out++ = *in++; */
933: /* } */
934:
935: /* /\* *in matches *chain *\/ */
936: /* while ((*in++ == *chain++) && (*in != '\0')){ */
937: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
938: /* } */
939: /* in--; chain--; */
940: /* while ( (*in != '\0')){ */
941: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
942: /* *out++ = *in++; */
943: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
944: /* } */
945: /* *out='\0'; */
946: /* out=s; */
947: /* return out; */
948: /* } */
949: char *substrchaine(char *out, char *in, char *chain)
950: {
951: /* Substract chain 'chain' from 'in', return and output 'out' */
952: /* in="V1+V1*age+age*age+V2", chain="age*age" */
953:
954: char *strloc;
955:
956: strcpy (out, in);
957: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
958: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
959: if(strloc != NULL){
960: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
961: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
962: /* strcpy (strloc, strloc +strlen(chain));*/
963: }
964: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
965: return out;
966: }
967:
968:
1.145 brouard 969: char *cutl(char *blocc, char *alocc, char *in, char occ)
970: {
1.187 brouard 971: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 972: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 973: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 974: If occ is not found blocc is null and alocc is equal to in. Returns blocc
975: */
1.160 brouard 976: char *s, *t;
1.145 brouard 977: t=in;s=in;
978: while ((*in != occ) && (*in != '\0')){
979: *alocc++ = *in++;
980: }
981: if( *in == occ){
982: *(alocc)='\0';
983: s=++in;
984: }
985:
986: if (s == t) {/* occ not found */
987: *(alocc-(in-s))='\0';
988: in=s;
989: }
990: while ( *in != '\0'){
991: *blocc++ = *in++;
992: }
993:
994: *blocc='\0';
995: return t;
996: }
1.137 brouard 997: char *cutv(char *blocc, char *alocc, char *in, char occ)
998: {
1.187 brouard 999: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1000: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1001: gives blocc="abcdef2ghi" and alocc="j".
1002: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1003: */
1004: char *s, *t;
1005: t=in;s=in;
1006: while (*in != '\0'){
1007: while( *in == occ){
1008: *blocc++ = *in++;
1009: s=in;
1010: }
1011: *blocc++ = *in++;
1012: }
1013: if (s == t) /* occ not found */
1014: *(blocc-(in-s))='\0';
1015: else
1016: *(blocc-(in-s)-1)='\0';
1017: in=s;
1018: while ( *in != '\0'){
1019: *alocc++ = *in++;
1020: }
1021:
1022: *alocc='\0';
1023: return s;
1024: }
1025:
1.126 brouard 1026: int nbocc(char *s, char occ)
1027: {
1028: int i,j=0;
1029: int lg=20;
1030: i=0;
1031: lg=strlen(s);
1032: for(i=0; i<= lg; i++) {
1033: if (s[i] == occ ) j++;
1034: }
1035: return j;
1036: }
1037:
1.137 brouard 1038: /* void cutv(char *u,char *v, char*t, char occ) */
1039: /* { */
1040: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1041: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1042: /* gives u="abcdef2ghi" and v="j" *\/ */
1043: /* int i,lg,j,p=0; */
1044: /* i=0; */
1045: /* lg=strlen(t); */
1046: /* for(j=0; j<=lg-1; j++) { */
1047: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1048: /* } */
1.126 brouard 1049:
1.137 brouard 1050: /* for(j=0; j<p; j++) { */
1051: /* (u[j] = t[j]); */
1052: /* } */
1053: /* u[p]='\0'; */
1.126 brouard 1054:
1.137 brouard 1055: /* for(j=0; j<= lg; j++) { */
1056: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1057: /* } */
1058: /* } */
1.126 brouard 1059:
1.160 brouard 1060: #ifdef _WIN32
1061: char * strsep(char **pp, const char *delim)
1062: {
1063: char *p, *q;
1064:
1065: if ((p = *pp) == NULL)
1066: return 0;
1067: if ((q = strpbrk (p, delim)) != NULL)
1068: {
1069: *pp = q + 1;
1070: *q = '\0';
1071: }
1072: else
1073: *pp = 0;
1074: return p;
1075: }
1076: #endif
1077:
1.126 brouard 1078: /********************** nrerror ********************/
1079:
1080: void nrerror(char error_text[])
1081: {
1082: fprintf(stderr,"ERREUR ...\n");
1083: fprintf(stderr,"%s\n",error_text);
1084: exit(EXIT_FAILURE);
1085: }
1086: /*********************** vector *******************/
1087: double *vector(int nl, int nh)
1088: {
1089: double *v;
1090: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1091: if (!v) nrerror("allocation failure in vector");
1092: return v-nl+NR_END;
1093: }
1094:
1095: /************************ free vector ******************/
1096: void free_vector(double*v, int nl, int nh)
1097: {
1098: free((FREE_ARG)(v+nl-NR_END));
1099: }
1100:
1101: /************************ivector *******************************/
1102: int *ivector(long nl,long nh)
1103: {
1104: int *v;
1105: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1106: if (!v) nrerror("allocation failure in ivector");
1107: return v-nl+NR_END;
1108: }
1109:
1110: /******************free ivector **************************/
1111: void free_ivector(int *v, long nl, long nh)
1112: {
1113: free((FREE_ARG)(v+nl-NR_END));
1114: }
1115:
1116: /************************lvector *******************************/
1117: long *lvector(long nl,long nh)
1118: {
1119: long *v;
1120: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1121: if (!v) nrerror("allocation failure in ivector");
1122: return v-nl+NR_END;
1123: }
1124:
1125: /******************free lvector **************************/
1126: void free_lvector(long *v, long nl, long nh)
1127: {
1128: free((FREE_ARG)(v+nl-NR_END));
1129: }
1130:
1131: /******************* imatrix *******************************/
1132: int **imatrix(long nrl, long nrh, long ncl, long nch)
1133: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1134: {
1135: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1136: int **m;
1137:
1138: /* allocate pointers to rows */
1139: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1140: if (!m) nrerror("allocation failure 1 in matrix()");
1141: m += NR_END;
1142: m -= nrl;
1143:
1144:
1145: /* allocate rows and set pointers to them */
1146: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1147: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1148: m[nrl] += NR_END;
1149: m[nrl] -= ncl;
1150:
1151: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1152:
1153: /* return pointer to array of pointers to rows */
1154: return m;
1155: }
1156:
1157: /****************** free_imatrix *************************/
1158: void free_imatrix(m,nrl,nrh,ncl,nch)
1159: int **m;
1160: long nch,ncl,nrh,nrl;
1161: /* free an int matrix allocated by imatrix() */
1162: {
1163: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1164: free((FREE_ARG) (m+nrl-NR_END));
1165: }
1166:
1167: /******************* matrix *******************************/
1168: double **matrix(long nrl, long nrh, long ncl, long nch)
1169: {
1170: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1171: double **m;
1172:
1173: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1174: if (!m) nrerror("allocation failure 1 in matrix()");
1175: m += NR_END;
1176: m -= nrl;
1177:
1178: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1179: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1180: m[nrl] += NR_END;
1181: m[nrl] -= ncl;
1182:
1183: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1184: return m;
1.145 brouard 1185: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1186: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1187: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1188: */
1189: }
1190:
1191: /*************************free matrix ************************/
1192: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1193: {
1194: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1195: free((FREE_ARG)(m+nrl-NR_END));
1196: }
1197:
1198: /******************* ma3x *******************************/
1199: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1200: {
1201: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1202: double ***m;
1203:
1204: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1205: if (!m) nrerror("allocation failure 1 in matrix()");
1206: m += NR_END;
1207: m -= nrl;
1208:
1209: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1210: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1211: m[nrl] += NR_END;
1212: m[nrl] -= ncl;
1213:
1214: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1215:
1216: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1217: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1218: m[nrl][ncl] += NR_END;
1219: m[nrl][ncl] -= nll;
1220: for (j=ncl+1; j<=nch; j++)
1221: m[nrl][j]=m[nrl][j-1]+nlay;
1222:
1223: for (i=nrl+1; i<=nrh; i++) {
1224: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1225: for (j=ncl+1; j<=nch; j++)
1226: m[i][j]=m[i][j-1]+nlay;
1227: }
1228: return m;
1229: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1230: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1231: */
1232: }
1233:
1234: /*************************free ma3x ************************/
1235: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1236: {
1237: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1238: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1239: free((FREE_ARG)(m+nrl-NR_END));
1240: }
1241:
1242: /*************** function subdirf ***********/
1243: char *subdirf(char fileres[])
1244: {
1245: /* Caution optionfilefiname is hidden */
1246: strcpy(tmpout,optionfilefiname);
1247: strcat(tmpout,"/"); /* Add to the right */
1248: strcat(tmpout,fileres);
1249: return tmpout;
1250: }
1251:
1252: /*************** function subdirf2 ***********/
1253: char *subdirf2(char fileres[], char *preop)
1254: {
1255:
1256: /* Caution optionfilefiname is hidden */
1257: strcpy(tmpout,optionfilefiname);
1258: strcat(tmpout,"/");
1259: strcat(tmpout,preop);
1260: strcat(tmpout,fileres);
1261: return tmpout;
1262: }
1263:
1264: /*************** function subdirf3 ***********/
1265: char *subdirf3(char fileres[], char *preop, char *preop2)
1266: {
1267:
1268: /* Caution optionfilefiname is hidden */
1269: strcpy(tmpout,optionfilefiname);
1270: strcat(tmpout,"/");
1271: strcat(tmpout,preop);
1272: strcat(tmpout,preop2);
1273: strcat(tmpout,fileres);
1274: return tmpout;
1275: }
1276:
1.162 brouard 1277: char *asc_diff_time(long time_sec, char ascdiff[])
1278: {
1279: long sec_left, days, hours, minutes;
1280: days = (time_sec) / (60*60*24);
1281: sec_left = (time_sec) % (60*60*24);
1282: hours = (sec_left) / (60*60) ;
1283: sec_left = (sec_left) %(60*60);
1284: minutes = (sec_left) /60;
1285: sec_left = (sec_left) % (60);
1286: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1287: return ascdiff;
1288: }
1289:
1.126 brouard 1290: /***************** f1dim *************************/
1291: extern int ncom;
1292: extern double *pcom,*xicom;
1293: extern double (*nrfunc)(double []);
1294:
1295: double f1dim(double x)
1296: {
1297: int j;
1298: double f;
1299: double *xt;
1300:
1301: xt=vector(1,ncom);
1302: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1303: f=(*nrfunc)(xt);
1304: free_vector(xt,1,ncom);
1305: return f;
1306: }
1307:
1308: /*****************brent *************************/
1309: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1310: {
1311: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1312: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1313: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1314: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1315: * returned function value.
1316: */
1.126 brouard 1317: int iter;
1318: double a,b,d,etemp;
1.159 brouard 1319: double fu=0,fv,fw,fx;
1.164 brouard 1320: double ftemp=0.;
1.126 brouard 1321: double p,q,r,tol1,tol2,u,v,w,x,xm;
1322: double e=0.0;
1323:
1324: a=(ax < cx ? ax : cx);
1325: b=(ax > cx ? ax : cx);
1326: x=w=v=bx;
1327: fw=fv=fx=(*f)(x);
1328: for (iter=1;iter<=ITMAX;iter++) {
1329: xm=0.5*(a+b);
1330: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1331: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1332: printf(".");fflush(stdout);
1333: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1334: #ifdef DEBUGBRENT
1.126 brouard 1335: 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);
1336: 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);
1337: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1338: #endif
1339: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1340: *xmin=x;
1341: return fx;
1342: }
1343: ftemp=fu;
1344: if (fabs(e) > tol1) {
1345: r=(x-w)*(fx-fv);
1346: q=(x-v)*(fx-fw);
1347: p=(x-v)*q-(x-w)*r;
1348: q=2.0*(q-r);
1349: if (q > 0.0) p = -p;
1350: q=fabs(q);
1351: etemp=e;
1352: e=d;
1353: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1354: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1355: else {
1356: d=p/q;
1357: u=x+d;
1358: if (u-a < tol2 || b-u < tol2)
1359: d=SIGN(tol1,xm-x);
1360: }
1361: } else {
1362: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1363: }
1364: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1365: fu=(*f)(u);
1366: if (fu <= fx) {
1367: if (u >= x) a=x; else b=x;
1368: SHFT(v,w,x,u)
1.183 brouard 1369: SHFT(fv,fw,fx,fu)
1370: } else {
1371: if (u < x) a=u; else b=u;
1372: if (fu <= fw || w == x) {
1373: v=w;
1374: w=u;
1375: fv=fw;
1376: fw=fu;
1377: } else if (fu <= fv || v == x || v == w) {
1378: v=u;
1379: fv=fu;
1380: }
1381: }
1.126 brouard 1382: }
1383: nrerror("Too many iterations in brent");
1384: *xmin=x;
1385: return fx;
1386: }
1387:
1388: /****************** mnbrak ***********************/
1389:
1390: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1391: double (*func)(double))
1.183 brouard 1392: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1393: the downhill direction (defined by the function as evaluated at the initial points) and returns
1394: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1395: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1396: */
1.126 brouard 1397: double ulim,u,r,q, dum;
1398: double fu;
1.187 brouard 1399:
1400: double scale=10.;
1401: int iterscale=0;
1402:
1403: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1404: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1405:
1406:
1407: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1408: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1409: /* *bx = *ax - (*ax - *bx)/scale; */
1410: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1411: /* } */
1412:
1.126 brouard 1413: if (*fb > *fa) {
1414: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1415: SHFT(dum,*fb,*fa,dum)
1416: }
1.126 brouard 1417: *cx=(*bx)+GOLD*(*bx-*ax);
1418: *fc=(*func)(*cx);
1.183 brouard 1419: #ifdef DEBUG
1420: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1421: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1422: #endif
1423: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1424: r=(*bx-*ax)*(*fb-*fc);
1425: q=(*bx-*cx)*(*fb-*fa);
1426: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1427: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1428: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1429: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1430: fu=(*func)(u);
1.163 brouard 1431: #ifdef DEBUG
1432: /* f(x)=A(x-u)**2+f(u) */
1433: double A, fparabu;
1434: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1435: fparabu= *fa - A*(*ax-u)*(*ax-u);
1436: 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);
1437: 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 1438: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1439: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1440: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1441: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1442: #endif
1.184 brouard 1443: #ifdef MNBRAKORIGINAL
1.183 brouard 1444: #else
1445: if (fu > *fc) {
1446: #ifdef DEBUG
1447: printf("mnbrak4 fu > fc \n");
1448: fprintf(ficlog, "mnbrak4 fu > fc\n");
1449: #endif
1450: /* 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 *\/ */
1451: /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\/ */
1452: dum=u; /* Shifting c and u */
1453: u = *cx;
1454: *cx = dum;
1455: dum = fu;
1456: fu = *fc;
1457: *fc =dum;
1458: } else { /* end */
1459: #ifdef DEBUG
1460: printf("mnbrak3 fu < fc \n");
1461: fprintf(ficlog, "mnbrak3 fu < fc\n");
1462: #endif
1463: dum=u; /* Shifting c and u */
1464: u = *cx;
1465: *cx = dum;
1466: dum = fu;
1467: fu = *fc;
1468: *fc =dum;
1469: }
1470: #endif
1.162 brouard 1471: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1472: #ifdef DEBUG
1473: printf("mnbrak2 u after c but before ulim\n");
1474: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1475: #endif
1.126 brouard 1476: fu=(*func)(u);
1477: if (fu < *fc) {
1.183 brouard 1478: #ifdef DEBUG
1479: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1480: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1481: #endif
1.126 brouard 1482: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1483: SHFT(*fb,*fc,fu,(*func)(u))
1484: }
1.162 brouard 1485: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1486: #ifdef DEBUG
1487: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1488: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1489: #endif
1.126 brouard 1490: u=ulim;
1491: fu=(*func)(u);
1.183 brouard 1492: } else { /* u could be left to b (if r > q parabola has a maximum) */
1493: #ifdef DEBUG
1494: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1495: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1496: #endif
1.126 brouard 1497: u=(*cx)+GOLD*(*cx-*bx);
1498: fu=(*func)(u);
1.183 brouard 1499: } /* end tests */
1.126 brouard 1500: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1501: SHFT(*fa,*fb,*fc,fu)
1502: #ifdef DEBUG
1503: 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);
1504: 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);
1505: #endif
1506: } /* 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 1507: }
1508:
1509: /*************** linmin ************************/
1.162 brouard 1510: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1511: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1512: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1513: the value of func at the returned location p . This is actually all accomplished by calling the
1514: routines mnbrak and brent .*/
1.126 brouard 1515: int ncom;
1516: double *pcom,*xicom;
1517: double (*nrfunc)(double []);
1518:
1519: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1520: {
1521: double brent(double ax, double bx, double cx,
1522: double (*f)(double), double tol, double *xmin);
1523: double f1dim(double x);
1524: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1525: double *fc, double (*func)(double));
1526: int j;
1527: double xx,xmin,bx,ax;
1528: double fx,fb,fa;
1.187 brouard 1529:
1530: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126 brouard 1531:
1532: ncom=n;
1533: pcom=vector(1,n);
1534: xicom=vector(1,n);
1535: nrfunc=func;
1536: for (j=1;j<=n;j++) {
1537: pcom[j]=p[j];
1538: xicom[j]=xi[j];
1539: }
1.187 brouard 1540:
1541: axs=0.0;
1542: xxss=1; /* 1 and using scale */
1543: xxs=1;
1544: do{
1545: ax=0.;
1546: xx= xxs;
1547: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1548: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1549: /* 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)) */
1550: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1551: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1552: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1553: /* 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]]*/
1554: if (fx != fx){
1555: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1556: 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);
1557: }
1558: }while(fx != fx);
1559:
1560: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1561: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1562: /* fmin = f(p[j] + xmin * xi[j]) */
1563: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1564: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1565: #ifdef DEBUG
1566: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1567: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1568: #endif
1.189 ! brouard 1569: /* printf("linmin end "); */
1.126 brouard 1570: for (j=1;j<=n;j++) {
1.188 brouard 1571: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187 brouard 1572: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189 ! brouard 1573: /* if(xxs <1.0) */
! 1574: /* 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 1575: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1576: }
1.189 ! brouard 1577: /* printf("\n"); */
! 1578: /* printf("Comparing last *frec(xmin)=%12.8f from Brent and frec(0.)=%12.8f \n", *fret, (*func)(p)); */
1.126 brouard 1579: free_vector(xicom,1,n);
1580: free_vector(pcom,1,n);
1581: }
1582:
1583:
1584: /*************** powell ************************/
1.162 brouard 1585: /*
1586: Minimization of a function func of n variables. Input consists of an initial starting point
1587: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1588: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1589: such that failure to decrease by more than this amount on one iteration signals doneness. On
1590: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1591: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1592: */
1.126 brouard 1593: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1594: double (*func)(double []))
1595: {
1596: void linmin(double p[], double xi[], int n, double *fret,
1597: double (*func)(double []));
1598: int i,ibig,j;
1599: double del,t,*pt,*ptt,*xit;
1.181 brouard 1600: double directest;
1.126 brouard 1601: double fp,fptt;
1602: double *xits;
1603: int niterf, itmp;
1604:
1605: pt=vector(1,n);
1606: ptt=vector(1,n);
1607: xit=vector(1,n);
1608: xits=vector(1,n);
1609: *fret=(*func)(p);
1610: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1611: rcurr_time = time(NULL);
1.126 brouard 1612: for (*iter=1;;++(*iter)) {
1.187 brouard 1613: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1614: ibig=0;
1615: del=0.0;
1.157 brouard 1616: rlast_time=rcurr_time;
1617: /* (void) gettimeofday(&curr_time,&tzp); */
1618: rcurr_time = time(NULL);
1619: curr_time = *localtime(&rcurr_time);
1620: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1621: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1622: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1623: for (i=1;i<=n;i++) {
1624: printf(" %d %.12f",i, p[i]);
1625: fprintf(ficlog," %d %.12lf",i, p[i]);
1626: fprintf(ficrespow," %.12lf", p[i]);
1627: }
1628: printf("\n");
1629: fprintf(ficlog,"\n");
1630: fprintf(ficrespow,"\n");fflush(ficrespow);
1631: if(*iter <=3){
1.157 brouard 1632: tml = *localtime(&rcurr_time);
1633: strcpy(strcurr,asctime(&tml));
1634: rforecast_time=rcurr_time;
1.126 brouard 1635: itmp = strlen(strcurr);
1636: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1637: strcurr[itmp-1]='\0';
1.162 brouard 1638: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1639: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1640: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1641: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1642: forecast_time = *localtime(&rforecast_time);
1643: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1644: itmp = strlen(strfor);
1645: if(strfor[itmp-1]=='\n')
1646: strfor[itmp-1]='\0';
1.157 brouard 1647: 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);
1648: 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 1649: }
1650: }
1.187 brouard 1651: for (i=1;i<=n;i++) { /* For each direction i */
1652: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1653: fptt=(*fret);
1654: #ifdef DEBUG
1.164 brouard 1655: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1656: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1657: #endif
1.187 brouard 1658: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1659: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1660: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1661: /* Outputs are fret(new point p) p is updated and xit rescaled */
1662: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1663: /* because that direction will be replaced unless the gain del is small */
1664: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1665: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1666: /* with the new direction. */
1.126 brouard 1667: del=fabs(fptt-(*fret));
1668: ibig=i;
1669: }
1670: #ifdef DEBUG
1671: printf("%d %.12e",i,(*fret));
1672: fprintf(ficlog,"%d %.12e",i,(*fret));
1673: for (j=1;j<=n;j++) {
1674: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1675: printf(" x(%d)=%.12e",j,xit[j]);
1676: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1677: }
1678: for(j=1;j<=n;j++) {
1.162 brouard 1679: printf(" p(%d)=%.12e",j,p[j]);
1680: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1681: }
1682: printf("\n");
1683: fprintf(ficlog,"\n");
1684: #endif
1.187 brouard 1685: } /* end loop on each direction i */
1686: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1687: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1688: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1689: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1690: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1691: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1692: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1693: /* decreased of more than 3.84 */
1694: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1695: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1696: /* By adding 10 parameters more the gain should be 18.31 */
1697:
1698: /* Starting the program with initial values given by a former maximization will simply change */
1699: /* the scales of the directions and the directions, because the are reset to canonical directions */
1700: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1701: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1702: #ifdef DEBUG
1703: int k[2],l;
1704: k[0]=1;
1705: k[1]=-1;
1706: printf("Max: %.12e",(*func)(p));
1707: fprintf(ficlog,"Max: %.12e",(*func)(p));
1708: for (j=1;j<=n;j++) {
1709: printf(" %.12e",p[j]);
1710: fprintf(ficlog," %.12e",p[j]);
1711: }
1712: printf("\n");
1713: fprintf(ficlog,"\n");
1714: for(l=0;l<=1;l++) {
1715: for (j=1;j<=n;j++) {
1716: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1717: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1718: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1719: }
1720: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1721: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1722: }
1723: #endif
1724:
1725:
1726: free_vector(xit,1,n);
1727: free_vector(xits,1,n);
1728: free_vector(ptt,1,n);
1729: free_vector(pt,1,n);
1730: return;
1731: }
1732: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1733: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1734: ptt[j]=2.0*p[j]-pt[j];
1735: xit[j]=p[j]-pt[j];
1736: pt[j]=p[j];
1737: }
1.181 brouard 1738: fptt=(*func)(ptt); /* f_3 */
1.161 brouard 1739: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1740: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1741: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1742: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1743: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1744: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1745: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1746: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1747: #ifdef NRCORIGINAL
1748: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1749: #else
1750: 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 1751: t= t- del*SQR(fp-fptt);
1.183 brouard 1752: #endif
1.182 brouard 1753: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1754: #ifdef DEBUG
1.181 brouard 1755: 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);
1756: 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 1757: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1758: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1759: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1760: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1761: 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);
1762: 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);
1763: #endif
1.183 brouard 1764: #ifdef POWELLORIGINAL
1765: if (t < 0.0) { /* Then we use it for new direction */
1766: #else
1.182 brouard 1767: if (directest*t < 0.0) { /* Contradiction between both tests */
1.184 brouard 1768: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.182 brouard 1769: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.184 brouard 1770: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.182 brouard 1771: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1772: }
1.181 brouard 1773: if (directest < 0.0) { /* Then we use it for new direction */
1774: #endif
1.187 brouard 1775: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.126 brouard 1776: for (j=1;j<=n;j++) {
1.181 brouard 1777: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1778: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1779: }
1.181 brouard 1780: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1781: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1782:
1.126 brouard 1783: #ifdef DEBUG
1.164 brouard 1784: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1785: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1786: for(j=1;j<=n;j++){
1787: printf(" %.12e",xit[j]);
1788: fprintf(ficlog," %.12e",xit[j]);
1789: }
1790: printf("\n");
1791: fprintf(ficlog,"\n");
1792: #endif
1.162 brouard 1793: } /* end of t negative */
1794: } /* end if (fptt < fp) */
1.126 brouard 1795: }
1796: }
1797:
1798: /**** Prevalence limit (stable or period prevalence) ****************/
1799:
1800: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1801: {
1802: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1803: matrix by transitions matrix until convergence is reached */
1.169 brouard 1804:
1.126 brouard 1805: int i, ii,j,k;
1806: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1807: /* double **matprod2(); */ /* test */
1.131 brouard 1808: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1809: double **newm;
1810: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1811:
1.126 brouard 1812: for (ii=1;ii<=nlstate+ndeath;ii++)
1813: for (j=1;j<=nlstate+ndeath;j++){
1814: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1815: }
1.169 brouard 1816:
1817: cov[1]=1.;
1818:
1819: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1820: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1821: newm=savm;
1822: /* Covariates have to be included here again */
1.138 brouard 1823: cov[2]=agefin;
1.187 brouard 1824: if(nagesqr==1)
1825: cov[3]= agefin*agefin;;
1.138 brouard 1826: for (k=1; k<=cptcovn;k++) {
1.187 brouard 1827: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1828: /*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 1829: }
1.186 brouard 1830: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 1831: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186 brouard 1832: for (k=1; k<=cptcovprod;k++) /* Useless */
1.187 brouard 1833: 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 1834:
1835: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1836: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1837: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1838: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1839: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1840: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1841:
1.126 brouard 1842: savm=oldm;
1843: oldm=newm;
1844: maxmax=0.;
1845: for(j=1;j<=nlstate;j++){
1846: min=1.;
1847: max=0.;
1848: for(i=1; i<=nlstate; i++) {
1849: sumnew=0;
1850: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1851: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1852: /*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 1853: max=FMAX(max,prlim[i][j]);
1854: min=FMIN(min,prlim[i][j]);
1855: }
1856: maxmin=max-min;
1857: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1858: } /* j loop */
1.126 brouard 1859: if(maxmax < ftolpl){
1860: return prlim;
1861: }
1.169 brouard 1862: } /* age loop */
1863: return prlim; /* should not reach here */
1.126 brouard 1864: }
1865:
1866: /*************** transition probabilities ***************/
1867:
1868: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1869: {
1.138 brouard 1870: /* According to parameters values stored in x and the covariate's values stored in cov,
1871: computes the probability to be observed in state j being in state i by appying the
1872: model to the ncovmodel covariates (including constant and age).
1873: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1874: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1875: ncth covariate in the global vector x is given by the formula:
1876: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1877: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1878: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1879: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1880: Outputs ps[i][j] the probability to be observed in j being in j according to
1881: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1882: */
1883: double s1, lnpijopii;
1.126 brouard 1884: /*double t34;*/
1.164 brouard 1885: int i,j, nc, ii, jj;
1.126 brouard 1886:
1887: for(i=1; i<= nlstate; i++){
1888: for(j=1; j<i;j++){
1.138 brouard 1889: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1890: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1891: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1892: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1893: }
1.138 brouard 1894: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1895: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1896: }
1897: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1898: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1899: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1900: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1901: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1902: }
1.138 brouard 1903: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1904: }
1905: }
1906:
1907: for(i=1; i<= nlstate; i++){
1908: s1=0;
1.131 brouard 1909: for(j=1; j<i; j++){
1.138 brouard 1910: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1911: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1912: }
1913: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1914: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1915: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1916: }
1.138 brouard 1917: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1918: ps[i][i]=1./(s1+1.);
1.138 brouard 1919: /* Computing other pijs */
1.126 brouard 1920: for(j=1; j<i; j++)
1921: ps[i][j]= exp(ps[i][j])*ps[i][i];
1922: for(j=i+1; j<=nlstate+ndeath; j++)
1923: ps[i][j]= exp(ps[i][j])*ps[i][i];
1924: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1925: } /* end i */
1926:
1927: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1928: for(jj=1; jj<= nlstate+ndeath; jj++){
1929: ps[ii][jj]=0;
1930: ps[ii][ii]=1;
1931: }
1932: }
1933:
1.145 brouard 1934:
1935: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1936: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1937: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1938: /* } */
1939: /* printf("\n "); */
1940: /* } */
1941: /* printf("\n ");printf("%lf ",cov[2]);*/
1942: /*
1.126 brouard 1943: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1944: goto end;*/
1945: return ps;
1946: }
1947:
1948: /**************** Product of 2 matrices ******************/
1949:
1.145 brouard 1950: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1951: {
1952: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1953: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1954: /* in, b, out are matrice of pointers which should have been initialized
1955: before: only the contents of out is modified. The function returns
1956: a pointer to pointers identical to out */
1.145 brouard 1957: int i, j, k;
1.126 brouard 1958: for(i=nrl; i<= nrh; i++)
1.145 brouard 1959: for(k=ncolol; k<=ncoloh; k++){
1960: out[i][k]=0.;
1961: for(j=ncl; j<=nch; j++)
1962: out[i][k] +=in[i][j]*b[j][k];
1963: }
1.126 brouard 1964: return out;
1965: }
1966:
1967:
1968: /************* Higher Matrix Product ***************/
1969:
1970: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1971: {
1972: /* Computes the transition matrix starting at age 'age' over
1973: 'nhstepm*hstepm*stepm' months (i.e. until
1974: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1975: nhstepm*hstepm matrices.
1976: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1977: (typically every 2 years instead of every month which is too big
1978: for the memory).
1979: Model is determined by parameters x and covariates have to be
1980: included manually here.
1981:
1982: */
1983:
1984: int i, j, d, h, k;
1.131 brouard 1985: double **out, cov[NCOVMAX+1];
1.126 brouard 1986: double **newm;
1.187 brouard 1987: double agexact;
1.126 brouard 1988:
1989: /* Hstepm could be zero and should return the unit matrix */
1990: for (i=1;i<=nlstate+ndeath;i++)
1991: for (j=1;j<=nlstate+ndeath;j++){
1992: oldm[i][j]=(i==j ? 1.0 : 0.0);
1993: po[i][j][0]=(i==j ? 1.0 : 0.0);
1994: }
1995: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1996: for(h=1; h <=nhstepm; h++){
1997: for(d=1; d <=hstepm; d++){
1998: newm=savm;
1999: /* Covariates have to be included here again */
2000: cov[1]=1.;
1.187 brouard 2001: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2002: cov[2]=agexact;
2003: if(nagesqr==1)
2004: cov[3]= agexact*agexact;
1.131 brouard 2005: for (k=1; k<=cptcovn;k++)
1.187 brouard 2006: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186 brouard 2007: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2008: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187 brouard 2009: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145 brouard 2010: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187 brouard 2011: 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 2012:
2013:
2014: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2015: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2016: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2017: pmij(pmmij,cov,ncovmodel,x,nlstate));
2018: savm=oldm;
2019: oldm=newm;
2020: }
2021: for(i=1; i<=nlstate+ndeath; i++)
2022: for(j=1;j<=nlstate+ndeath;j++) {
2023: po[i][j][h]=newm[i][j];
1.128 brouard 2024: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2025: }
1.128 brouard 2026: /*printf("h=%d ",h);*/
1.126 brouard 2027: } /* end h */
1.128 brouard 2028: /* printf("\n H=%d \n",h); */
1.126 brouard 2029: return po;
2030: }
2031:
1.162 brouard 2032: #ifdef NLOPT
2033: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2034: double fret;
2035: double *xt;
2036: int j;
2037: myfunc_data *d2 = (myfunc_data *) pd;
2038: /* xt = (p1-1); */
2039: xt=vector(1,n);
2040: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2041:
2042: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2043: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2044: printf("Function = %.12lf ",fret);
2045: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2046: printf("\n");
2047: free_vector(xt,1,n);
2048: return fret;
2049: }
2050: #endif
1.126 brouard 2051:
2052: /*************** log-likelihood *************/
2053: double func( double *x)
2054: {
2055: int i, ii, j, k, mi, d, kk;
1.131 brouard 2056: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2057: double **out;
2058: double sw; /* Sum of weights */
2059: double lli; /* Individual log likelihood */
2060: int s1, s2;
2061: double bbh, survp;
2062: long ipmx;
1.187 brouard 2063: double agexact;
1.126 brouard 2064: /*extern weight */
2065: /* We are differentiating ll according to initial status */
2066: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2067: /*for(i=1;i<imx;i++)
2068: printf(" %d\n",s[4][i]);
2069: */
1.162 brouard 2070:
2071: ++countcallfunc;
2072:
1.126 brouard 2073: cov[1]=1.;
2074:
2075: for(k=1; k<=nlstate; k++) ll[k]=0.;
2076:
2077: if(mle==1){
2078: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2079: /* Computes the values of the ncovmodel covariates of the model
2080: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2081: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2082: to be observed in j being in i according to the model.
2083: */
1.145 brouard 2084: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2085: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2086: }
1.137 brouard 2087: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2088: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2089: has been calculated etc */
1.126 brouard 2090: for(mi=1; mi<= wav[i]-1; mi++){
2091: for (ii=1;ii<=nlstate+ndeath;ii++)
2092: for (j=1;j<=nlstate+ndeath;j++){
2093: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2094: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2095: }
2096: for(d=0; d<dh[mi][i]; d++){
2097: newm=savm;
1.187 brouard 2098: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2099: cov[2]=agexact;
2100: if(nagesqr==1)
2101: cov[3]= agexact*agexact;
1.126 brouard 2102: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2103: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2104: }
2105: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2106: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2107: savm=oldm;
2108: oldm=newm;
2109: } /* end mult */
2110:
2111: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2112: /* But now since version 0.9 we anticipate for bias at large stepm.
2113: * If stepm is larger than one month (smallest stepm) and if the exact delay
2114: * (in months) between two waves is not a multiple of stepm, we rounded to
2115: * the nearest (and in case of equal distance, to the lowest) interval but now
2116: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2117: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2118: * probability in order to take into account the bias as a fraction of the way
2119: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2120: * -stepm/2 to stepm/2 .
2121: * For stepm=1 the results are the same as for previous versions of Imach.
2122: * For stepm > 1 the results are less biased than in previous versions.
2123: */
2124: s1=s[mw[mi][i]][i];
2125: s2=s[mw[mi+1][i]][i];
2126: bbh=(double)bh[mi][i]/(double)stepm;
2127: /* bias bh is positive if real duration
2128: * is higher than the multiple of stepm and negative otherwise.
2129: */
2130: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2131: if( s2 > nlstate){
2132: /* i.e. if s2 is a death state and if the date of death is known
2133: then the contribution to the likelihood is the probability to
2134: die between last step unit time and current step unit time,
2135: which is also equal to probability to die before dh
2136: minus probability to die before dh-stepm .
2137: In version up to 0.92 likelihood was computed
2138: as if date of death was unknown. Death was treated as any other
2139: health state: the date of the interview describes the actual state
2140: and not the date of a change in health state. The former idea was
2141: to consider that at each interview the state was recorded
2142: (healthy, disable or death) and IMaCh was corrected; but when we
2143: introduced the exact date of death then we should have modified
2144: the contribution of an exact death to the likelihood. This new
2145: contribution is smaller and very dependent of the step unit
2146: stepm. It is no more the probability to die between last interview
2147: and month of death but the probability to survive from last
2148: interview up to one month before death multiplied by the
2149: probability to die within a month. Thanks to Chris
2150: Jackson for correcting this bug. Former versions increased
2151: mortality artificially. The bad side is that we add another loop
2152: which slows down the processing. The difference can be up to 10%
2153: lower mortality.
2154: */
1.183 brouard 2155: /* If, at the beginning of the maximization mostly, the
2156: cumulative probability or probability to be dead is
2157: constant (ie = 1) over time d, the difference is equal to
2158: 0. out[s1][3] = savm[s1][3]: probability, being at state
2159: s1 at precedent wave, to be dead a month before current
2160: wave is equal to probability, being at state s1 at
2161: precedent wave, to be dead at mont of the current
2162: wave. Then the observed probability (that this person died)
2163: is null according to current estimated parameter. In fact,
2164: it should be very low but not zero otherwise the log go to
2165: infinity.
2166: */
2167: /* #ifdef INFINITYORIGINAL */
2168: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2169: /* #else */
2170: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2171: /* lli=log(mytinydouble); */
2172: /* else */
2173: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2174: /* #endif */
2175: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2176:
2177: } else if (s2==-2) {
2178: for (j=1,survp=0. ; j<=nlstate; j++)
2179: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2180: /*survp += out[s1][j]; */
2181: lli= log(survp);
2182: }
2183:
2184: else if (s2==-4) {
2185: for (j=3,survp=0. ; j<=nlstate; j++)
2186: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2187: lli= log(survp);
2188: }
2189:
2190: else if (s2==-5) {
2191: for (j=1,survp=0. ; j<=2; j++)
2192: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2193: lli= log(survp);
2194: }
2195:
2196: else{
2197: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2198: /* 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 */
2199: }
2200: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2201: /*if(lli ==000.0)*/
2202: /*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); */
2203: ipmx +=1;
2204: sw += weight[i];
2205: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2206: /* if (lli < log(mytinydouble)){ */
2207: /* 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); */
2208: /* 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]); */
2209: /* } */
1.126 brouard 2210: } /* end of wave */
2211: } /* end of individual */
2212: } else if(mle==2){
2213: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2214: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2215: for(mi=1; mi<= wav[i]-1; mi++){
2216: for (ii=1;ii<=nlstate+ndeath;ii++)
2217: for (j=1;j<=nlstate+ndeath;j++){
2218: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2219: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2220: }
2221: for(d=0; d<=dh[mi][i]; d++){
2222: newm=savm;
1.187 brouard 2223: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2224: cov[2]=agexact;
2225: if(nagesqr==1)
2226: cov[3]= agexact*agexact;
1.126 brouard 2227: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2228: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2229: }
2230: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2231: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2232: savm=oldm;
2233: oldm=newm;
2234: } /* end mult */
2235:
2236: s1=s[mw[mi][i]][i];
2237: s2=s[mw[mi+1][i]][i];
2238: bbh=(double)bh[mi][i]/(double)stepm;
2239: 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 */
2240: ipmx +=1;
2241: sw += weight[i];
2242: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2243: } /* end of wave */
2244: } /* end of individual */
2245: } else if(mle==3){ /* exponential inter-extrapolation */
2246: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2247: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2248: for(mi=1; mi<= wav[i]-1; mi++){
2249: for (ii=1;ii<=nlstate+ndeath;ii++)
2250: for (j=1;j<=nlstate+ndeath;j++){
2251: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2252: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2253: }
2254: for(d=0; d<dh[mi][i]; d++){
2255: newm=savm;
1.187 brouard 2256: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2257: cov[2]=agexact;
2258: if(nagesqr==1)
2259: cov[3]= agexact*agexact;
1.126 brouard 2260: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2261: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2262: }
2263: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2264: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2265: savm=oldm;
2266: oldm=newm;
2267: } /* end mult */
2268:
2269: s1=s[mw[mi][i]][i];
2270: s2=s[mw[mi+1][i]][i];
2271: bbh=(double)bh[mi][i]/(double)stepm;
2272: 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 */
2273: ipmx +=1;
2274: sw += weight[i];
2275: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2276: } /* end of wave */
2277: } /* end of individual */
2278: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2279: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2280: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2281: for(mi=1; mi<= wav[i]-1; mi++){
2282: for (ii=1;ii<=nlstate+ndeath;ii++)
2283: for (j=1;j<=nlstate+ndeath;j++){
2284: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2285: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2286: }
2287: for(d=0; d<dh[mi][i]; d++){
2288: newm=savm;
1.187 brouard 2289: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2290: cov[2]=agexact;
2291: if(nagesqr==1)
2292: cov[3]= agexact*agexact;
1.126 brouard 2293: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2294: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2295: }
2296:
2297: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2298: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2299: savm=oldm;
2300: oldm=newm;
2301: } /* end mult */
2302:
2303: s1=s[mw[mi][i]][i];
2304: s2=s[mw[mi+1][i]][i];
2305: if( s2 > nlstate){
2306: lli=log(out[s1][s2] - savm[s1][s2]);
2307: }else{
2308: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2309: }
2310: ipmx +=1;
2311: sw += weight[i];
2312: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2313: /* 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]); */
2314: } /* end of wave */
2315: } /* end of individual */
2316: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2317: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2318: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2319: for(mi=1; mi<= wav[i]-1; mi++){
2320: for (ii=1;ii<=nlstate+ndeath;ii++)
2321: for (j=1;j<=nlstate+ndeath;j++){
2322: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2323: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2324: }
2325: for(d=0; d<dh[mi][i]; d++){
2326: newm=savm;
1.187 brouard 2327: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2328: cov[2]=agexact;
2329: if(nagesqr==1)
2330: cov[3]= agexact*agexact;
1.126 brouard 2331: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2332: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2333: }
2334:
2335: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2336: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2337: savm=oldm;
2338: oldm=newm;
2339: } /* end mult */
2340:
2341: s1=s[mw[mi][i]][i];
2342: s2=s[mw[mi+1][i]][i];
2343: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2344: ipmx +=1;
2345: sw += weight[i];
2346: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2347: /*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]);*/
2348: } /* end of wave */
2349: } /* end of individual */
2350: } /* End of if */
2351: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2352: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2353: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2354: return -l;
2355: }
2356:
2357: /*************** log-likelihood *************/
2358: double funcone( double *x)
2359: {
2360: /* Same as likeli but slower because of a lot of printf and if */
2361: int i, ii, j, k, mi, d, kk;
1.131 brouard 2362: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2363: double **out;
2364: double lli; /* Individual log likelihood */
2365: double llt;
2366: int s1, s2;
2367: double bbh, survp;
1.187 brouard 2368: double agexact;
1.126 brouard 2369: /*extern weight */
2370: /* We are differentiating ll according to initial status */
2371: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2372: /*for(i=1;i<imx;i++)
2373: printf(" %d\n",s[4][i]);
2374: */
2375: cov[1]=1.;
2376:
2377: for(k=1; k<=nlstate; k++) ll[k]=0.;
2378:
2379: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2380: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2381: for(mi=1; mi<= wav[i]-1; mi++){
2382: for (ii=1;ii<=nlstate+ndeath;ii++)
2383: for (j=1;j<=nlstate+ndeath;j++){
2384: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2385: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2386: }
2387: for(d=0; d<dh[mi][i]; d++){
2388: newm=savm;
1.187 brouard 2389: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2390: cov[2]=agexact;
2391: if(nagesqr==1)
2392: cov[3]= agexact*agexact;
1.126 brouard 2393: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2394: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2395: }
1.187 brouard 2396:
1.145 brouard 2397: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2398: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2399: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2400: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2401: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2402: savm=oldm;
2403: oldm=newm;
2404: } /* end mult */
2405:
2406: s1=s[mw[mi][i]][i];
2407: s2=s[mw[mi+1][i]][i];
2408: bbh=(double)bh[mi][i]/(double)stepm;
2409: /* bias is positive if real duration
2410: * is higher than the multiple of stepm and negative otherwise.
2411: */
2412: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2413: lli=log(out[s1][s2] - savm[s1][s2]);
2414: } else if (s2==-2) {
2415: for (j=1,survp=0. ; j<=nlstate; j++)
2416: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2417: lli= log(survp);
2418: }else if (mle==1){
2419: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2420: } else if(mle==2){
2421: 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 */
2422: } else if(mle==3){ /* exponential inter-extrapolation */
2423: 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 */
2424: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2425: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2426: } else{ /* mle=0 back to 1 */
2427: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2428: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2429: } /* End of if */
2430: ipmx +=1;
2431: sw += weight[i];
2432: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2433: /*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 2434: if(globpr){
1.141 brouard 2435: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2436: %11.6f %11.6f %11.6f ", \
2437: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2438: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2439: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2440: llt +=ll[k]*gipmx/gsw;
2441: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2442: }
2443: fprintf(ficresilk," %10.6f\n", -llt);
2444: }
2445: } /* end of wave */
2446: } /* end of individual */
2447: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2448: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2449: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2450: if(globpr==0){ /* First time we count the contributions and weights */
2451: gipmx=ipmx;
2452: gsw=sw;
2453: }
2454: return -l;
2455: }
2456:
2457:
2458: /*************** function likelione ***********/
2459: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2460: {
2461: /* This routine should help understanding what is done with
2462: the selection of individuals/waves and
2463: to check the exact contribution to the likelihood.
2464: Plotting could be done.
2465: */
2466: int k;
2467:
2468: if(*globpri !=0){ /* Just counts and sums, no printings */
2469: strcpy(fileresilk,"ilk");
2470: strcat(fileresilk,fileres);
2471: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2472: printf("Problem with resultfile: %s\n", fileresilk);
2473: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2474: }
2475: 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");
2476: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2477: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2478: for(k=1; k<=nlstate; k++)
2479: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2480: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2481: }
2482:
2483: *fretone=(*funcone)(p);
2484: if(*globpri !=0){
2485: fclose(ficresilk);
2486: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2487: fflush(fichtm);
2488: }
2489: return;
2490: }
2491:
2492:
2493: /*********** Maximum Likelihood Estimation ***************/
2494:
2495: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2496: {
1.165 brouard 2497: int i,j, iter=0;
1.126 brouard 2498: double **xi;
2499: double fret;
2500: double fretone; /* Only one call to likelihood */
2501: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2502:
2503: #ifdef NLOPT
2504: int creturn;
2505: nlopt_opt opt;
2506: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2507: double *lb;
2508: double minf; /* the minimum objective value, upon return */
2509: double * p1; /* Shifted parameters from 0 instead of 1 */
2510: myfunc_data dinst, *d = &dinst;
2511: #endif
2512:
2513:
1.126 brouard 2514: xi=matrix(1,npar,1,npar);
2515: for (i=1;i<=npar;i++)
2516: for (j=1;j<=npar;j++)
2517: xi[i][j]=(i==j ? 1.0 : 0.0);
2518: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2519: strcpy(filerespow,"pow");
2520: strcat(filerespow,fileres);
2521: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2522: printf("Problem with resultfile: %s\n", filerespow);
2523: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2524: }
2525: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2526: for (i=1;i<=nlstate;i++)
2527: for(j=1;j<=nlstate+ndeath;j++)
2528: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2529: fprintf(ficrespow,"\n");
1.162 brouard 2530: #ifdef POWELL
1.126 brouard 2531: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2532: #endif
1.126 brouard 2533:
1.162 brouard 2534: #ifdef NLOPT
2535: #ifdef NEWUOA
2536: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2537: #else
2538: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2539: #endif
2540: lb=vector(0,npar-1);
2541: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2542: nlopt_set_lower_bounds(opt, lb);
2543: nlopt_set_initial_step1(opt, 0.1);
2544:
2545: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2546: d->function = func;
2547: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2548: nlopt_set_min_objective(opt, myfunc, d);
2549: nlopt_set_xtol_rel(opt, ftol);
2550: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2551: printf("nlopt failed! %d\n",creturn);
2552: }
2553: else {
2554: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2555: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2556: iter=1; /* not equal */
2557: }
2558: nlopt_destroy(opt);
2559: #endif
1.126 brouard 2560: free_matrix(xi,1,npar,1,npar);
2561: fclose(ficrespow);
1.180 brouard 2562: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2563: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2564: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2565:
2566: }
2567:
2568: /**** Computes Hessian and covariance matrix ***/
2569: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2570: {
2571: double **a,**y,*x,pd;
2572: double **hess;
1.164 brouard 2573: int i, j;
1.126 brouard 2574: int *indx;
2575:
2576: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2577: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2578: void lubksb(double **a, int npar, int *indx, double b[]) ;
2579: void ludcmp(double **a, int npar, int *indx, double *d) ;
2580: double gompertz(double p[]);
2581: hess=matrix(1,npar,1,npar);
2582:
2583: printf("\nCalculation of the hessian matrix. Wait...\n");
2584: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2585: for (i=1;i<=npar;i++){
2586: printf("%d",i);fflush(stdout);
2587: fprintf(ficlog,"%d",i);fflush(ficlog);
2588:
2589: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2590:
2591: /* printf(" %f ",p[i]);
2592: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2593: }
2594:
2595: for (i=1;i<=npar;i++) {
2596: for (j=1;j<=npar;j++) {
2597: if (j>i) {
2598: printf(".%d%d",i,j);fflush(stdout);
2599: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2600: hess[i][j]=hessij(p,delti,i,j,func,npar);
2601:
2602: hess[j][i]=hess[i][j];
2603: /*printf(" %lf ",hess[i][j]);*/
2604: }
2605: }
2606: }
2607: printf("\n");
2608: fprintf(ficlog,"\n");
2609:
2610: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2611: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2612:
2613: a=matrix(1,npar,1,npar);
2614: y=matrix(1,npar,1,npar);
2615: x=vector(1,npar);
2616: indx=ivector(1,npar);
2617: for (i=1;i<=npar;i++)
2618: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2619: ludcmp(a,npar,indx,&pd);
2620:
2621: for (j=1;j<=npar;j++) {
2622: for (i=1;i<=npar;i++) x[i]=0;
2623: x[j]=1;
2624: lubksb(a,npar,indx,x);
2625: for (i=1;i<=npar;i++){
2626: matcov[i][j]=x[i];
2627: }
2628: }
2629:
2630: printf("\n#Hessian matrix#\n");
2631: fprintf(ficlog,"\n#Hessian matrix#\n");
2632: for (i=1;i<=npar;i++) {
2633: for (j=1;j<=npar;j++) {
2634: printf("%.3e ",hess[i][j]);
2635: fprintf(ficlog,"%.3e ",hess[i][j]);
2636: }
2637: printf("\n");
2638: fprintf(ficlog,"\n");
2639: }
2640:
2641: /* Recompute Inverse */
2642: for (i=1;i<=npar;i++)
2643: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2644: ludcmp(a,npar,indx,&pd);
2645:
2646: /* printf("\n#Hessian matrix recomputed#\n");
2647:
2648: for (j=1;j<=npar;j++) {
2649: for (i=1;i<=npar;i++) x[i]=0;
2650: x[j]=1;
2651: lubksb(a,npar,indx,x);
2652: for (i=1;i<=npar;i++){
2653: y[i][j]=x[i];
2654: printf("%.3e ",y[i][j]);
2655: fprintf(ficlog,"%.3e ",y[i][j]);
2656: }
2657: printf("\n");
2658: fprintf(ficlog,"\n");
2659: }
2660: */
2661:
2662: free_matrix(a,1,npar,1,npar);
2663: free_matrix(y,1,npar,1,npar);
2664: free_vector(x,1,npar);
2665: free_ivector(indx,1,npar);
2666: free_matrix(hess,1,npar,1,npar);
2667:
2668:
2669: }
2670:
2671: /*************** hessian matrix ****************/
2672: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2673: {
2674: int i;
2675: int l=1, lmax=20;
2676: double k1,k2;
1.132 brouard 2677: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2678: double res;
2679: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2680: double fx;
2681: int k=0,kmax=10;
2682: double l1;
2683:
2684: fx=func(x);
2685: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2686: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2687: l1=pow(10,l);
2688: delts=delt;
2689: for(k=1 ; k <kmax; k=k+1){
2690: delt = delta*(l1*k);
2691: p2[theta]=x[theta] +delt;
1.145 brouard 2692: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2693: p2[theta]=x[theta]-delt;
2694: k2=func(p2)-fx;
2695: /*res= (k1-2.0*fx+k2)/delt/delt; */
2696: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2697:
1.132 brouard 2698: #ifdef DEBUGHESS
1.126 brouard 2699: 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);
2700: 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);
2701: #endif
2702: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2703: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2704: k=kmax;
2705: }
2706: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2707: k=kmax; l=lmax*10;
1.126 brouard 2708: }
2709: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2710: delts=delt;
2711: }
2712: }
2713: }
2714: delti[theta]=delts;
2715: return res;
2716:
2717: }
2718:
2719: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2720: {
2721: int i;
1.164 brouard 2722: int l=1, lmax=20;
1.126 brouard 2723: double k1,k2,k3,k4,res,fx;
1.132 brouard 2724: double p2[MAXPARM+1];
1.126 brouard 2725: int k;
2726:
2727: fx=func(x);
2728: for (k=1; k<=2; k++) {
2729: for (i=1;i<=npar;i++) p2[i]=x[i];
2730: p2[thetai]=x[thetai]+delti[thetai]/k;
2731: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2732: k1=func(p2)-fx;
2733:
2734: p2[thetai]=x[thetai]+delti[thetai]/k;
2735: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2736: k2=func(p2)-fx;
2737:
2738: p2[thetai]=x[thetai]-delti[thetai]/k;
2739: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2740: k3=func(p2)-fx;
2741:
2742: p2[thetai]=x[thetai]-delti[thetai]/k;
2743: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2744: k4=func(p2)-fx;
2745: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2746: #ifdef DEBUG
2747: 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);
2748: 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);
2749: #endif
2750: }
2751: return res;
2752: }
2753:
2754: /************** Inverse of matrix **************/
2755: void ludcmp(double **a, int n, int *indx, double *d)
2756: {
2757: int i,imax,j,k;
2758: double big,dum,sum,temp;
2759: double *vv;
2760:
2761: vv=vector(1,n);
2762: *d=1.0;
2763: for (i=1;i<=n;i++) {
2764: big=0.0;
2765: for (j=1;j<=n;j++)
2766: if ((temp=fabs(a[i][j])) > big) big=temp;
2767: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2768: vv[i]=1.0/big;
2769: }
2770: for (j=1;j<=n;j++) {
2771: for (i=1;i<j;i++) {
2772: sum=a[i][j];
2773: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2774: a[i][j]=sum;
2775: }
2776: big=0.0;
2777: for (i=j;i<=n;i++) {
2778: sum=a[i][j];
2779: for (k=1;k<j;k++)
2780: sum -= a[i][k]*a[k][j];
2781: a[i][j]=sum;
2782: if ( (dum=vv[i]*fabs(sum)) >= big) {
2783: big=dum;
2784: imax=i;
2785: }
2786: }
2787: if (j != imax) {
2788: for (k=1;k<=n;k++) {
2789: dum=a[imax][k];
2790: a[imax][k]=a[j][k];
2791: a[j][k]=dum;
2792: }
2793: *d = -(*d);
2794: vv[imax]=vv[j];
2795: }
2796: indx[j]=imax;
2797: if (a[j][j] == 0.0) a[j][j]=TINY;
2798: if (j != n) {
2799: dum=1.0/(a[j][j]);
2800: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2801: }
2802: }
2803: free_vector(vv,1,n); /* Doesn't work */
2804: ;
2805: }
2806:
2807: void lubksb(double **a, int n, int *indx, double b[])
2808: {
2809: int i,ii=0,ip,j;
2810: double sum;
2811:
2812: for (i=1;i<=n;i++) {
2813: ip=indx[i];
2814: sum=b[ip];
2815: b[ip]=b[i];
2816: if (ii)
2817: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2818: else if (sum) ii=i;
2819: b[i]=sum;
2820: }
2821: for (i=n;i>=1;i--) {
2822: sum=b[i];
2823: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2824: b[i]=sum/a[i][i];
2825: }
2826: }
2827:
2828: void pstamp(FILE *fichier)
2829: {
2830: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2831: }
2832:
2833: /************ Frequencies ********************/
2834: 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[])
2835: { /* Some frequencies */
2836:
1.164 brouard 2837: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2838: int first;
2839: double ***freq; /* Frequencies */
2840: double *pp, **prop;
2841: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2842: char fileresp[FILENAMELENGTH];
2843:
2844: pp=vector(1,nlstate);
2845: prop=matrix(1,nlstate,iagemin,iagemax+3);
2846: strcpy(fileresp,"p");
2847: strcat(fileresp,fileres);
2848: if((ficresp=fopen(fileresp,"w"))==NULL) {
2849: printf("Problem with prevalence resultfile: %s\n", fileresp);
2850: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2851: exit(0);
2852: }
2853: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2854: j1=0;
2855:
2856: j=cptcoveff;
2857: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2858:
2859: first=1;
2860:
1.169 brouard 2861: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2862: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2863: /* j1++; */
1.145 brouard 2864: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2865: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2866: scanf("%d", i);*/
2867: for (i=-5; i<=nlstate+ndeath; i++)
2868: for (jk=-5; jk<=nlstate+ndeath; jk++)
2869: for(m=iagemin; m <= iagemax+3; m++)
2870: freq[i][jk][m]=0;
1.143 brouard 2871:
2872: for (i=1; i<=nlstate; i++)
2873: for(m=iagemin; m <= iagemax+3; m++)
2874: prop[i][m]=0;
1.126 brouard 2875:
2876: dateintsum=0;
2877: k2cpt=0;
2878: for (i=1; i<=imx; i++) {
2879: bool=1;
1.144 brouard 2880: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2881: for (z1=1; z1<=cptcoveff; z1++)
2882: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2883: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2884: bool=0;
1.145 brouard 2885: /* 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",
2886: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2887: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2888: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2889: }
1.126 brouard 2890: }
1.144 brouard 2891:
1.126 brouard 2892: if (bool==1){
2893: for(m=firstpass; m<=lastpass; m++){
2894: k2=anint[m][i]+(mint[m][i]/12.);
2895: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2896: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2897: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2898: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2899: if (m<lastpass) {
2900: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2901: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2902: }
2903:
2904: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2905: dateintsum=dateintsum+k2;
2906: k2cpt++;
2907: }
2908: /*}*/
2909: }
2910: }
1.145 brouard 2911: } /* end i */
1.126 brouard 2912:
2913: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2914: pstamp(ficresp);
2915: if (cptcovn>0) {
2916: fprintf(ficresp, "\n#********** Variable ");
2917: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2918: fprintf(ficresp, "**********\n#");
1.143 brouard 2919: fprintf(ficlog, "\n#********** Variable ");
2920: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2921: fprintf(ficlog, "**********\n#");
1.126 brouard 2922: }
2923: for(i=1; i<=nlstate;i++)
2924: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2925: fprintf(ficresp, "\n");
2926:
2927: for(i=iagemin; i <= iagemax+3; i++){
2928: if(i==iagemax+3){
2929: fprintf(ficlog,"Total");
2930: }else{
2931: if(first==1){
2932: first=0;
2933: printf("See log file for details...\n");
2934: }
2935: fprintf(ficlog,"Age %d", i);
2936: }
2937: for(jk=1; jk <=nlstate ; jk++){
2938: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2939: pp[jk] += freq[jk][m][i];
2940: }
2941: for(jk=1; jk <=nlstate ; jk++){
2942: for(m=-1, pos=0; m <=0 ; m++)
2943: pos += freq[jk][m][i];
2944: if(pp[jk]>=1.e-10){
2945: if(first==1){
1.132 brouard 2946: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2947: }
2948: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2949: }else{
2950: if(first==1)
2951: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2952: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2953: }
2954: }
2955:
2956: for(jk=1; jk <=nlstate ; jk++){
2957: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2958: pp[jk] += freq[jk][m][i];
2959: }
2960: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2961: pos += pp[jk];
2962: posprop += prop[jk][i];
2963: }
2964: for(jk=1; jk <=nlstate ; jk++){
2965: if(pos>=1.e-5){
2966: if(first==1)
2967: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2968: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2969: }else{
2970: if(first==1)
2971: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2972: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2973: }
2974: if( i <= iagemax){
2975: if(pos>=1.e-5){
2976: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2977: /*probs[i][jk][j1]= pp[jk]/pos;*/
2978: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2979: }
2980: else
2981: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2982: }
2983: }
2984:
2985: for(jk=-1; jk <=nlstate+ndeath; jk++)
2986: for(m=-1; m <=nlstate+ndeath; m++)
2987: if(freq[jk][m][i] !=0 ) {
2988: if(first==1)
2989: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2990: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2991: }
2992: if(i <= iagemax)
2993: fprintf(ficresp,"\n");
2994: if(first==1)
2995: printf("Others in log...\n");
2996: fprintf(ficlog,"\n");
2997: }
1.145 brouard 2998: /*}*/
1.126 brouard 2999: }
3000: dateintmean=dateintsum/k2cpt;
3001:
3002: fclose(ficresp);
3003: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3004: free_vector(pp,1,nlstate);
3005: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3006: /* End of Freq */
3007: }
3008:
3009: /************ Prevalence ********************/
3010: 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)
3011: {
3012: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3013: in each health status at the date of interview (if between dateprev1 and dateprev2).
3014: We still use firstpass and lastpass as another selection.
3015: */
3016:
1.164 brouard 3017: int i, m, jk, j1, bool, z1,j;
3018:
3019: double **prop;
3020: double posprop;
1.126 brouard 3021: double y2; /* in fractional years */
3022: int iagemin, iagemax;
1.145 brouard 3023: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3024:
3025: iagemin= (int) agemin;
3026: iagemax= (int) agemax;
3027: /*pp=vector(1,nlstate);*/
3028: prop=matrix(1,nlstate,iagemin,iagemax+3);
3029: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3030: j1=0;
3031:
1.145 brouard 3032: /*j=cptcoveff;*/
1.126 brouard 3033: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3034:
1.145 brouard 3035: first=1;
3036: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3037: /*for(i1=1; i1<=ncodemax[k1];i1++){
3038: j1++;*/
1.126 brouard 3039:
3040: for (i=1; i<=nlstate; i++)
3041: for(m=iagemin; m <= iagemax+3; m++)
3042: prop[i][m]=0.0;
3043:
3044: for (i=1; i<=imx; i++) { /* Each individual */
3045: bool=1;
3046: if (cptcovn>0) {
3047: for (z1=1; z1<=cptcoveff; z1++)
3048: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
3049: bool=0;
3050: }
3051: if (bool==1) {
3052: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3053: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3054: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3055: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3056: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3057: 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);
3058: if (s[m][i]>0 && s[m][i]<=nlstate) {
3059: /*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]]);*/
3060: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3061: prop[s[m][i]][iagemax+3] += weight[i];
3062: }
3063: }
3064: } /* end selection of waves */
3065: }
3066: }
3067: for(i=iagemin; i <= iagemax+3; i++){
3068: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3069: posprop += prop[jk][i];
3070: }
1.145 brouard 3071:
1.126 brouard 3072: for(jk=1; jk <=nlstate ; jk++){
3073: if( i <= iagemax){
3074: if(posprop>=1.e-5){
3075: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3076: } else{
3077: if(first==1){
3078: first=0;
3079: 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]);
3080: }
3081: }
1.126 brouard 3082: }
3083: }/* end jk */
3084: }/* end i */
1.145 brouard 3085: /*} *//* end i1 */
3086: } /* end j1 */
1.126 brouard 3087:
3088: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3089: /*free_vector(pp,1,nlstate);*/
3090: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3091: } /* End of prevalence */
3092:
3093: /************* Waves Concatenation ***************/
3094:
3095: 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)
3096: {
3097: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3098: Death is a valid wave (if date is known).
3099: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3100: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3101: and mw[mi+1][i]. dh depends on stepm.
3102: */
3103:
3104: int i, mi, m;
3105: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3106: double sum=0., jmean=0.;*/
3107: int first;
3108: int j, k=0,jk, ju, jl;
3109: double sum=0.;
3110: first=0;
1.164 brouard 3111: jmin=100000;
1.126 brouard 3112: jmax=-1;
3113: jmean=0.;
3114: for(i=1; i<=imx; i++){
3115: mi=0;
3116: m=firstpass;
3117: while(s[m][i] <= nlstate){
3118: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3119: mw[++mi][i]=m;
3120: if(m >=lastpass)
3121: break;
3122: else
3123: m++;
3124: }/* end while */
3125: if (s[m][i] > nlstate){
3126: mi++; /* Death is another wave */
3127: /* if(mi==0) never been interviewed correctly before death */
3128: /* Only death is a correct wave */
3129: mw[mi][i]=m;
3130: }
3131:
3132: wav[i]=mi;
3133: if(mi==0){
3134: nbwarn++;
3135: if(first==0){
3136: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3137: first=1;
3138: }
3139: if(first==1){
3140: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3141: }
3142: } /* end mi==0 */
3143: } /* End individuals */
3144:
3145: for(i=1; i<=imx; i++){
3146: for(mi=1; mi<wav[i];mi++){
3147: if (stepm <=0)
3148: dh[mi][i]=1;
3149: else{
3150: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3151: if (agedc[i] < 2*AGESUP) {
3152: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3153: if(j==0) j=1; /* Survives at least one month after exam */
3154: else if(j<0){
3155: nberr++;
3156: 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]);
3157: j=1; /* Temporary Dangerous patch */
3158: 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);
3159: 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]);
3160: 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);
3161: }
3162: k=k+1;
3163: if (j >= jmax){
3164: jmax=j;
3165: ijmax=i;
3166: }
3167: if (j <= jmin){
3168: jmin=j;
3169: ijmin=i;
3170: }
3171: sum=sum+j;
3172: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3173: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3174: }
3175: }
3176: else{
3177: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3178: /* 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]); */
3179:
3180: k=k+1;
3181: if (j >= jmax) {
3182: jmax=j;
3183: ijmax=i;
3184: }
3185: else if (j <= jmin){
3186: jmin=j;
3187: ijmin=i;
3188: }
3189: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3190: /*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]);*/
3191: if(j<0){
3192: nberr++;
3193: 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]);
3194: 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]);
3195: }
3196: sum=sum+j;
3197: }
3198: jk= j/stepm;
3199: jl= j -jk*stepm;
3200: ju= j -(jk+1)*stepm;
3201: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3202: if(jl==0){
3203: dh[mi][i]=jk;
3204: bh[mi][i]=0;
3205: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3206: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3207: dh[mi][i]=jk+1;
3208: bh[mi][i]=ju;
3209: }
3210: }else{
3211: if(jl <= -ju){
3212: dh[mi][i]=jk;
3213: bh[mi][i]=jl; /* bias is positive if real duration
3214: * is higher than the multiple of stepm and negative otherwise.
3215: */
3216: }
3217: else{
3218: dh[mi][i]=jk+1;
3219: bh[mi][i]=ju;
3220: }
3221: if(dh[mi][i]==0){
3222: dh[mi][i]=1; /* At least one step */
3223: bh[mi][i]=ju; /* At least one step */
3224: /* 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);*/
3225: }
3226: } /* end if mle */
3227: }
3228: } /* end wave */
3229: }
3230: jmean=sum/k;
3231: 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 3232: 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 3233: }
3234:
3235: /*********** Tricode ****************************/
1.145 brouard 3236: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3237: {
1.144 brouard 3238: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3239: /* 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 3240: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3241: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3242: * nbcode[Tvar[j]][1]=
1.144 brouard 3243: */
1.130 brouard 3244:
1.145 brouard 3245: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3246: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3247: int cptcode=0; /* Modality max of covariates j */
3248: int modmincovj=0; /* Modality min of covariates j */
3249:
3250:
1.126 brouard 3251: cptcoveff=0;
3252:
1.145 brouard 3253: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 3254: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3255:
1.145 brouard 3256: /* Loop on covariates without age and products */
1.186 brouard 3257: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3258: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3259: modality of this covariate Vj*/
1.145 brouard 3260: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3261: * If product of Vn*Vm, still boolean *:
3262: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3263: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3264: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3265: modality of the nth covariate of individual i. */
1.145 brouard 3266: if (ij > modmaxcovj)
3267: modmaxcovj=ij;
3268: else if (ij < modmincovj)
3269: modmincovj=ij;
3270: if ((ij < -1) && (ij > NCOVMAX)){
3271: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3272: exit(1);
3273: }else
1.136 brouard 3274: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3275: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3276: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3277: /* getting the maximum value of the modality of the covariate
3278: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3279: female is 1, then modmaxcovj=1.*/
1.187 brouard 3280: } /* end for loop on individuals */
1.145 brouard 3281: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3282: cptcode=modmaxcovj;
1.137 brouard 3283: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3284: /*for (i=0; i<=cptcode; i++) {*/
3285: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
1.187 brouard 3286: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
1.145 brouard 3287: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3288: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3289: }
3290: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3291: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3292: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3293:
1.136 brouard 3294: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3295: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3296: 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 3297: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3298: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3299: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3300: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3301: nbcode[Tvar[j]][ij]=k;
3302: nbcode[Tvar[j]][1]=0;
3303: nbcode[Tvar[j]][2]=1;
3304: nbcode[Tvar[j]][3]=2;
3305: */
3306: ij=1; /* ij is similar to i but can jumps over null modalities */
3307: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3308: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3309: /*recode from 0 */
1.131 brouard 3310: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
1.186 brouard 3311: nbcode[Tvar[j]][ij]=k; /* stores the modality k in an array nbcode.
1.131 brouard 3312: k is a modality. If we have model=V1+V1*sex
3313: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3314: ij++;
3315: }
3316: if (ij > ncodemax[j]) break;
1.137 brouard 3317: } /* end of loop on */
3318: } /* end of loop on modality */
3319: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3320:
1.145 brouard 3321: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3322:
1.187 brouard 3323: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3324: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3325: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3326: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3327: }
1.126 brouard 3328:
3329: ij=1;
1.145 brouard 3330: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3331: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3332: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3333: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3334: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3335: ij++;
1.145 brouard 3336: }else
3337: Tvaraff[ij]=0;
1.126 brouard 3338: }
1.131 brouard 3339: ij--;
1.144 brouard 3340: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3341:
1.126 brouard 3342: }
3343:
1.145 brouard 3344:
1.126 brouard 3345: /*********** Health Expectancies ****************/
3346:
1.127 brouard 3347: 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 3348:
3349: {
3350: /* Health expectancies, no variances */
1.164 brouard 3351: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3352: int nhstepma, nstepma; /* Decreasing with age */
3353: double age, agelim, hf;
3354: double ***p3mat;
3355: double eip;
3356:
3357: pstamp(ficreseij);
3358: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3359: fprintf(ficreseij,"# Age");
3360: for(i=1; i<=nlstate;i++){
3361: for(j=1; j<=nlstate;j++){
3362: fprintf(ficreseij," e%1d%1d ",i,j);
3363: }
3364: fprintf(ficreseij," e%1d. ",i);
3365: }
3366: fprintf(ficreseij,"\n");
3367:
3368:
3369: if(estepm < stepm){
3370: printf ("Problem %d lower than %d\n",estepm, stepm);
3371: }
3372: else hstepm=estepm;
3373: /* We compute the life expectancy from trapezoids spaced every estepm months
3374: * This is mainly to measure the difference between two models: for example
3375: * if stepm=24 months pijx are given only every 2 years and by summing them
3376: * we are calculating an estimate of the Life Expectancy assuming a linear
3377: * progression in between and thus overestimating or underestimating according
3378: * to the curvature of the survival function. If, for the same date, we
3379: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3380: * to compare the new estimate of Life expectancy with the same linear
3381: * hypothesis. A more precise result, taking into account a more precise
3382: * curvature will be obtained if estepm is as small as stepm. */
3383:
3384: /* For example we decided to compute the life expectancy with the smallest unit */
3385: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3386: nhstepm is the number of hstepm from age to agelim
3387: nstepm is the number of stepm from age to agelin.
3388: Look at hpijx to understand the reason of that which relies in memory size
3389: and note for a fixed period like estepm months */
3390: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3391: survival function given by stepm (the optimization length). Unfortunately it
3392: means that if the survival funtion is printed only each two years of age and if
3393: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3394: results. So we changed our mind and took the option of the best precision.
3395: */
3396: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3397:
3398: agelim=AGESUP;
3399: /* If stepm=6 months */
3400: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3401: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3402:
3403: /* nhstepm age range expressed in number of stepm */
3404: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3405: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3406: /* if (stepm >= YEARM) hstepm=1;*/
3407: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3408: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3409:
3410: for (age=bage; age<=fage; age ++){
3411: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3412: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3413: /* if (stepm >= YEARM) hstepm=1;*/
3414: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3415:
3416: /* If stepm=6 months */
3417: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3418: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3419:
3420: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3421:
3422: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3423:
3424: printf("%d|",(int)age);fflush(stdout);
3425: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3426:
3427: /* Computing expectancies */
3428: for(i=1; i<=nlstate;i++)
3429: for(j=1; j<=nlstate;j++)
3430: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3431: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3432:
3433: /* 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]);*/
3434:
3435: }
3436:
3437: fprintf(ficreseij,"%3.0f",age );
3438: for(i=1; i<=nlstate;i++){
3439: eip=0;
3440: for(j=1; j<=nlstate;j++){
3441: eip +=eij[i][j][(int)age];
3442: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3443: }
3444: fprintf(ficreseij,"%9.4f", eip );
3445: }
3446: fprintf(ficreseij,"\n");
3447:
3448: }
3449: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3450: printf("\n");
3451: fprintf(ficlog,"\n");
3452:
3453: }
3454:
1.127 brouard 3455: 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 3456:
3457: {
3458: /* Covariances of health expectancies eij and of total life expectancies according
3459: to initial status i, ei. .
3460: */
3461: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3462: int nhstepma, nstepma; /* Decreasing with age */
3463: double age, agelim, hf;
3464: double ***p3matp, ***p3matm, ***varhe;
3465: double **dnewm,**doldm;
3466: double *xp, *xm;
3467: double **gp, **gm;
3468: double ***gradg, ***trgradg;
3469: int theta;
3470:
3471: double eip, vip;
3472:
3473: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3474: xp=vector(1,npar);
3475: xm=vector(1,npar);
3476: dnewm=matrix(1,nlstate*nlstate,1,npar);
3477: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3478:
3479: pstamp(ficresstdeij);
3480: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3481: fprintf(ficresstdeij,"# Age");
3482: for(i=1; i<=nlstate;i++){
3483: for(j=1; j<=nlstate;j++)
3484: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3485: fprintf(ficresstdeij," e%1d. ",i);
3486: }
3487: fprintf(ficresstdeij,"\n");
3488:
3489: pstamp(ficrescveij);
3490: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3491: fprintf(ficrescveij,"# Age");
3492: for(i=1; i<=nlstate;i++)
3493: for(j=1; j<=nlstate;j++){
3494: cptj= (j-1)*nlstate+i;
3495: for(i2=1; i2<=nlstate;i2++)
3496: for(j2=1; j2<=nlstate;j2++){
3497: cptj2= (j2-1)*nlstate+i2;
3498: if(cptj2 <= cptj)
3499: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3500: }
3501: }
3502: fprintf(ficrescveij,"\n");
3503:
3504: if(estepm < stepm){
3505: printf ("Problem %d lower than %d\n",estepm, stepm);
3506: }
3507: else hstepm=estepm;
3508: /* We compute the life expectancy from trapezoids spaced every estepm months
3509: * This is mainly to measure the difference between two models: for example
3510: * if stepm=24 months pijx are given only every 2 years and by summing them
3511: * we are calculating an estimate of the Life Expectancy assuming a linear
3512: * progression in between and thus overestimating or underestimating according
3513: * to the curvature of the survival function. If, for the same date, we
3514: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3515: * to compare the new estimate of Life expectancy with the same linear
3516: * hypothesis. A more precise result, taking into account a more precise
3517: * curvature will be obtained if estepm is as small as stepm. */
3518:
3519: /* For example we decided to compute the life expectancy with the smallest unit */
3520: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3521: nhstepm is the number of hstepm from age to agelim
3522: nstepm is the number of stepm from age to agelin.
3523: Look at hpijx to understand the reason of that which relies in memory size
3524: and note for a fixed period like estepm months */
3525: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3526: survival function given by stepm (the optimization length). Unfortunately it
3527: means that if the survival funtion is printed only each two years of age and if
3528: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3529: results. So we changed our mind and took the option of the best precision.
3530: */
3531: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3532:
3533: /* If stepm=6 months */
3534: /* nhstepm age range expressed in number of stepm */
3535: agelim=AGESUP;
3536: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3537: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3538: /* if (stepm >= YEARM) hstepm=1;*/
3539: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3540:
3541: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3542: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3543: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3544: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3545: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3546: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3547:
3548: for (age=bage; age<=fage; age ++){
3549: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3550: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3551: /* if (stepm >= YEARM) hstepm=1;*/
3552: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3553:
3554: /* If stepm=6 months */
3555: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3556: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3557:
3558: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3559:
3560: /* Computing Variances of health expectancies */
3561: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3562: decrease memory allocation */
3563: for(theta=1; theta <=npar; theta++){
3564: for(i=1; i<=npar; i++){
3565: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3566: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3567: }
3568: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3569: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3570:
3571: for(j=1; j<= nlstate; j++){
3572: for(i=1; i<=nlstate; i++){
3573: for(h=0; h<=nhstepm-1; h++){
3574: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3575: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3576: }
3577: }
3578: }
3579:
3580: for(ij=1; ij<= nlstate*nlstate; ij++)
3581: for(h=0; h<=nhstepm-1; h++){
3582: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3583: }
3584: }/* End theta */
3585:
3586:
3587: for(h=0; h<=nhstepm-1; h++)
3588: for(j=1; j<=nlstate*nlstate;j++)
3589: for(theta=1; theta <=npar; theta++)
3590: trgradg[h][j][theta]=gradg[h][theta][j];
3591:
3592:
3593: for(ij=1;ij<=nlstate*nlstate;ij++)
3594: for(ji=1;ji<=nlstate*nlstate;ji++)
3595: varhe[ij][ji][(int)age] =0.;
3596:
3597: printf("%d|",(int)age);fflush(stdout);
3598: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3599: for(h=0;h<=nhstepm-1;h++){
3600: for(k=0;k<=nhstepm-1;k++){
3601: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3602: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3603: for(ij=1;ij<=nlstate*nlstate;ij++)
3604: for(ji=1;ji<=nlstate*nlstate;ji++)
3605: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3606: }
3607: }
3608:
3609: /* Computing expectancies */
3610: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3611: for(i=1; i<=nlstate;i++)
3612: for(j=1; j<=nlstate;j++)
3613: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3614: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3615:
3616: /* 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]);*/
3617:
3618: }
3619:
3620: fprintf(ficresstdeij,"%3.0f",age );
3621: for(i=1; i<=nlstate;i++){
3622: eip=0.;
3623: vip=0.;
3624: for(j=1; j<=nlstate;j++){
3625: eip += eij[i][j][(int)age];
3626: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3627: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3628: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3629: }
3630: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3631: }
3632: fprintf(ficresstdeij,"\n");
3633:
3634: fprintf(ficrescveij,"%3.0f",age );
3635: for(i=1; i<=nlstate;i++)
3636: for(j=1; j<=nlstate;j++){
3637: cptj= (j-1)*nlstate+i;
3638: for(i2=1; i2<=nlstate;i2++)
3639: for(j2=1; j2<=nlstate;j2++){
3640: cptj2= (j2-1)*nlstate+i2;
3641: if(cptj2 <= cptj)
3642: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3643: }
3644: }
3645: fprintf(ficrescveij,"\n");
3646:
3647: }
3648: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3649: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3650: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3651: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3652: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3653: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3654: printf("\n");
3655: fprintf(ficlog,"\n");
3656:
3657: free_vector(xm,1,npar);
3658: free_vector(xp,1,npar);
3659: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3660: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3661: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3662: }
3663:
3664: /************ Variance ******************/
3665: 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[])
3666: {
3667: /* Variance of health expectancies */
3668: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3669: /* double **newm;*/
1.169 brouard 3670: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3671:
3672: int movingaverage();
1.126 brouard 3673: double **dnewm,**doldm;
3674: double **dnewmp,**doldmp;
3675: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3676: int k;
1.126 brouard 3677: double *xp;
3678: double **gp, **gm; /* for var eij */
3679: double ***gradg, ***trgradg; /*for var eij */
3680: double **gradgp, **trgradgp; /* for var p point j */
3681: double *gpp, *gmp; /* for var p point j */
3682: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3683: double ***p3mat;
3684: double age,agelim, hf;
3685: double ***mobaverage;
3686: int theta;
3687: char digit[4];
3688: char digitp[25];
3689:
3690: char fileresprobmorprev[FILENAMELENGTH];
3691:
3692: if(popbased==1){
3693: if(mobilav!=0)
3694: strcpy(digitp,"-populbased-mobilav-");
3695: else strcpy(digitp,"-populbased-nomobil-");
3696: }
3697: else
3698: strcpy(digitp,"-stablbased-");
3699:
3700: if (mobilav!=0) {
3701: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3702: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3703: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3704: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3705: }
3706: }
3707:
3708: strcpy(fileresprobmorprev,"prmorprev");
3709: sprintf(digit,"%-d",ij);
3710: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3711: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3712: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3713: strcat(fileresprobmorprev,fileres);
3714: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3715: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3716: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3717: }
3718: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3719:
3720: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3721: pstamp(ficresprobmorprev);
3722: 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);
3723: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3724: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3725: fprintf(ficresprobmorprev," p.%-d SE",j);
3726: for(i=1; i<=nlstate;i++)
3727: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3728: }
3729: fprintf(ficresprobmorprev,"\n");
3730: fprintf(ficgp,"\n# Routine varevsij");
3731: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3732: 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");
3733: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3734: /* } */
3735: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3736: pstamp(ficresvij);
3737: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3738: if(popbased==1)
1.128 brouard 3739: 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 3740: else
3741: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3742: fprintf(ficresvij,"# Age");
3743: for(i=1; i<=nlstate;i++)
3744: for(j=1; j<=nlstate;j++)
3745: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3746: fprintf(ficresvij,"\n");
3747:
3748: xp=vector(1,npar);
3749: dnewm=matrix(1,nlstate,1,npar);
3750: doldm=matrix(1,nlstate,1,nlstate);
3751: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3752: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3753:
3754: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3755: gpp=vector(nlstate+1,nlstate+ndeath);
3756: gmp=vector(nlstate+1,nlstate+ndeath);
3757: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3758:
3759: if(estepm < stepm){
3760: printf ("Problem %d lower than %d\n",estepm, stepm);
3761: }
3762: else hstepm=estepm;
3763: /* For example we decided to compute the life expectancy with the smallest unit */
3764: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3765: nhstepm is the number of hstepm from age to agelim
3766: nstepm is the number of stepm from age to agelin.
1.128 brouard 3767: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3768: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3769: survival function given by stepm (the optimization length). Unfortunately it
3770: means that if the survival funtion is printed every two years of age and if
3771: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3772: results. So we changed our mind and took the option of the best precision.
3773: */
3774: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3775: agelim = AGESUP;
3776: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3777: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3778: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3779: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3780: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3781: gp=matrix(0,nhstepm,1,nlstate);
3782: gm=matrix(0,nhstepm,1,nlstate);
3783:
3784:
3785: for(theta=1; theta <=npar; theta++){
3786: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3787: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3788: }
3789: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3790: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3791:
3792: if (popbased==1) {
3793: if(mobilav ==0){
3794: for(i=1; i<=nlstate;i++)
3795: prlim[i][i]=probs[(int)age][i][ij];
3796: }else{ /* mobilav */
3797: for(i=1; i<=nlstate;i++)
3798: prlim[i][i]=mobaverage[(int)age][i][ij];
3799: }
3800: }
3801:
3802: for(j=1; j<= nlstate; j++){
3803: for(h=0; h<=nhstepm; h++){
3804: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3805: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3806: }
3807: }
3808: /* This for computing probability of death (h=1 means
3809: computed over hstepm matrices product = hstepm*stepm months)
3810: as a weighted average of prlim.
3811: */
3812: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3813: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3814: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3815: }
3816: /* end probability of death */
3817:
3818: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3819: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3820: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3821: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3822:
3823: if (popbased==1) {
3824: if(mobilav ==0){
3825: for(i=1; i<=nlstate;i++)
3826: prlim[i][i]=probs[(int)age][i][ij];
3827: }else{ /* mobilav */
3828: for(i=1; i<=nlstate;i++)
3829: prlim[i][i]=mobaverage[(int)age][i][ij];
3830: }
3831: }
3832:
1.128 brouard 3833: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3834: for(h=0; h<=nhstepm; h++){
3835: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3836: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3837: }
3838: }
3839: /* This for computing probability of death (h=1 means
3840: computed over hstepm matrices product = hstepm*stepm months)
3841: as a weighted average of prlim.
3842: */
3843: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3844: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3845: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3846: }
3847: /* end probability of death */
3848:
3849: for(j=1; j<= nlstate; j++) /* vareij */
3850: for(h=0; h<=nhstepm; h++){
3851: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3852: }
3853:
3854: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3855: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3856: }
3857:
3858: } /* End theta */
3859:
3860: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3861:
3862: for(h=0; h<=nhstepm; h++) /* veij */
3863: for(j=1; j<=nlstate;j++)
3864: for(theta=1; theta <=npar; theta++)
3865: trgradg[h][j][theta]=gradg[h][theta][j];
3866:
3867: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3868: for(theta=1; theta <=npar; theta++)
3869: trgradgp[j][theta]=gradgp[theta][j];
3870:
3871:
3872: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3873: for(i=1;i<=nlstate;i++)
3874: for(j=1;j<=nlstate;j++)
3875: vareij[i][j][(int)age] =0.;
3876:
3877: for(h=0;h<=nhstepm;h++){
3878: for(k=0;k<=nhstepm;k++){
3879: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3880: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3881: for(i=1;i<=nlstate;i++)
3882: for(j=1;j<=nlstate;j++)
3883: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3884: }
3885: }
3886:
3887: /* pptj */
3888: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3889: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3890: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3891: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3892: varppt[j][i]=doldmp[j][i];
3893: /* end ppptj */
3894: /* x centered again */
3895: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3896: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3897:
3898: if (popbased==1) {
3899: if(mobilav ==0){
3900: for(i=1; i<=nlstate;i++)
3901: prlim[i][i]=probs[(int)age][i][ij];
3902: }else{ /* mobilav */
3903: for(i=1; i<=nlstate;i++)
3904: prlim[i][i]=mobaverage[(int)age][i][ij];
3905: }
3906: }
3907:
3908: /* This for computing probability of death (h=1 means
3909: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3910: as a weighted average of prlim.
3911: */
3912: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3913: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3914: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3915: }
3916: /* end probability of death */
3917:
3918: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3919: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3920: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3921: for(i=1; i<=nlstate;i++){
3922: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3923: }
3924: }
3925: fprintf(ficresprobmorprev,"\n");
3926:
3927: fprintf(ficresvij,"%.0f ",age );
3928: for(i=1; i<=nlstate;i++)
3929: for(j=1; j<=nlstate;j++){
3930: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3931: }
3932: fprintf(ficresvij,"\n");
3933: free_matrix(gp,0,nhstepm,1,nlstate);
3934: free_matrix(gm,0,nhstepm,1,nlstate);
3935: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3936: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3937: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3938: } /* End age */
3939: free_vector(gpp,nlstate+1,nlstate+ndeath);
3940: free_vector(gmp,nlstate+1,nlstate+ndeath);
3941: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3942: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3943: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3944: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3945: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3946: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3947: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3948: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3949: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3950: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3951: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3952: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3953: 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);
3954: /* 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);
3955: */
3956: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3957: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3958:
3959: free_vector(xp,1,npar);
3960: free_matrix(doldm,1,nlstate,1,nlstate);
3961: free_matrix(dnewm,1,nlstate,1,npar);
3962: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3963: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3964: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3965: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3966: fclose(ficresprobmorprev);
3967: fflush(ficgp);
3968: fflush(fichtm);
3969: } /* end varevsij */
3970:
3971: /************ Variance of prevlim ******************/
3972: 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[])
3973: {
3974: /* Variance of prevalence limit */
3975: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3976:
1.126 brouard 3977: double **dnewm,**doldm;
3978: int i, j, nhstepm, hstepm;
3979: double *xp;
3980: double *gp, *gm;
3981: double **gradg, **trgradg;
3982: double age,agelim;
3983: int theta;
3984:
3985: pstamp(ficresvpl);
3986: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3987: fprintf(ficresvpl,"# Age");
3988: for(i=1; i<=nlstate;i++)
3989: fprintf(ficresvpl," %1d-%1d",i,i);
3990: fprintf(ficresvpl,"\n");
3991:
3992: xp=vector(1,npar);
3993: dnewm=matrix(1,nlstate,1,npar);
3994: doldm=matrix(1,nlstate,1,nlstate);
3995:
3996: hstepm=1*YEARM; /* Every year of age */
3997: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3998: agelim = AGESUP;
3999: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4000: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4001: if (stepm >= YEARM) hstepm=1;
4002: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4003: gradg=matrix(1,npar,1,nlstate);
4004: gp=vector(1,nlstate);
4005: gm=vector(1,nlstate);
4006:
4007: for(theta=1; theta <=npar; theta++){
4008: for(i=1; i<=npar; i++){ /* Computes gradient */
4009: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4010: }
4011: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4012: for(i=1;i<=nlstate;i++)
4013: gp[i] = prlim[i][i];
4014:
4015: for(i=1; i<=npar; i++) /* Computes gradient */
4016: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4017: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4018: for(i=1;i<=nlstate;i++)
4019: gm[i] = prlim[i][i];
4020:
4021: for(i=1;i<=nlstate;i++)
4022: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4023: } /* End theta */
4024:
4025: trgradg =matrix(1,nlstate,1,npar);
4026:
4027: for(j=1; j<=nlstate;j++)
4028: for(theta=1; theta <=npar; theta++)
4029: trgradg[j][theta]=gradg[theta][j];
4030:
4031: for(i=1;i<=nlstate;i++)
4032: varpl[i][(int)age] =0.;
4033: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4034: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4035: for(i=1;i<=nlstate;i++)
4036: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4037:
4038: fprintf(ficresvpl,"%.0f ",age );
4039: for(i=1; i<=nlstate;i++)
4040: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4041: fprintf(ficresvpl,"\n");
4042: free_vector(gp,1,nlstate);
4043: free_vector(gm,1,nlstate);
4044: free_matrix(gradg,1,npar,1,nlstate);
4045: free_matrix(trgradg,1,nlstate,1,npar);
4046: } /* End age */
4047:
4048: free_vector(xp,1,npar);
4049: free_matrix(doldm,1,nlstate,1,npar);
4050: free_matrix(dnewm,1,nlstate,1,nlstate);
4051:
4052: }
4053:
4054: /************ Variance of one-step probabilities ******************/
4055: 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[])
4056: {
1.164 brouard 4057: int i, j=0, k1, l1, tj;
1.126 brouard 4058: int k2, l2, j1, z1;
1.164 brouard 4059: int k=0, l;
1.145 brouard 4060: int first=1, first1, first2;
1.126 brouard 4061: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4062: double **dnewm,**doldm;
4063: double *xp;
4064: double *gp, *gm;
4065: double **gradg, **trgradg;
4066: double **mu;
1.164 brouard 4067: double age, cov[NCOVMAX+1];
1.126 brouard 4068: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4069: int theta;
4070: char fileresprob[FILENAMELENGTH];
4071: char fileresprobcov[FILENAMELENGTH];
4072: char fileresprobcor[FILENAMELENGTH];
4073: double ***varpij;
4074:
4075: strcpy(fileresprob,"prob");
4076: strcat(fileresprob,fileres);
4077: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4078: printf("Problem with resultfile: %s\n", fileresprob);
4079: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4080: }
4081: strcpy(fileresprobcov,"probcov");
4082: strcat(fileresprobcov,fileres);
4083: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4084: printf("Problem with resultfile: %s\n", fileresprobcov);
4085: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4086: }
4087: strcpy(fileresprobcor,"probcor");
4088: strcat(fileresprobcor,fileres);
4089: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4090: printf("Problem with resultfile: %s\n", fileresprobcor);
4091: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4092: }
4093: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4094: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4095: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4096: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4097: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4098: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4099: pstamp(ficresprob);
4100: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4101: fprintf(ficresprob,"# Age");
4102: pstamp(ficresprobcov);
4103: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4104: fprintf(ficresprobcov,"# Age");
4105: pstamp(ficresprobcor);
4106: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4107: fprintf(ficresprobcor,"# Age");
4108:
4109:
4110: for(i=1; i<=nlstate;i++)
4111: for(j=1; j<=(nlstate+ndeath);j++){
4112: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4113: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4114: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4115: }
4116: /* fprintf(ficresprob,"\n");
4117: fprintf(ficresprobcov,"\n");
4118: fprintf(ficresprobcor,"\n");
4119: */
1.131 brouard 4120: xp=vector(1,npar);
1.126 brouard 4121: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4122: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4123: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4124: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4125: first=1;
4126: fprintf(ficgp,"\n# Routine varprob");
4127: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4128: fprintf(fichtm,"\n");
4129:
4130: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
4131: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
4132: file %s<br>\n",optionfilehtmcov);
4133: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
4134: and drawn. It helps understanding how is the covariance between two incidences.\
4135: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4136: 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. \
4137: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4138: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4139: standard deviations wide on each axis. <br>\
4140: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4141: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4142: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4143:
4144: cov[1]=1;
1.145 brouard 4145: /* tj=cptcoveff; */
4146: tj = (int) pow(2,cptcoveff);
1.126 brouard 4147: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4148: j1=0;
1.145 brouard 4149: for(j1=1; j1<=tj;j1++){
4150: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4151: /*j1++;*/
1.126 brouard 4152: if (cptcovn>0) {
4153: fprintf(ficresprob, "\n#********** Variable ");
4154: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4155: fprintf(ficresprob, "**********\n#\n");
4156: fprintf(ficresprobcov, "\n#********** Variable ");
4157: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4158: fprintf(ficresprobcov, "**********\n#\n");
4159:
4160: fprintf(ficgp, "\n#********** Variable ");
4161: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4162: fprintf(ficgp, "**********\n#\n");
4163:
4164:
4165: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4166: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4167: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4168:
4169: fprintf(ficresprobcor, "\n#********** Variable ");
4170: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4171: fprintf(ficresprobcor, "**********\n#");
4172: }
4173:
1.145 brouard 4174: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4175: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4176: gp=vector(1,(nlstate)*(nlstate+ndeath));
4177: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4178: for (age=bage; age<=fage; age ++){
4179: cov[2]=age;
1.187 brouard 4180: if(nagesqr==1)
4181: cov[3]= age*age;
1.126 brouard 4182: for (k=1; k<=cptcovn;k++) {
1.187 brouard 4183: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145 brouard 4184: * 1 1 1 1 1
4185: * 2 2 1 1 1
4186: * 3 1 2 1 1
4187: */
4188: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4189: }
1.186 brouard 4190: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4191: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126 brouard 4192: for (k=1; k<=cptcovprod;k++)
1.187 brouard 4193: 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 4194:
4195:
4196: for(theta=1; theta <=npar; theta++){
4197: for(i=1; i<=npar; i++)
4198: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4199:
4200: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4201:
4202: k=0;
4203: for(i=1; i<= (nlstate); i++){
4204: for(j=1; j<=(nlstate+ndeath);j++){
4205: k=k+1;
4206: gp[k]=pmmij[i][j];
4207: }
4208: }
4209:
4210: for(i=1; i<=npar; i++)
4211: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4212:
4213: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4214: k=0;
4215: for(i=1; i<=(nlstate); i++){
4216: for(j=1; j<=(nlstate+ndeath);j++){
4217: k=k+1;
4218: gm[k]=pmmij[i][j];
4219: }
4220: }
4221:
4222: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4223: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4224: }
4225:
4226: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4227: for(theta=1; theta <=npar; theta++)
4228: trgradg[j][theta]=gradg[theta][j];
4229:
4230: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4231: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4232:
4233: pmij(pmmij,cov,ncovmodel,x,nlstate);
4234:
4235: k=0;
4236: for(i=1; i<=(nlstate); i++){
4237: for(j=1; j<=(nlstate+ndeath);j++){
4238: k=k+1;
4239: mu[k][(int) age]=pmmij[i][j];
4240: }
4241: }
4242: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4243: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4244: varpij[i][j][(int)age] = doldm[i][j];
4245:
4246: /*printf("\n%d ",(int)age);
4247: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4248: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4249: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4250: }*/
4251:
4252: fprintf(ficresprob,"\n%d ",(int)age);
4253: fprintf(ficresprobcov,"\n%d ",(int)age);
4254: fprintf(ficresprobcor,"\n%d ",(int)age);
4255:
4256: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4257: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4258: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4259: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4260: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4261: }
4262: i=0;
4263: for (k=1; k<=(nlstate);k++){
4264: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4265: i++;
1.126 brouard 4266: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4267: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4268: for (j=1; j<=i;j++){
1.145 brouard 4269: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4270: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4271: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4272: }
4273: }
4274: }/* end of loop for state */
4275: } /* end of loop for age */
1.145 brouard 4276: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4277: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4278: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4279: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4280:
1.126 brouard 4281: /* Confidence intervalle of pij */
4282: /*
1.131 brouard 4283: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4284: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4285: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4286: 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);
4287: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4288: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4289: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4290: */
4291:
4292: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4293: first1=1;first2=2;
1.126 brouard 4294: for (k2=1; k2<=(nlstate);k2++){
4295: for (l2=1; l2<=(nlstate+ndeath);l2++){
4296: if(l2==k2) continue;
4297: j=(k2-1)*(nlstate+ndeath)+l2;
4298: for (k1=1; k1<=(nlstate);k1++){
4299: for (l1=1; l1<=(nlstate+ndeath);l1++){
4300: if(l1==k1) continue;
4301: i=(k1-1)*(nlstate+ndeath)+l1;
4302: if(i<=j) continue;
4303: for (age=bage; age<=fage; age ++){
4304: if ((int)age %5==0){
4305: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4306: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4307: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4308: mu1=mu[i][(int) age]/stepm*YEARM ;
4309: mu2=mu[j][(int) age]/stepm*YEARM;
4310: c12=cv12/sqrt(v1*v2);
4311: /* Computing eigen value of matrix of covariance */
4312: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4313: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4314: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4315: if(first2==1){
4316: first1=0;
4317: 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);
4318: }
4319: 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);
4320: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4321: /* lc2=fabs(lc2); */
1.135 brouard 4322: }
4323:
1.126 brouard 4324: /* Eigen vectors */
4325: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4326: /*v21=sqrt(1.-v11*v11); *//* error */
4327: v21=(lc1-v1)/cv12*v11;
4328: v12=-v21;
4329: v22=v11;
4330: tnalp=v21/v11;
4331: if(first1==1){
4332: first1=0;
4333: 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);
4334: }
4335: 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);
4336: /*printf(fignu*/
4337: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4338: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4339: if(first==1){
4340: first=0;
4341: fprintf(ficgp,"\nset parametric;unset label");
4342: 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 4343: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4344: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4345: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4346: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4347: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4348: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4349: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4350: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4351: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4352: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4353: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4354: 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",\
4355: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4356: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4357: }else{
4358: first=0;
4359: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4360: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4361: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4362: 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",\
4363: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4364: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4365: }/* if first */
4366: } /* age mod 5 */
4367: } /* end loop age */
4368: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4369: first=1;
4370: } /*l12 */
4371: } /* k12 */
4372: } /*l1 */
4373: }/* k1 */
1.169 brouard 4374: /* } */ /* loop covariates */
1.126 brouard 4375: }
4376: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4377: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4378: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4379: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4380: free_vector(xp,1,npar);
4381: fclose(ficresprob);
4382: fclose(ficresprobcov);
4383: fclose(ficresprobcor);
4384: fflush(ficgp);
4385: fflush(fichtmcov);
4386: }
4387:
4388:
4389: /******************* Printing html file ***********/
4390: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4391: int lastpass, int stepm, int weightopt, char model[],\
4392: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4393: int popforecast, int estepm ,\
4394: double jprev1, double mprev1,double anprev1, \
4395: double jprev2, double mprev2,double anprev2){
4396: int jj1, k1, i1, cpt;
4397:
4398: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4399: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4400: </ul>");
4401: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4402: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4403: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4404: fprintf(fichtm,"\
4405: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4406: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4407: fprintf(fichtm,"\
4408: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4409: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4410: fprintf(fichtm,"\
1.128 brouard 4411: - (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 4412: <a href=\"%s\">%s</a> <br>\n",
4413: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4414: fprintf(fichtm,"\
4415: - Population projections by age and states: \
4416: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4417:
4418: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4419:
1.145 brouard 4420: m=pow(2,cptcoveff);
1.126 brouard 4421: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4422:
4423: jj1=0;
4424: for(k1=1; k1<=m;k1++){
4425: for(i1=1; i1<=ncodemax[k1];i1++){
4426: jj1++;
4427: if (cptcovn > 0) {
4428: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4429: for (cpt=1; cpt<=cptcoveff;cpt++)
4430: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4431: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4432: }
4433: /* Pij */
1.145 brouard 4434: 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> \
4435: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4436: /* Quasi-incidences */
4437: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4438: 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> \
4439: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4440: /* Period (stable) prevalence in each health state */
1.154 brouard 4441: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4442: 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> \
4443: <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 4444: }
4445: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4446: 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> \
4447: <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 4448: }
4449: } /* end i1 */
4450: }/* End k1 */
4451: fprintf(fichtm,"</ul>");
4452:
4453:
4454: fprintf(fichtm,"\
4455: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4456: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4457:
4458: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4459: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4460: fprintf(fichtm,"\
4461: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4462: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4463:
4464: fprintf(fichtm,"\
4465: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4466: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4467: fprintf(fichtm,"\
4468: - 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): \
4469: <a href=\"%s\">%s</a> <br>\n</li>",
4470: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4471: fprintf(fichtm,"\
4472: - (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): \
4473: <a href=\"%s\">%s</a> <br>\n</li>",
4474: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4475: fprintf(fichtm,"\
1.128 brouard 4476: - 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 4477: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4478: fprintf(fichtm,"\
1.128 brouard 4479: - 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",
4480: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4481: fprintf(fichtm,"\
4482: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4483: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4484:
4485: /* if(popforecast==1) fprintf(fichtm,"\n */
4486: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4487: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4488: /* <br>",fileres,fileres,fileres,fileres); */
4489: /* else */
4490: /* 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); */
4491: fflush(fichtm);
4492: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4493:
1.145 brouard 4494: m=pow(2,cptcoveff);
1.126 brouard 4495: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4496:
4497: jj1=0;
4498: for(k1=1; k1<=m;k1++){
4499: for(i1=1; i1<=ncodemax[k1];i1++){
4500: jj1++;
4501: if (cptcovn > 0) {
4502: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4503: for (cpt=1; cpt<=cptcoveff;cpt++)
4504: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4505: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4506: }
4507: for(cpt=1; cpt<=nlstate;cpt++) {
4508: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4509: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4510: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4511: }
4512: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4513: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4514: true period expectancies (those weighted with period prevalences are also\
4515: drawn in addition to the population based expectancies computed using\
4516: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4517: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4518: } /* end i1 */
4519: }/* End k1 */
4520: fprintf(fichtm,"</ul>");
4521: fflush(fichtm);
4522: }
4523:
4524: /******************* Gnuplot file **************/
4525: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4526:
4527: char dirfileres[132],optfileres[132];
1.164 brouard 4528: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4529: int ng=0;
1.126 brouard 4530: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4531: /* printf("Problem with file %s",optionfilegnuplot); */
4532: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4533: /* } */
4534:
4535: /*#ifdef windows */
4536: fprintf(ficgp,"cd \"%s\" \n",pathc);
4537: /*#endif */
4538: m=pow(2,cptcoveff);
4539:
4540: strcpy(dirfileres,optionfilefiname);
4541: strcpy(optfileres,"vpl");
4542: /* 1eme*/
1.153 brouard 4543: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4544: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4545: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4546: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4547: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4548: fprintf(ficgp,"set xlabel \"Age\" \n\
4549: set ylabel \"Probability\" \n\
1.145 brouard 4550: set ter png small size 320, 240\n\
1.170 brouard 4551: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4552:
4553: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4554: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4555: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4556: }
1.170 brouard 4557: 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 4558: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4559: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4560: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4561: }
1.170 brouard 4562: 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 4563: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4564: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4565: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4566: }
1.145 brouard 4567: 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 4568: }
4569: }
4570: /*2 eme*/
1.153 brouard 4571: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4572: for (k1=1; k1<= m ; k1 ++) {
4573: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4574: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4575:
4576: for (i=1; i<= nlstate+1 ; i ++) {
4577: k=2*i;
1.170 brouard 4578: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4579: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4580: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4581: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4582: }
4583: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4584: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4585: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4586: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4587: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4588: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4589: }
1.145 brouard 4590: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4591: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4592: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4593: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4594: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4595: }
1.145 brouard 4596: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4597: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4598: }
4599: }
4600:
4601: /*3eme*/
4602:
4603: for (k1=1; k1<= m ; k1 ++) {
4604: for (cpt=1; cpt<= nlstate ; cpt ++) {
4605: /* k=2+nlstate*(2*cpt-2); */
4606: k=2+(nlstate+1)*(cpt-1);
4607: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4608: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4609: 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);
4610: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4611: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4612: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4613: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4614: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4615: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4616:
4617: */
4618: for (i=1; i< nlstate ; i ++) {
4619: 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);
4620: /* 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);*/
4621:
4622: }
4623: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4624: }
4625: }
4626:
4627: /* CV preval stable (period) */
1.153 brouard 4628: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4629: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4630: k=3;
1.153 brouard 4631: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4632: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4633: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4634: set ter png small size 320, 240\n\
1.126 brouard 4635: unset log y\n\
1.153 brouard 4636: plot [%.f:%.f] ", ageminpar, agemaxpar);
4637: for (i=1; i<= nlstate ; i ++){
4638: if(i==1)
4639: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4640: else
4641: fprintf(ficgp,", '' ");
1.154 brouard 4642: l=(nlstate+ndeath)*(i-1)+1;
4643: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4644: for (j=1; j<= (nlstate-1) ; j ++)
4645: fprintf(ficgp,"+$%d",k+l+j);
4646: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4647: } /* nlstate */
4648: fprintf(ficgp,"\n");
4649: } /* end cpt state*/
4650: } /* end covariate */
1.126 brouard 4651:
4652: /* proba elementaires */
1.187 brouard 4653: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 4654: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 4655: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 4656: for(k=1; k <=(nlstate+ndeath); k++){
4657: if (k != i) {
1.187 brouard 4658: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 4659: for(j=1; j <=ncovmodel; j++){
1.187 brouard 4660: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 4661: jk++;
4662: }
1.187 brouard 4663: fprintf(ficgp,"\n");
1.126 brouard 4664: }
4665: }
4666: }
1.187 brouard 4667: fprintf(ficgp,"##############\n#\n");
4668:
1.145 brouard 4669: /*goto avoid;*/
1.187 brouard 4670: fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
4671: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4672: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4673: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4674: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4675: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4676: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4677: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4678: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4679: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4680: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4681: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4682: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4683: fprintf(ficgp,"#\n");
1.126 brouard 4684: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187 brouard 4685: fprintf(ficgp,"# ng=%d\n",ng);
4686: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 4687: for(jk=1; jk <=m; jk++) {
1.187 brouard 4688: fprintf(ficgp,"# jk=%d\n",jk);
1.145 brouard 4689: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4690: if (ng==2)
4691: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4692: else
4693: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4694: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4695: i=1;
4696: for(k2=1; k2<=nlstate; k2++) {
4697: k3=i;
4698: for(k=1; k<=(nlstate+ndeath); k++) {
4699: if (k != k2){
4700: if(ng==2)
1.187 brouard 4701: if(nagesqr==0)
4702: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4703: else /* nagesqr =1 */
4704: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126 brouard 4705: else
1.187 brouard 4706: if(nagesqr==0)
4707: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4708: else /* nagesqr =1 */
4709: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141 brouard 4710: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 4711: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186 brouard 4712: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187 brouard 4713: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186 brouard 4714: ij++;
4715: }
4716: else
1.187 brouard 4717: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4718: }
4719: fprintf(ficgp,")/(1");
4720:
1.187 brouard 4721: for(k1=1; k1 <=nlstate; k1++){
4722: if(nagesqr==0)
4723: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4724: else /* nagesqr =1 */
4725: 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);
4726:
1.126 brouard 4727: ij=1;
1.187 brouard 4728: for(j=3; j <=ncovmodel-nagesqr; j++){
1.186 brouard 4729: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187 brouard 4730: 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 4731: ij++;
4732: }
4733: else
1.187 brouard 4734: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126 brouard 4735: }
4736: fprintf(ficgp,")");
4737: }
4738: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4739: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4740: i=i+ncovmodel;
4741: }
4742: } /* end k */
4743: } /* end k2 */
4744: } /* end jk */
4745: } /* end ng */
1.164 brouard 4746: /* avoid: */
1.126 brouard 4747: fflush(ficgp);
4748: } /* end gnuplot */
4749:
4750:
4751: /*************** Moving average **************/
4752: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4753:
4754: int i, cpt, cptcod;
4755: int modcovmax =1;
4756: int mobilavrange, mob;
4757: double age;
4758:
4759: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4760: a covariate has 2 modalities */
4761: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4762:
4763: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4764: if(mobilav==1) mobilavrange=5; /* default */
4765: else mobilavrange=mobilav;
4766: for (age=bage; age<=fage; age++)
4767: for (i=1; i<=nlstate;i++)
4768: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4769: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4770: /* We keep the original values on the extreme ages bage, fage and for
4771: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4772: we use a 5 terms etc. until the borders are no more concerned.
4773: */
4774: for (mob=3;mob <=mobilavrange;mob=mob+2){
4775: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4776: for (i=1; i<=nlstate;i++){
4777: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4778: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4779: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4780: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4781: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4782: }
4783: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4784: }
4785: }
4786: }/* end age */
4787: }/* end mob */
4788: }else return -1;
4789: return 0;
4790: }/* End movingaverage */
4791:
4792:
4793: /************** Forecasting ******************/
1.169 brouard 4794: 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 4795: /* proj1, year, month, day of starting projection
4796: agemin, agemax range of age
4797: dateprev1 dateprev2 range of dates during which prevalence is computed
4798: anproj2 year of en of projection (same day and month as proj1).
4799: */
1.164 brouard 4800: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4801: double agec; /* generic age */
4802: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4803: double *popeffectif,*popcount;
4804: double ***p3mat;
4805: double ***mobaverage;
4806: char fileresf[FILENAMELENGTH];
4807:
4808: agelim=AGESUP;
4809: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4810:
4811: strcpy(fileresf,"f");
4812: strcat(fileresf,fileres);
4813: if((ficresf=fopen(fileresf,"w"))==NULL) {
4814: printf("Problem with forecast resultfile: %s\n", fileresf);
4815: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4816: }
4817: printf("Computing forecasting: result on file '%s' \n", fileresf);
4818: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4819:
4820: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4821:
4822: if (mobilav!=0) {
4823: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4824: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4825: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4826: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4827: }
4828: }
4829:
4830: stepsize=(int) (stepm+YEARM-1)/YEARM;
4831: if (stepm<=12) stepsize=1;
4832: if(estepm < stepm){
4833: printf ("Problem %d lower than %d\n",estepm, stepm);
4834: }
4835: else hstepm=estepm;
4836:
4837: hstepm=hstepm/stepm;
4838: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4839: fractional in yp1 */
4840: anprojmean=yp;
4841: yp2=modf((yp1*12),&yp);
4842: mprojmean=yp;
4843: yp1=modf((yp2*30.5),&yp);
4844: jprojmean=yp;
4845: if(jprojmean==0) jprojmean=1;
4846: if(mprojmean==0) jprojmean=1;
4847:
4848: i1=cptcoveff;
4849: if (cptcovn < 1){i1=1;}
4850:
4851: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4852:
4853: fprintf(ficresf,"#****** Routine prevforecast **\n");
4854:
4855: /* if (h==(int)(YEARM*yearp)){ */
4856: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4857: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4858: k=k+1;
4859: fprintf(ficresf,"\n#******");
4860: for(j=1;j<=cptcoveff;j++) {
4861: 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]]);
4862: }
4863: fprintf(ficresf,"******\n");
4864: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4865: for(j=1; j<=nlstate+ndeath;j++){
4866: for(i=1; i<=nlstate;i++)
4867: fprintf(ficresf," p%d%d",i,j);
4868: fprintf(ficresf," p.%d",j);
4869: }
4870: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4871: fprintf(ficresf,"\n");
4872: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4873:
4874: for (agec=fage; agec>=(ageminpar-1); agec--){
4875: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4876: nhstepm = nhstepm/hstepm;
4877: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4878: oldm=oldms;savm=savms;
4879: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4880:
4881: for (h=0; h<=nhstepm; h++){
4882: if (h*hstepm/YEARM*stepm ==yearp) {
4883: fprintf(ficresf,"\n");
4884: for(j=1;j<=cptcoveff;j++)
4885: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4886: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4887: }
4888: for(j=1; j<=nlstate+ndeath;j++) {
4889: ppij=0.;
4890: for(i=1; i<=nlstate;i++) {
4891: if (mobilav==1)
4892: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4893: else {
4894: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4895: }
4896: if (h*hstepm/YEARM*stepm== yearp) {
4897: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4898: }
4899: } /* end i */
4900: if (h*hstepm/YEARM*stepm==yearp) {
4901: fprintf(ficresf," %.3f", ppij);
4902: }
4903: }/* end j */
4904: } /* end h */
4905: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4906: } /* end agec */
4907: } /* end yearp */
4908: } /* end cptcod */
4909: } /* end cptcov */
4910:
4911: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4912:
4913: fclose(ficresf);
4914: }
4915:
4916: /************** Forecasting *****not tested NB*************/
1.169 brouard 4917: 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 4918:
4919: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4920: int *popage;
4921: double calagedatem, agelim, kk1, kk2;
4922: double *popeffectif,*popcount;
4923: double ***p3mat,***tabpop,***tabpopprev;
4924: double ***mobaverage;
4925: char filerespop[FILENAMELENGTH];
4926:
4927: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4928: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4929: agelim=AGESUP;
4930: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4931:
4932: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4933:
4934:
4935: strcpy(filerespop,"pop");
4936: strcat(filerespop,fileres);
4937: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4938: printf("Problem with forecast resultfile: %s\n", filerespop);
4939: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4940: }
4941: printf("Computing forecasting: result on file '%s' \n", filerespop);
4942: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4943:
4944: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4945:
4946: if (mobilav!=0) {
4947: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4948: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4949: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4950: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4951: }
4952: }
4953:
4954: stepsize=(int) (stepm+YEARM-1)/YEARM;
4955: if (stepm<=12) stepsize=1;
4956:
4957: agelim=AGESUP;
4958:
4959: hstepm=1;
4960: hstepm=hstepm/stepm;
4961:
4962: if (popforecast==1) {
4963: if((ficpop=fopen(popfile,"r"))==NULL) {
4964: printf("Problem with population file : %s\n",popfile);exit(0);
4965: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4966: }
4967: popage=ivector(0,AGESUP);
4968: popeffectif=vector(0,AGESUP);
4969: popcount=vector(0,AGESUP);
4970:
4971: i=1;
4972: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4973:
4974: imx=i;
4975: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4976: }
4977:
4978: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4979: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4980: k=k+1;
4981: fprintf(ficrespop,"\n#******");
4982: for(j=1;j<=cptcoveff;j++) {
4983: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4984: }
4985: fprintf(ficrespop,"******\n");
4986: fprintf(ficrespop,"# Age");
4987: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4988: if (popforecast==1) fprintf(ficrespop," [Population]");
4989:
4990: for (cpt=0; cpt<=0;cpt++) {
4991: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4992:
4993: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4994: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4995: nhstepm = nhstepm/hstepm;
4996:
4997: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4998: oldm=oldms;savm=savms;
4999: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5000:
5001: for (h=0; h<=nhstepm; h++){
5002: if (h==(int) (calagedatem+YEARM*cpt)) {
5003: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5004: }
5005: for(j=1; j<=nlstate+ndeath;j++) {
5006: kk1=0.;kk2=0;
5007: for(i=1; i<=nlstate;i++) {
5008: if (mobilav==1)
5009: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5010: else {
5011: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5012: }
5013: }
5014: if (h==(int)(calagedatem+12*cpt)){
5015: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5016: /*fprintf(ficrespop," %.3f", kk1);
5017: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5018: }
5019: }
5020: for(i=1; i<=nlstate;i++){
5021: kk1=0.;
5022: for(j=1; j<=nlstate;j++){
5023: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5024: }
5025: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5026: }
5027:
5028: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5029: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5030: }
5031: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5032: }
5033: }
5034:
5035: /******/
5036:
5037: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5038: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5039: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5040: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5041: nhstepm = nhstepm/hstepm;
5042:
5043: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5044: oldm=oldms;savm=savms;
5045: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5046: for (h=0; h<=nhstepm; h++){
5047: if (h==(int) (calagedatem+YEARM*cpt)) {
5048: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5049: }
5050: for(j=1; j<=nlstate+ndeath;j++) {
5051: kk1=0.;kk2=0;
5052: for(i=1; i<=nlstate;i++) {
5053: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5054: }
5055: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5056: }
5057: }
5058: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5059: }
5060: }
5061: }
5062: }
5063:
5064: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5065:
5066: if (popforecast==1) {
5067: free_ivector(popage,0,AGESUP);
5068: free_vector(popeffectif,0,AGESUP);
5069: free_vector(popcount,0,AGESUP);
5070: }
5071: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5072: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5073: fclose(ficrespop);
5074: } /* End of popforecast */
5075:
5076: int fileappend(FILE *fichier, char *optionfich)
5077: {
5078: if((fichier=fopen(optionfich,"a"))==NULL) {
5079: printf("Problem with file: %s\n", optionfich);
5080: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5081: return (0);
5082: }
5083: fflush(fichier);
5084: return (1);
5085: }
5086:
5087:
5088: /**************** function prwizard **********************/
5089: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5090: {
5091:
5092: /* Wizard to print covariance matrix template */
5093:
1.164 brouard 5094: char ca[32], cb[32];
5095: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5096: int numlinepar;
5097:
5098: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5099: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5100: for(i=1; i <=nlstate; i++){
5101: jj=0;
5102: for(j=1; j <=nlstate+ndeath; j++){
5103: if(j==i) continue;
5104: jj++;
5105: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5106: printf("%1d%1d",i,j);
5107: fprintf(ficparo,"%1d%1d",i,j);
5108: for(k=1; k<=ncovmodel;k++){
5109: /* printf(" %lf",param[i][j][k]); */
5110: /* fprintf(ficparo," %lf",param[i][j][k]); */
5111: printf(" 0.");
5112: fprintf(ficparo," 0.");
5113: }
5114: printf("\n");
5115: fprintf(ficparo,"\n");
5116: }
5117: }
5118: printf("# Scales (for hessian or gradient estimation)\n");
5119: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5120: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5121: for(i=1; i <=nlstate; i++){
5122: jj=0;
5123: for(j=1; j <=nlstate+ndeath; j++){
5124: if(j==i) continue;
5125: jj++;
5126: fprintf(ficparo,"%1d%1d",i,j);
5127: printf("%1d%1d",i,j);
5128: fflush(stdout);
5129: for(k=1; k<=ncovmodel;k++){
5130: /* printf(" %le",delti3[i][j][k]); */
5131: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5132: printf(" 0.");
5133: fprintf(ficparo," 0.");
5134: }
5135: numlinepar++;
5136: printf("\n");
5137: fprintf(ficparo,"\n");
5138: }
5139: }
5140: printf("# Covariance matrix\n");
5141: /* # 121 Var(a12)\n\ */
5142: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5143: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5144: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5145: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5146: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5147: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5148: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5149: fflush(stdout);
5150: fprintf(ficparo,"# Covariance matrix\n");
5151: /* # 121 Var(a12)\n\ */
5152: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5153: /* # ...\n\ */
5154: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5155:
5156: for(itimes=1;itimes<=2;itimes++){
5157: jj=0;
5158: for(i=1; i <=nlstate; i++){
5159: for(j=1; j <=nlstate+ndeath; j++){
5160: if(j==i) continue;
5161: for(k=1; k<=ncovmodel;k++){
5162: jj++;
5163: ca[0]= k+'a'-1;ca[1]='\0';
5164: if(itimes==1){
5165: printf("#%1d%1d%d",i,j,k);
5166: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5167: }else{
5168: printf("%1d%1d%d",i,j,k);
5169: fprintf(ficparo,"%1d%1d%d",i,j,k);
5170: /* printf(" %.5le",matcov[i][j]); */
5171: }
5172: ll=0;
5173: for(li=1;li <=nlstate; li++){
5174: for(lj=1;lj <=nlstate+ndeath; lj++){
5175: if(lj==li) continue;
5176: for(lk=1;lk<=ncovmodel;lk++){
5177: ll++;
5178: if(ll<=jj){
5179: cb[0]= lk +'a'-1;cb[1]='\0';
5180: if(ll<jj){
5181: if(itimes==1){
5182: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5183: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5184: }else{
5185: printf(" 0.");
5186: fprintf(ficparo," 0.");
5187: }
5188: }else{
5189: if(itimes==1){
5190: printf(" Var(%s%1d%1d)",ca,i,j);
5191: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5192: }else{
5193: printf(" 0.");
5194: fprintf(ficparo," 0.");
5195: }
5196: }
5197: }
5198: } /* end lk */
5199: } /* end lj */
5200: } /* end li */
5201: printf("\n");
5202: fprintf(ficparo,"\n");
5203: numlinepar++;
5204: } /* end k*/
5205: } /*end j */
5206: } /* end i */
5207: } /* end itimes */
5208:
5209: } /* end of prwizard */
5210: /******************* Gompertz Likelihood ******************************/
5211: double gompertz(double x[])
5212: {
5213: double A,B,L=0.0,sump=0.,num=0.;
5214: int i,n=0; /* n is the size of the sample */
5215:
5216: for (i=0;i<=imx-1 ; i++) {
5217: sump=sump+weight[i];
5218: /* sump=sump+1;*/
5219: num=num+1;
5220: }
5221:
5222:
5223: /* for (i=0; i<=imx; i++)
5224: 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]);*/
5225:
5226: for (i=1;i<=imx ; i++)
5227: {
5228: if (cens[i] == 1 && wav[i]>1)
5229: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5230:
5231: if (cens[i] == 0 && wav[i]>1)
5232: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5233: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5234:
5235: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5236: if (wav[i] > 1 ) { /* ??? */
5237: L=L+A*weight[i];
5238: /* 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]);*/
5239: }
5240: }
5241:
5242: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5243:
5244: return -2*L*num/sump;
5245: }
5246:
1.136 brouard 5247: #ifdef GSL
5248: /******************* Gompertz_f Likelihood ******************************/
5249: double gompertz_f(const gsl_vector *v, void *params)
5250: {
5251: double A,B,LL=0.0,sump=0.,num=0.;
5252: double *x= (double *) v->data;
5253: int i,n=0; /* n is the size of the sample */
5254:
5255: for (i=0;i<=imx-1 ; i++) {
5256: sump=sump+weight[i];
5257: /* sump=sump+1;*/
5258: num=num+1;
5259: }
5260:
5261:
5262: /* for (i=0; i<=imx; i++)
5263: 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]);*/
5264: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5265: for (i=1;i<=imx ; i++)
5266: {
5267: if (cens[i] == 1 && wav[i]>1)
5268: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5269:
5270: if (cens[i] == 0 && wav[i]>1)
5271: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5272: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5273:
5274: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5275: if (wav[i] > 1 ) { /* ??? */
5276: LL=LL+A*weight[i];
5277: /* 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]);*/
5278: }
5279: }
5280:
5281: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5282: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5283:
5284: return -2*LL*num/sump;
5285: }
5286: #endif
5287:
1.126 brouard 5288: /******************* Printing html file ***********/
5289: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5290: int lastpass, int stepm, int weightopt, char model[],\
5291: int imx, double p[],double **matcov,double agemortsup){
5292: int i,k;
5293:
5294: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5295: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5296: for (i=1;i<=2;i++)
5297: 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]));
5298: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5299: fprintf(fichtm,"</ul>");
5300:
5301: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5302:
5303: 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>");
5304:
5305: for (k=agegomp;k<(agemortsup-2);k++)
5306: 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]);
5307:
5308:
5309: fflush(fichtm);
5310: }
5311:
5312: /******************* Gnuplot file **************/
5313: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5314:
5315: char dirfileres[132],optfileres[132];
1.164 brouard 5316:
1.126 brouard 5317: int ng;
5318:
5319:
5320: /*#ifdef windows */
5321: fprintf(ficgp,"cd \"%s\" \n",pathc);
5322: /*#endif */
5323:
5324:
5325: strcpy(dirfileres,optionfilefiname);
5326: strcpy(optfileres,"vpl");
5327: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5328: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5329: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5330: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5331: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5332:
5333: }
5334:
1.136 brouard 5335: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5336: {
1.126 brouard 5337:
1.136 brouard 5338: /*-------- data file ----------*/
5339: FILE *fic;
5340: char dummy[]=" ";
1.164 brouard 5341: int i=0, j=0, n=0;
1.136 brouard 5342: int linei, month, year,iout;
5343: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5344: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5345: char *stratrunc;
5346: int lstra;
1.126 brouard 5347:
5348:
1.136 brouard 5349: if((fic=fopen(datafile,"r"))==NULL) {
5350: printf("Problem while opening datafile: %s\n", datafile);return 1;
5351: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5352: }
1.126 brouard 5353:
1.136 brouard 5354: i=1;
5355: linei=0;
5356: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5357: linei=linei+1;
5358: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5359: if(line[j] == '\t')
5360: line[j] = ' ';
5361: }
5362: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5363: ;
5364: };
5365: line[j+1]=0; /* Trims blanks at end of line */
5366: if(line[0]=='#'){
5367: fprintf(ficlog,"Comment line\n%s\n",line);
5368: printf("Comment line\n%s\n",line);
5369: continue;
5370: }
5371: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5372: strcpy(line, linetmp);
1.136 brouard 5373:
1.126 brouard 5374:
1.136 brouard 5375: for (j=maxwav;j>=1;j--){
1.137 brouard 5376: cutv(stra, strb, line, ' ');
1.136 brouard 5377: if(strb[0]=='.') { /* Missing status */
5378: lval=-1;
5379: }else{
5380: errno=0;
5381: lval=strtol(strb,&endptr,10);
5382: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5383: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5384: 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);
5385: 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 5386: return 1;
5387: }
5388: }
5389: s[j][i]=lval;
5390:
5391: strcpy(line,stra);
5392: cutv(stra, strb,line,' ');
1.169 brouard 5393: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5394: }
1.169 brouard 5395: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5396: month=99;
5397: year=9999;
5398: }else{
1.141 brouard 5399: 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);
5400: 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 5401: return 1;
5402: }
5403: anint[j][i]= (double) year;
5404: mint[j][i]= (double)month;
5405: strcpy(line,stra);
5406: } /* ENd Waves */
5407:
5408: cutv(stra, strb,line,' ');
1.169 brouard 5409: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5410: }
1.169 brouard 5411: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5412: month=99;
5413: year=9999;
5414: }else{
1.141 brouard 5415: 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);
5416: 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 5417: return 1;
5418: }
5419: andc[i]=(double) year;
5420: moisdc[i]=(double) month;
5421: strcpy(line,stra);
5422:
5423: cutv(stra, strb,line,' ');
1.169 brouard 5424: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5425: }
1.169 brouard 5426: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5427: month=99;
5428: year=9999;
5429: }else{
1.141 brouard 5430: 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);
5431: 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 5432: return 1;
5433: }
5434: if (year==9999) {
1.141 brouard 5435: 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);
5436: 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 5437: return 1;
1.126 brouard 5438:
1.136 brouard 5439: }
5440: annais[i]=(double)(year);
5441: moisnais[i]=(double)(month);
5442: strcpy(line,stra);
5443:
5444: cutv(stra, strb,line,' ');
5445: errno=0;
5446: dval=strtod(strb,&endptr);
5447: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5448: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5449: 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 5450: fflush(ficlog);
5451: return 1;
5452: }
5453: weight[i]=dval;
5454: strcpy(line,stra);
5455:
5456: for (j=ncovcol;j>=1;j--){
5457: cutv(stra, strb,line,' ');
5458: if(strb[0]=='.') { /* Missing status */
5459: lval=-1;
5460: }else{
5461: errno=0;
5462: lval=strtol(strb,&endptr,10);
5463: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5464: 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);
5465: 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 5466: return 1;
5467: }
5468: }
5469: if(lval <-1 || lval >1){
1.141 brouard 5470: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5471: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5472: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5473: For example, for multinomial values like 1, 2 and 3,\n \
5474: build V1=0 V2=0 for the reference value (1),\n \
5475: V1=1 V2=0 for (2) \n \
5476: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5477: output of IMaCh is often meaningless.\n \
5478: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5479: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5480: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5481: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5482: For example, for multinomial values like 1, 2 and 3,\n \
5483: build V1=0 V2=0 for the reference value (1),\n \
5484: V1=1 V2=0 for (2) \n \
5485: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5486: output of IMaCh is often meaningless.\n \
5487: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5488: return 1;
5489: }
5490: covar[j][i]=(double)(lval);
5491: strcpy(line,stra);
5492: }
5493: lstra=strlen(stra);
5494:
5495: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5496: stratrunc = &(stra[lstra-9]);
5497: num[i]=atol(stratrunc);
5498: }
5499: else
5500: num[i]=atol(stra);
5501: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5502: 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;}*/
5503:
5504: i=i+1;
5505: } /* End loop reading data */
1.126 brouard 5506:
1.136 brouard 5507: *imax=i-1; /* Number of individuals */
5508: fclose(fic);
5509:
5510: return (0);
1.164 brouard 5511: /* endread: */
1.136 brouard 5512: printf("Exiting readdata: ");
5513: fclose(fic);
5514: return (1);
1.126 brouard 5515:
5516:
5517:
1.136 brouard 5518: }
1.145 brouard 5519: void removespace(char *str) {
5520: char *p1 = str, *p2 = str;
5521: do
5522: while (*p2 == ' ')
5523: p2++;
1.169 brouard 5524: while (*p1++ == *p2++);
1.145 brouard 5525: }
5526:
5527: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5528: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5529: * - nagesqr = 1 if age*age in the model, otherwise 0.
5530: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5531: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5532: * - cptcovage number of covariates with age*products =2
5533: * - cptcovs number of simple covariates
5534: * - 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
5535: * which is a new column after the 9 (ncovcol) variables.
5536: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5537: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5538: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5539: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5540: */
1.136 brouard 5541: {
1.145 brouard 5542: int i, j, k, ks;
1.164 brouard 5543: int j1, k1, k2;
1.136 brouard 5544: char modelsav[80];
1.145 brouard 5545: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 5546: char *strpt;
1.136 brouard 5547:
1.145 brouard 5548: /*removespace(model);*/
1.136 brouard 5549: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5550: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 5551: if (strstr(model,"AGE") !=0){
1.187 brouard 5552: printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
5553: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
1.136 brouard 5554: return 1;
5555: }
1.141 brouard 5556: if (strstr(model,"v") !=0){
5557: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5558: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5559: return 1;
5560: }
1.187 brouard 5561: strcpy(modelsav,model);
5562: if ((strpt=strstr(model,"age*age")) !=0){
5563: printf(" strpt=%s, model=%s\n",strpt, model);
5564: if(strpt != model){
5565: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
5566: 'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
5567: corresponding column of parameters.\n",model);
5568: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
5569: 'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
5570: corresponding column of parameters.\n",model); fflush(ficlog);
5571: return 1;
5572: }
5573:
5574: nagesqr=1;
5575: if (strstr(model,"+age*age") !=0)
5576: substrchaine(modelsav, model, "+age*age");
5577: else if (strstr(model,"age*age+") !=0)
5578: substrchaine(modelsav, model, "age*age+");
5579: else
5580: substrchaine(modelsav, model, "age*age");
5581: }else
5582: nagesqr=0;
5583: if (strlen(modelsav) >1){
5584: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5585: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5586: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5587: cptcovt= j+1; /* Number of total covariates in the model, not including
5588: * cst, age and age*age
5589: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5590: /* including age products which are counted in cptcovage.
5591: * but the covariates which are products must be treated
5592: * separately: ncovn=4- 2=2 (V1+V3). */
5593: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5594: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5595:
5596:
5597: /* Design
5598: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5599: * < ncovcol=8 >
5600: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5601: * k= 1 2 3 4 5 6 7 8
5602: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5603: * covar[k,i], value of kth covariate if not including age for individual i:
5604: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5605: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5606: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5607: * Tage[++cptcovage]=k
5608: * if products, new covar are created after ncovcol with k1
5609: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5610: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5611: * 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
5612: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5613: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5614: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5615: * < ncovcol=8 >
5616: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5617: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5618: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5619: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5620: * p Tprod[1]@2={ 6, 5}
5621: *p Tvard[1][1]@4= {7, 8, 5, 6}
5622: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5623: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5624: *How to reorganize?
5625: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5626: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5627: * {2, 1, 4, 8, 5, 6, 3, 7}
5628: * Struct []
5629: */
1.145 brouard 5630:
1.187 brouard 5631: /* This loop fills the array Tvar from the string 'model'.*/
5632: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5633: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5634: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5635: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5636: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5637: /* k=1 Tvar[1]=2 (from V2) */
5638: /* k=5 Tvar[5] */
5639: /* for (k=1; k<=cptcovn;k++) { */
5640: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5641: /* } */
5642: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
5643: /*
5644: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5645: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 5646: Tvar[k]=0;
1.187 brouard 5647: cptcovage=0;
5648: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5649: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5650: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5651: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5652: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5653: /*scanf("%d",i);*/
5654: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5655: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5656: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5657: /* covar is not filled and then is empty */
5658: cptcovprod--;
5659: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5660: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5661: cptcovage++; /* Sums the number of covariates which include age as a product */
5662: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5663: /*printf("stre=%s ", stre);*/
5664: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5665: cptcovprod--;
5666: cutl(stre,strb,strc,'V');
5667: Tvar[k]=atoi(stre);
5668: cptcovage++;
5669: Tage[cptcovage]=k;
5670: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5671: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5672: cptcovn++;
5673: cptcovprodnoage++;k1++;
5674: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5675: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5676: because this model-covariate is a construction we invent a new column
5677: ncovcol + k1
5678: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5679: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5680: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5681: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5682: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5683: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5684: k2=k2+2;
5685: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5686: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5687: for (i=1; i<=lastobs;i++){
5688: /* Computes the new covariate which is a product of
5689: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5690: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5691: }
5692: } /* End age is not in the model */
5693: } /* End if model includes a product */
5694: else { /* no more sum */
5695: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5696: /* scanf("%d",i);*/
5697: cutl(strd,strc,strb,'V');
5698: ks++; /**< Number of simple covariates */
1.145 brouard 5699: cptcovn++;
1.187 brouard 5700: Tvar[k]=atoi(strd);
5701: }
5702: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5703: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5704: scanf("%d",i);*/
5705: } /* end of loop + on total covariates */
5706: } /* end if strlen(modelsave == 0) age*age might exist */
5707: } /* end if strlen(model == 0) */
1.136 brouard 5708:
5709: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5710: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5711:
5712: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5713: printf("cptcovprod=%d ", cptcovprod);
5714: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5715:
5716: scanf("%d ",i);*/
5717:
5718:
1.137 brouard 5719: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5720: /*endread:*/
1.136 brouard 5721: printf("Exiting decodemodel: ");
5722: return (1);
5723: }
5724:
1.169 brouard 5725: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5726: {
5727: int i, m;
5728:
5729: for (i=1; i<=imx; i++) {
5730: for(m=2; (m<= maxwav); m++) {
5731: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5732: anint[m][i]=9999;
5733: s[m][i]=-1;
5734: }
5735: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5736: *nberr = *nberr + 1;
5737: 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);
5738: 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 5739: s[m][i]=-1;
5740: }
5741: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5742: (*nberr)++;
1.136 brouard 5743: 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]);
5744: 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]);
5745: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5746: }
5747: }
5748: }
5749:
5750: for (i=1; i<=imx; i++) {
5751: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5752: for(m=firstpass; (m<= lastpass); m++){
5753: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5754: if (s[m][i] >= nlstate+1) {
1.169 brouard 5755: if(agedc[i]>0){
5756: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5757: agev[m][i]=agedc[i];
5758: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5759: }else {
1.136 brouard 5760: if ((int)andc[i]!=9999){
5761: nbwarn++;
5762: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5763: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5764: agev[m][i]=-1;
5765: }
5766: }
1.169 brouard 5767: } /* agedc > 0 */
1.136 brouard 5768: }
5769: else if(s[m][i] !=9){ /* Standard case, age in fractional
5770: years but with the precision of a month */
5771: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5772: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5773: agev[m][i]=1;
5774: else if(agev[m][i] < *agemin){
5775: *agemin=agev[m][i];
5776: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5777: }
5778: else if(agev[m][i] >*agemax){
5779: *agemax=agev[m][i];
1.156 brouard 5780: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5781: }
5782: /*agev[m][i]=anint[m][i]-annais[i];*/
5783: /* agev[m][i] = age[i]+2*m;*/
5784: }
5785: else { /* =9 */
5786: agev[m][i]=1;
5787: s[m][i]=-1;
5788: }
5789: }
5790: else /*= 0 Unknown */
5791: agev[m][i]=1;
5792: }
5793:
5794: }
5795: for (i=1; i<=imx; i++) {
5796: for(m=firstpass; (m<=lastpass); m++){
5797: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5798: (*nberr)++;
1.136 brouard 5799: 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);
5800: 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);
5801: return 1;
5802: }
5803: }
5804: }
5805:
5806: /*for (i=1; i<=imx; i++){
5807: for (m=firstpass; (m<lastpass); m++){
5808: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5809: }
5810:
5811: }*/
5812:
5813:
1.139 brouard 5814: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5815: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5816:
5817: return (0);
1.164 brouard 5818: /* endread:*/
1.136 brouard 5819: printf("Exiting calandcheckages: ");
5820: return (1);
5821: }
5822:
1.172 brouard 5823: #if defined(_MSC_VER)
5824: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5825: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5826: //#include "stdafx.h"
5827: //#include <stdio.h>
5828: //#include <tchar.h>
5829: //#include <windows.h>
5830: //#include <iostream>
5831: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5832:
5833: LPFN_ISWOW64PROCESS fnIsWow64Process;
5834:
5835: BOOL IsWow64()
5836: {
5837: BOOL bIsWow64 = FALSE;
5838:
5839: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5840: // (HANDLE, PBOOL);
5841:
5842: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5843:
5844: HMODULE module = GetModuleHandle(_T("kernel32"));
5845: const char funcName[] = "IsWow64Process";
5846: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5847: GetProcAddress(module, funcName);
5848:
5849: if (NULL != fnIsWow64Process)
5850: {
5851: if (!fnIsWow64Process(GetCurrentProcess(),
5852: &bIsWow64))
5853: //throw std::exception("Unknown error");
5854: printf("Unknown error\n");
5855: }
5856: return bIsWow64 != FALSE;
5857: }
5858: #endif
1.177 brouard 5859:
1.169 brouard 5860: void syscompilerinfo()
1.167 brouard 5861: {
5862: /* #include "syscompilerinfo.h"*/
1.185 brouard 5863: /* command line Intel compiler 32bit windows, XP compatible:*/
5864: /* /GS /W3 /Gy
5865: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5866: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5867: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 5868: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5869: */
5870: /* 64 bits */
1.185 brouard 5871: /*
5872: /GS /W3 /Gy
5873: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5874: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5875: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5876: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5877: /* Optimization are useless and O3 is slower than O2 */
5878: /*
5879: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
5880: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
5881: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
5882: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
5883: */
1.186 brouard 5884: /* Link is */ /* /OUT:"visual studio
1.185 brouard 5885: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
5886: /PDB:"visual studio
5887: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
5888: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
5889: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
5890: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
5891: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
5892: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
5893: uiAccess='false'"
5894: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
5895: /NOLOGO /TLBID:1
5896: */
1.177 brouard 5897: #if defined __INTEL_COMPILER
1.178 brouard 5898: #if defined(__GNUC__)
5899: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5900: #endif
1.177 brouard 5901: #elif defined(__GNUC__)
1.179 brouard 5902: #ifndef __APPLE__
1.174 brouard 5903: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5904: #endif
1.177 brouard 5905: struct utsname sysInfo;
1.178 brouard 5906: int cross = CROSS;
5907: if (cross){
5908: printf("Cross-");
5909: fprintf(ficlog, "Cross-");
5910: }
1.174 brouard 5911: #endif
5912:
1.171 brouard 5913: #include <stdint.h>
1.178 brouard 5914:
1.169 brouard 5915: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5916: #if defined(__clang__)
5917: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5918: #endif
5919: #if defined(__ICC) || defined(__INTEL_COMPILER)
5920: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5921: #endif
5922: #if defined(__GNUC__) || defined(__GNUG__)
5923: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5924: #endif
5925: #if defined(__HP_cc) || defined(__HP_aCC)
5926: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5927: #endif
5928: #if defined(__IBMC__) || defined(__IBMCPP__)
5929: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5930: #endif
5931: #if defined(_MSC_VER)
5932: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5933: #endif
5934: #if defined(__PGI)
5935: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5936: #endif
5937: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5938: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5939: #endif
1.174 brouard 5940: printf(" for ");fprintf(ficlog," for ");
1.169 brouard 5941:
1.167 brouard 5942: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5943: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5944: // Windows (x64 and x86)
1.174 brouard 5945: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 5946: #elif __unix__ // all unices, not all compilers
5947: // Unix
1.174 brouard 5948: printf("Unix ");fprintf(ficlog,"Unix ");
1.167 brouard 5949: #elif __linux__
5950: // linux
1.174 brouard 5951: printf("linux ");fprintf(ficlog,"linux ");
1.167 brouard 5952: #elif __APPLE__
1.174 brouard 5953: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5954: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167 brouard 5955: #endif
5956:
5957: /* __MINGW32__ */
5958: /* __CYGWIN__ */
5959: /* __MINGW64__ */
5960: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5961: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5962: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5963: /* _WIN64 // Defined for applications for Win64. */
5964: /* _M_X64 // Defined for compilations that target x64 processors. */
5965: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5966:
1.167 brouard 5967: #if UINTPTR_MAX == 0xffffffff
1.174 brouard 5968: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 5969: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174 brouard 5970: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 5971: #else
1.174 brouard 5972: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 5973: #endif
5974:
1.169 brouard 5975: #if defined(__GNUC__)
5976: # if defined(__GNUC_PATCHLEVEL__)
5977: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5978: + __GNUC_MINOR__ * 100 \
5979: + __GNUC_PATCHLEVEL__)
5980: # else
5981: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5982: + __GNUC_MINOR__ * 100)
5983: # endif
1.174 brouard 5984: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5985: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 5986:
5987: if (uname(&sysInfo) != -1) {
5988: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5989: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5990: }
5991: else
5992: perror("uname() error");
1.179 brouard 5993: //#ifndef __INTEL_COMPILER
5994: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 5995: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.179 brouard 5996: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 5997: #endif
1.169 brouard 5998: #endif
1.172 brouard 5999:
6000: // void main()
6001: // {
1.169 brouard 6002: #if defined(_MSC_VER)
1.174 brouard 6003: if (IsWow64()){
1.176 brouard 6004: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6005: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6006: }
6007: else{
1.176 brouard 6008: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178 brouard 6009: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6010: }
1.172 brouard 6011: // printf("\nPress Enter to continue...");
6012: // getchar();
6013: // }
6014:
1.169 brouard 6015: #endif
6016:
1.167 brouard 6017:
6018: }
1.136 brouard 6019:
1.180 brouard 6020: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6021: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6022: int i, j, k, i1 ;
6023: double ftolpl = 1.e-10;
6024: double age, agebase, agelim;
6025:
6026: strcpy(filerespl,"pl");
6027: strcat(filerespl,fileres);
6028: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6029: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6030: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6031: }
6032: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6033: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6034: pstamp(ficrespl);
6035: fprintf(ficrespl,"# Period (stable) prevalence \n");
6036: fprintf(ficrespl,"#Age ");
6037: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6038: fprintf(ficrespl,"\n");
6039:
6040: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6041:
6042: agebase=ageminpar;
6043: agelim=agemaxpar;
6044:
6045: i1=pow(2,cptcoveff);
6046: if (cptcovn < 1){i1=1;}
6047:
6048: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6049: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6050: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6051: k=k+1;
6052: /* to clean */
6053: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
6054: fprintf(ficrespl,"\n#******");
6055: printf("\n#******");
6056: fprintf(ficlog,"\n#******");
6057: for(j=1;j<=cptcoveff;j++) {
6058: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6059: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6060: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6061: }
6062: fprintf(ficrespl,"******\n");
6063: printf("******\n");
6064: fprintf(ficlog,"******\n");
6065:
6066: fprintf(ficrespl,"#Age ");
6067: for(j=1;j<=cptcoveff;j++) {
6068: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6069: }
6070: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6071: fprintf(ficrespl,"\n");
6072:
6073: for (age=agebase; age<=agelim; age++){
6074: /* for (age=agebase; age<=agebase; age++){ */
6075: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6076: fprintf(ficrespl,"%.0f ",age );
6077: for(j=1;j<=cptcoveff;j++)
6078: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6079: for(i=1; i<=nlstate;i++)
6080: fprintf(ficrespl," %.5f", prlim[i][i]);
6081: fprintf(ficrespl,"\n");
6082: } /* Age */
6083: /* was end of cptcod */
6084: } /* cptcov */
1.184 brouard 6085: return 0;
1.180 brouard 6086: }
6087:
6088: int hPijx(double *p, int bage, int fage){
6089: /*------------- h Pij x at various ages ------------*/
6090:
6091: int stepsize;
6092: int agelim;
6093: int hstepm;
6094: int nhstepm;
6095: int h, i, i1, j, k;
6096:
6097: double agedeb;
6098: double ***p3mat;
6099:
6100: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6101: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6102: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6103: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6104: }
6105: printf("Computing pij: result on file '%s' \n", filerespij);
6106: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6107:
6108: stepsize=(int) (stepm+YEARM-1)/YEARM;
6109: /*if (stepm<=24) stepsize=2;*/
6110:
6111: agelim=AGESUP;
6112: hstepm=stepsize*YEARM; /* Every year of age */
6113: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6114:
6115: /* hstepm=1; aff par mois*/
6116: pstamp(ficrespij);
6117: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6118: i1= pow(2,cptcoveff);
1.183 brouard 6119: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6120: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6121: /* k=k+1; */
6122: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6123: fprintf(ficrespij,"\n#****** ");
6124: for(j=1;j<=cptcoveff;j++)
6125: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6126: fprintf(ficrespij,"******\n");
6127:
6128: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6129: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6130: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6131:
6132: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6133:
1.183 brouard 6134: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6135: oldm=oldms;savm=savms;
6136: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6137: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6138: for(i=1; i<=nlstate;i++)
6139: for(j=1; j<=nlstate+ndeath;j++)
6140: fprintf(ficrespij," %1d-%1d",i,j);
6141: fprintf(ficrespij,"\n");
6142: for (h=0; h<=nhstepm; h++){
6143: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6144: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6145: for(i=1; i<=nlstate;i++)
6146: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6147: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6148: fprintf(ficrespij,"\n");
6149: }
1.183 brouard 6150: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6151: fprintf(ficrespij,"\n");
6152: }
1.180 brouard 6153: /*}*/
6154: }
1.184 brouard 6155: return 0;
1.180 brouard 6156: }
6157:
6158:
1.136 brouard 6159: /***********************************************/
6160: /**************** Main Program *****************/
6161: /***********************************************/
6162:
6163: int main(int argc, char *argv[])
6164: {
6165: #ifdef GSL
6166: const gsl_multimin_fminimizer_type *T;
6167: size_t iteri = 0, it;
6168: int rval = GSL_CONTINUE;
6169: int status = GSL_SUCCESS;
6170: double ssval;
6171: #endif
6172: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6173: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6174:
6175: int jj, ll, li, lj, lk;
1.136 brouard 6176: int numlinepar=0; /* Current linenumber of parameter file */
6177: int itimes;
6178: int NDIM=2;
6179: int vpopbased=0;
6180:
1.164 brouard 6181: char ca[32], cb[32];
1.136 brouard 6182: /* FILE *fichtm; *//* Html File */
6183: /* FILE *ficgp;*/ /*Gnuplot File */
6184: struct stat info;
1.164 brouard 6185: double agedeb;
1.136 brouard 6186: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
6187:
1.165 brouard 6188: double fret;
1.136 brouard 6189: double dum; /* Dummy variable */
6190: double ***p3mat;
6191: double ***mobaverage;
1.164 brouard 6192:
6193: char line[MAXLINE];
1.136 brouard 6194: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
6195: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6196: char *tok, *val; /* pathtot */
1.136 brouard 6197: int firstobs=1, lastobs=10;
1.164 brouard 6198: int c, h , cpt;
6199: int jl;
6200: int i1, j1, jk, stepsize;
6201: int *tab;
1.136 brouard 6202: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6203: int mobilav=0,popforecast=0;
6204: int hstepm, nhstepm;
6205: int agemortsup;
6206: float sumlpop=0.;
6207: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6208: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6209:
1.164 brouard 6210: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 6211: double ftolpl=FTOL;
6212: double **prlim;
6213: double ***param; /* Matrix of parameters */
6214: double *p;
6215: double **matcov; /* Matrix of covariance */
6216: double ***delti3; /* Scale */
6217: double *delti; /* Scale */
6218: double ***eij, ***vareij;
6219: double **varpl; /* Variances of prevalence limits by age */
6220: double *epj, vepp;
1.164 brouard 6221:
1.136 brouard 6222: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6223: double **ximort;
1.145 brouard 6224: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6225: int *dcwave;
6226:
1.164 brouard 6227: char z[1]="c";
1.136 brouard 6228:
6229: /*char *strt;*/
6230: char strtend[80];
1.126 brouard 6231:
1.164 brouard 6232:
1.126 brouard 6233: /* setlocale (LC_ALL, ""); */
6234: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6235: /* textdomain (PACKAGE); */
6236: /* setlocale (LC_CTYPE, ""); */
6237: /* setlocale (LC_MESSAGES, ""); */
6238:
6239: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6240: rstart_time = time(NULL);
6241: /* (void) gettimeofday(&start_time,&tzp);*/
6242: start_time = *localtime(&rstart_time);
1.126 brouard 6243: curr_time=start_time;
1.157 brouard 6244: /*tml = *localtime(&start_time.tm_sec);*/
6245: /* strcpy(strstart,asctime(&tml)); */
6246: strcpy(strstart,asctime(&start_time));
1.126 brouard 6247:
6248: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6249: /* tp.tm_sec = tp.tm_sec +86400; */
6250: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6251: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6252: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6253: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6254: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6255: /* strt=asctime(&tmg); */
6256: /* printf("Time(after) =%s",strstart); */
6257: /* (void) time (&time_value);
6258: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6259: * tm = *localtime(&time_value);
6260: * strstart=asctime(&tm);
6261: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6262: */
6263:
6264: nberr=0; /* Number of errors and warnings */
6265: nbwarn=0;
1.184 brouard 6266: #ifdef WIN32
6267: _getcwd(pathcd, size);
6268: #else
1.126 brouard 6269: getcwd(pathcd, size);
1.184 brouard 6270: #endif
1.126 brouard 6271:
6272: printf("\n%s\n%s",version,fullversion);
6273: if(argc <=1){
6274: printf("\nEnter the parameter file name: ");
6275: fgets(pathr,FILENAMELENGTH,stdin);
6276: i=strlen(pathr);
6277: if(pathr[i-1]=='\n')
6278: pathr[i-1]='\0';
1.156 brouard 6279: i=strlen(pathr);
6280: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6281: pathr[i-1]='\0';
1.126 brouard 6282: for (tok = pathr; tok != NULL; ){
6283: printf("Pathr |%s|\n",pathr);
6284: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6285: printf("val= |%s| pathr=%s\n",val,pathr);
6286: strcpy (pathtot, val);
6287: if(pathr[0] == '\0') break; /* Dirty */
6288: }
6289: }
6290: else{
6291: strcpy(pathtot,argv[1]);
6292: }
6293: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6294: /*cygwin_split_path(pathtot,path,optionfile);
6295: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6296: /* cutv(path,optionfile,pathtot,'\\');*/
6297:
6298: /* Split argv[0], imach program to get pathimach */
6299: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6300: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6301: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6302: /* strcpy(pathimach,argv[0]); */
6303: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6304: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6305: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6306: #ifdef WIN32
6307: _chdir(path); /* Can be a relative path */
6308: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6309: #else
1.126 brouard 6310: chdir(path); /* Can be a relative path */
1.184 brouard 6311: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6312: #endif
6313: printf("Current directory %s!\n",pathcd);
1.126 brouard 6314: strcpy(command,"mkdir ");
6315: strcat(command,optionfilefiname);
6316: if((outcmd=system(command)) != 0){
1.169 brouard 6317: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6318: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6319: /* fclose(ficlog); */
6320: /* exit(1); */
6321: }
6322: /* if((imk=mkdir(optionfilefiname))<0){ */
6323: /* perror("mkdir"); */
6324: /* } */
6325:
6326: /*-------- arguments in the command line --------*/
6327:
1.186 brouard 6328: /* Main Log file */
1.126 brouard 6329: strcat(filelog, optionfilefiname);
6330: strcat(filelog,".log"); /* */
6331: if((ficlog=fopen(filelog,"w"))==NULL) {
6332: printf("Problem with logfile %s\n",filelog);
6333: goto end;
6334: }
6335: fprintf(ficlog,"Log filename:%s\n",filelog);
6336: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6337: fprintf(ficlog,"\nEnter the parameter file name: \n");
6338: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6339: path=%s \n\
6340: optionfile=%s\n\
6341: optionfilext=%s\n\
1.156 brouard 6342: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6343:
1.167 brouard 6344: syscompilerinfo();
6345:
1.126 brouard 6346: printf("Local time (at start):%s",strstart);
6347: fprintf(ficlog,"Local time (at start): %s",strstart);
6348: fflush(ficlog);
6349: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6350: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6351:
6352: /* */
6353: strcpy(fileres,"r");
6354: strcat(fileres, optionfilefiname);
6355: strcat(fileres,".txt"); /* Other files have txt extension */
6356:
1.186 brouard 6357: /* Main ---------arguments file --------*/
1.126 brouard 6358:
6359: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6360: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6361: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6362: fflush(ficlog);
1.149 brouard 6363: /* goto end; */
6364: exit(70);
1.126 brouard 6365: }
6366:
6367:
6368:
6369: strcpy(filereso,"o");
6370: strcat(filereso,fileres);
6371: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6372: printf("Problem with Output resultfile: %s\n", filereso);
6373: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6374: fflush(ficlog);
6375: goto end;
6376: }
6377:
6378: /* Reads comments: lines beginning with '#' */
6379: numlinepar=0;
6380: while((c=getc(ficpar))=='#' && c!= EOF){
6381: ungetc(c,ficpar);
6382: fgets(line, MAXLINE, ficpar);
6383: numlinepar++;
1.141 brouard 6384: fputs(line,stdout);
1.126 brouard 6385: fputs(line,ficparo);
6386: fputs(line,ficlog);
6387: }
6388: ungetc(c,ficpar);
6389:
1.187 brouard 6390: fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
1.126 brouard 6391: numlinepar++;
1.187 brouard 6392: 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);
6393: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6394: model[strlen(model)-1]='\0';
6395: 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);
6396: 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 6397: fflush(ficlog);
1.187 brouard 6398: if(model[0]=='#'|| model[0]== '\0'){
6399: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6400: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6401: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6402: if(mle != -1){
6403: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6404: exit(1);
6405: }
6406: }
1.126 brouard 6407: while((c=getc(ficpar))=='#' && c!= EOF){
6408: ungetc(c,ficpar);
6409: fgets(line, MAXLINE, ficpar);
6410: numlinepar++;
1.141 brouard 6411: fputs(line, stdout);
6412: //puts(line);
1.126 brouard 6413: fputs(line,ficparo);
6414: fputs(line,ficlog);
6415: }
6416: ungetc(c,ficpar);
6417:
6418:
1.145 brouard 6419: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6420: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6421: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6422: v1+v2*age+v2*v3 makes cptcovn = 3
6423: */
6424: if (strlen(model)>1)
1.187 brouard 6425: 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 6426: else
1.187 brouard 6427: ncovmodel=2; /* Constant and age */
1.133 brouard 6428: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6429: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6430: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6431: 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);
6432: 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);
6433: fflush(stdout);
6434: fclose (ficlog);
6435: goto end;
6436: }
1.126 brouard 6437: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6438: delti=delti3[1][1];
6439: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6440: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6441: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6442: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6443: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6444: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6445: fclose (ficparo);
6446: fclose (ficlog);
6447: goto end;
6448: exit(0);
6449: }
1.186 brouard 6450: else if(mle==-3) { /* Main Wizard */
1.126 brouard 6451: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6452: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6453: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6454: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6455: matcov=matrix(1,npar,1,npar);
6456: }
6457: else{
1.145 brouard 6458: /* Read guessed parameters */
1.126 brouard 6459: /* Reads comments: lines beginning with '#' */
6460: while((c=getc(ficpar))=='#' && c!= EOF){
6461: ungetc(c,ficpar);
6462: fgets(line, MAXLINE, ficpar);
6463: numlinepar++;
1.141 brouard 6464: fputs(line,stdout);
1.126 brouard 6465: fputs(line,ficparo);
6466: fputs(line,ficlog);
6467: }
6468: ungetc(c,ficpar);
6469:
6470: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6471: for(i=1; i <=nlstate; i++){
6472: j=0;
6473: for(jj=1; jj <=nlstate+ndeath; jj++){
6474: if(jj==i) continue;
6475: j++;
6476: fscanf(ficpar,"%1d%1d",&i1,&j1);
6477: if ((i1 != i) && (j1 != j)){
6478: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6479: It might be a problem of design; if ncovcol and the model are correct\n \
6480: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6481: exit(1);
6482: }
6483: fprintf(ficparo,"%1d%1d",i1,j1);
6484: if(mle==1)
6485: printf("%1d%1d",i,j);
6486: fprintf(ficlog,"%1d%1d",i,j);
6487: for(k=1; k<=ncovmodel;k++){
6488: fscanf(ficpar," %lf",¶m[i][j][k]);
6489: if(mle==1){
6490: printf(" %lf",param[i][j][k]);
6491: fprintf(ficlog," %lf",param[i][j][k]);
6492: }
6493: else
6494: fprintf(ficlog," %lf",param[i][j][k]);
6495: fprintf(ficparo," %lf",param[i][j][k]);
6496: }
6497: fscanf(ficpar,"\n");
6498: numlinepar++;
6499: if(mle==1)
6500: printf("\n");
6501: fprintf(ficlog,"\n");
6502: fprintf(ficparo,"\n");
6503: }
6504: }
6505: fflush(ficlog);
6506:
1.145 brouard 6507: /* Reads scales values */
1.126 brouard 6508: p=param[1][1];
6509:
6510: /* Reads comments: lines beginning with '#' */
6511: while((c=getc(ficpar))=='#' && c!= EOF){
6512: ungetc(c,ficpar);
6513: fgets(line, MAXLINE, ficpar);
6514: numlinepar++;
1.141 brouard 6515: fputs(line,stdout);
1.126 brouard 6516: fputs(line,ficparo);
6517: fputs(line,ficlog);
6518: }
6519: ungetc(c,ficpar);
6520:
6521: for(i=1; i <=nlstate; i++){
6522: for(j=1; j <=nlstate+ndeath-1; j++){
6523: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6524: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6525: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6526: exit(1);
6527: }
6528: printf("%1d%1d",i,j);
6529: fprintf(ficparo,"%1d%1d",i1,j1);
6530: fprintf(ficlog,"%1d%1d",i1,j1);
6531: for(k=1; k<=ncovmodel;k++){
6532: fscanf(ficpar,"%le",&delti3[i][j][k]);
6533: printf(" %le",delti3[i][j][k]);
6534: fprintf(ficparo," %le",delti3[i][j][k]);
6535: fprintf(ficlog," %le",delti3[i][j][k]);
6536: }
6537: fscanf(ficpar,"\n");
6538: numlinepar++;
6539: printf("\n");
6540: fprintf(ficparo,"\n");
6541: fprintf(ficlog,"\n");
6542: }
6543: }
6544: fflush(ficlog);
6545:
1.145 brouard 6546: /* Reads covariance matrix */
1.126 brouard 6547: delti=delti3[1][1];
6548:
6549:
6550: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6551:
6552: /* Reads comments: lines beginning with '#' */
6553: while((c=getc(ficpar))=='#' && c!= EOF){
6554: ungetc(c,ficpar);
6555: fgets(line, MAXLINE, ficpar);
6556: numlinepar++;
1.141 brouard 6557: fputs(line,stdout);
1.126 brouard 6558: fputs(line,ficparo);
6559: fputs(line,ficlog);
6560: }
6561: ungetc(c,ficpar);
6562:
6563: matcov=matrix(1,npar,1,npar);
1.131 brouard 6564: for(i=1; i <=npar; i++)
6565: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6566:
1.126 brouard 6567: for(i=1; i <=npar; i++){
1.145 brouard 6568: fscanf(ficpar,"%s",str);
1.126 brouard 6569: if(mle==1)
6570: printf("%s",str);
6571: fprintf(ficlog,"%s",str);
6572: fprintf(ficparo,"%s",str);
6573: for(j=1; j <=i; j++){
6574: fscanf(ficpar," %le",&matcov[i][j]);
6575: if(mle==1){
6576: printf(" %.5le",matcov[i][j]);
6577: }
6578: fprintf(ficlog," %.5le",matcov[i][j]);
6579: fprintf(ficparo," %.5le",matcov[i][j]);
6580: }
6581: fscanf(ficpar,"\n");
6582: numlinepar++;
6583: if(mle==1)
6584: printf("\n");
6585: fprintf(ficlog,"\n");
6586: fprintf(ficparo,"\n");
6587: }
6588: for(i=1; i <=npar; i++)
6589: for(j=i+1;j<=npar;j++)
6590: matcov[i][j]=matcov[j][i];
6591:
6592: if(mle==1)
6593: printf("\n");
6594: fprintf(ficlog,"\n");
6595:
6596: fflush(ficlog);
6597:
6598: /*-------- Rewriting parameter file ----------*/
6599: strcpy(rfileres,"r"); /* "Rparameterfile */
6600: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6601: strcat(rfileres,"."); /* */
6602: strcat(rfileres,optionfilext); /* Other files have txt extension */
6603: if((ficres =fopen(rfileres,"w"))==NULL) {
6604: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6605: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6606: }
6607: fprintf(ficres,"#%s\n",version);
6608: } /* End of mle != -3 */
6609:
1.186 brouard 6610: /* Main data
6611: */
1.126 brouard 6612: n= lastobs;
6613: num=lvector(1,n);
6614: moisnais=vector(1,n);
6615: annais=vector(1,n);
6616: moisdc=vector(1,n);
6617: andc=vector(1,n);
6618: agedc=vector(1,n);
6619: cod=ivector(1,n);
6620: weight=vector(1,n);
6621: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6622: mint=matrix(1,maxwav,1,n);
6623: anint=matrix(1,maxwav,1,n);
1.131 brouard 6624: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6625: tab=ivector(1,NCOVMAX);
1.144 brouard 6626: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6627:
1.136 brouard 6628: /* Reads data from file datafile */
6629: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6630: goto end;
6631:
6632: /* Calculation of the number of parameters from char model */
1.137 brouard 6633: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6634: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6635: k=3 V4 Tvar[k=3]= 4 (from V4)
6636: k=2 V1 Tvar[k=2]= 1 (from V1)
6637: k=1 Tvar[1]=2 (from V2)
6638: */
6639: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6640: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6641: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6642: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6643: */
6644: /* For model-covariate k tells which data-covariate to use but
6645: because this model-covariate is a construction we invent a new column
6646: ncovcol + k1
6647: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6648: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6649: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6650: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6651: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6652: */
1.145 brouard 6653: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6654: 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 6655: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6656: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6657: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6658: 4 covariates (3 plus signs)
6659: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6660: */
1.136 brouard 6661:
1.186 brouard 6662: /* Main decodemodel */
6663:
1.187 brouard 6664:
1.136 brouard 6665: if(decodemodel(model, lastobs) == 1)
6666: goto end;
6667:
1.137 brouard 6668: if((double)(lastobs-imx)/(double)imx > 1.10){
6669: nbwarn++;
6670: 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);
6671: 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);
6672: }
1.136 brouard 6673: /* if(mle==1){*/
1.137 brouard 6674: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6675: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6676: }
6677:
6678: /*-calculation of age at interview from date of interview and age at death -*/
6679: agev=matrix(1,maxwav,1,imx);
6680:
6681: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6682: goto end;
6683:
1.126 brouard 6684:
1.136 brouard 6685: agegomp=(int)agemin;
6686: free_vector(moisnais,1,n);
6687: free_vector(annais,1,n);
1.126 brouard 6688: /* free_matrix(mint,1,maxwav,1,n);
6689: free_matrix(anint,1,maxwav,1,n);*/
6690: free_vector(moisdc,1,n);
6691: free_vector(andc,1,n);
1.145 brouard 6692: /* */
6693:
1.126 brouard 6694: wav=ivector(1,imx);
6695: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6696: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6697: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6698:
6699: /* Concatenates waves */
6700: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6701: /* */
6702:
1.126 brouard 6703: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6704:
6705: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6706: ncodemax[1]=1;
1.145 brouard 6707: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 6708: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 6709: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 6710: /* Nbcode gives the value of the lth modality of jth covariate, in
6711: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6712: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 6713:
6714: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6715: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186 brouard 6716: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 6717: h=0;
6718:
6719:
6720: /*if (cptcovn > 0) */
1.126 brouard 6721:
1.145 brouard 6722:
1.126 brouard 6723: m=pow(2,cptcoveff);
6724:
1.131 brouard 6725: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6726: 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 */
6727: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6728: 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 6729: h++;
1.141 brouard 6730: if (h>m)
1.136 brouard 6731: h=1;
1.144 brouard 6732: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 6733: * For k=4 covariates, h goes from 1 to 2**k
6734: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6735: * h\k 1 2 3 4
1.143 brouard 6736: *______________________________
6737: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6738: * 2 2 1 1 1
6739: * 3 i=2 1 2 1 1
6740: * 4 2 2 1 1
6741: * 5 i=3 1 i=2 1 2 1
6742: * 6 2 1 2 1
6743: * 7 i=4 1 2 2 1
6744: * 8 2 2 2 1
6745: * 9 i=5 1 i=3 1 i=2 1 1
6746: * 10 2 1 1 1
6747: * 11 i=6 1 2 1 1
6748: * 12 2 2 1 1
6749: * 13 i=7 1 i=4 1 2 1
6750: * 14 2 1 2 1
6751: * 15 i=8 1 2 2 1
6752: * 16 2 2 2 1
6753: */
1.141 brouard 6754: codtab[h][k]=j;
1.186 brouard 6755: /* codtab[12][3]=1; */
1.145 brouard 6756: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6757: 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 6758: }
6759: }
6760: }
6761: }
6762: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6763: codtab[1][2]=1;codtab[2][2]=2; */
6764: /* for(i=1; i <=m ;i++){
6765: for(k=1; k <=cptcovn; k++){
1.131 brouard 6766: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6767: }
6768: printf("\n");
6769: }
6770: scanf("%d",i);*/
1.145 brouard 6771:
6772: free_ivector(Ndum,-1,NCOVMAX);
6773:
6774:
1.126 brouard 6775:
1.186 brouard 6776: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 6777: strcpy(optionfilegnuplot,optionfilefiname);
6778: if(mle==-3)
6779: strcat(optionfilegnuplot,"-mort");
6780: strcat(optionfilegnuplot,".gp");
6781:
6782: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6783: printf("Problem with file %s",optionfilegnuplot);
6784: }
6785: else{
6786: fprintf(ficgp,"\n# %s\n", version);
6787: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6788: //fprintf(ficgp,"set missing 'NaNq'\n");
6789: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6790: }
6791: /* fclose(ficgp);*/
1.186 brouard 6792:
6793:
6794: /* Initialisation of --------- index.htm --------*/
1.126 brouard 6795:
6796: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6797: if(mle==-3)
6798: strcat(optionfilehtm,"-mort");
6799: strcat(optionfilehtm,".htm");
6800: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6801: printf("Problem with %s \n",optionfilehtm);
6802: exit(0);
1.126 brouard 6803: }
6804:
6805: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6806: strcat(optionfilehtmcov,"-cov.htm");
6807: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6808: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6809: }
6810: else{
6811: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6812: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6813: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6814: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6815: }
6816:
6817: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6818: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6819: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6820: \n\
6821: <hr size=\"2\" color=\"#EC5E5E\">\
6822: <ul><li><h4>Parameter files</h4>\n\
6823: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6824: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6825: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6826: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6827: - Date and time at start: %s</ul>\n",\
6828: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6829: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6830: fileres,fileres,\
6831: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6832: fflush(fichtm);
6833:
6834: strcpy(pathr,path);
6835: strcat(pathr,optionfilefiname);
1.184 brouard 6836: #ifdef WIN32
6837: _chdir(optionfilefiname); /* Move to directory named optionfile */
6838: #else
1.126 brouard 6839: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 6840: #endif
6841:
1.126 brouard 6842:
6843: /* Calculates basic frequencies. Computes observed prevalence at single age
6844: and prints on file fileres'p'. */
6845: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6846:
6847: fprintf(fichtm,"\n");
6848: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6849: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6850: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6851: imx,agemin,agemax,jmin,jmax,jmean);
6852: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6853: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6854: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6855: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6856: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6857:
6858:
6859: /* For Powell, parameters are in a vector p[] starting at p[1]
6860: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6861: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6862:
6863: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 6864: /* For mortality only */
1.126 brouard 6865: if (mle==-3){
1.136 brouard 6866: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 6867: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6868: cens=ivector(1,n);
6869: ageexmed=vector(1,n);
6870: agecens=vector(1,n);
6871: dcwave=ivector(1,n);
6872:
6873: for (i=1; i<=imx; i++){
6874: dcwave[i]=-1;
6875: for (m=firstpass; m<=lastpass; m++)
6876: if (s[m][i]>nlstate) {
6877: dcwave[i]=m;
6878: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6879: break;
6880: }
6881: }
6882:
6883: for (i=1; i<=imx; i++) {
6884: if (wav[i]>0){
6885: ageexmed[i]=agev[mw[1][i]][i];
6886: j=wav[i];
6887: agecens[i]=1.;
6888:
6889: if (ageexmed[i]> 1 && wav[i] > 0){
6890: agecens[i]=agev[mw[j][i]][i];
6891: cens[i]= 1;
6892: }else if (ageexmed[i]< 1)
6893: cens[i]= -1;
6894: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6895: cens[i]=0 ;
6896: }
6897: else cens[i]=-1;
6898: }
6899:
6900: for (i=1;i<=NDIM;i++) {
6901: for (j=1;j<=NDIM;j++)
6902: ximort[i][j]=(i == j ? 1.0 : 0.0);
6903: }
6904:
1.145 brouard 6905: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6906: /*printf("%lf %lf", p[1], p[2]);*/
6907:
6908:
1.136 brouard 6909: #ifdef GSL
6910: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6911: #else
1.126 brouard 6912: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6913: #endif
1.126 brouard 6914: strcpy(filerespow,"pow-mort");
6915: strcat(filerespow,fileres);
6916: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6917: printf("Problem with resultfile: %s\n", filerespow);
6918: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6919: }
1.136 brouard 6920: #ifdef GSL
6921: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6922: #else
1.126 brouard 6923: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6924: #endif
1.126 brouard 6925: /* for (i=1;i<=nlstate;i++)
6926: for(j=1;j<=nlstate+ndeath;j++)
6927: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6928: */
6929: fprintf(ficrespow,"\n");
1.136 brouard 6930: #ifdef GSL
6931: /* gsl starts here */
6932: T = gsl_multimin_fminimizer_nmsimplex;
6933: gsl_multimin_fminimizer *sfm = NULL;
6934: gsl_vector *ss, *x;
6935: gsl_multimin_function minex_func;
6936:
6937: /* Initial vertex size vector */
6938: ss = gsl_vector_alloc (NDIM);
6939:
6940: if (ss == NULL){
6941: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6942: }
6943: /* Set all step sizes to 1 */
6944: gsl_vector_set_all (ss, 0.001);
6945:
6946: /* Starting point */
1.126 brouard 6947:
1.136 brouard 6948: x = gsl_vector_alloc (NDIM);
6949:
6950: if (x == NULL){
6951: gsl_vector_free(ss);
6952: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6953: }
6954:
6955: /* Initialize method and iterate */
6956: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 6957: /* gsl_vector_set(x, 0, 0.0268); */
6958: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 6959: gsl_vector_set(x, 0, p[1]);
6960: gsl_vector_set(x, 1, p[2]);
6961:
6962: minex_func.f = &gompertz_f;
6963: minex_func.n = NDIM;
6964: minex_func.params = (void *)&p; /* ??? */
6965:
6966: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6967: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6968:
6969: printf("Iterations beginning .....\n\n");
6970: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6971:
6972: iteri=0;
6973: while (rval == GSL_CONTINUE){
6974: iteri++;
6975: status = gsl_multimin_fminimizer_iterate(sfm);
6976:
6977: if (status) printf("error: %s\n", gsl_strerror (status));
6978: fflush(0);
6979:
6980: if (status)
6981: break;
6982:
6983: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6984: ssval = gsl_multimin_fminimizer_size (sfm);
6985:
6986: if (rval == GSL_SUCCESS)
6987: printf ("converged to a local maximum at\n");
6988:
6989: printf("%5d ", iteri);
6990: for (it = 0; it < NDIM; it++){
6991: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6992: }
6993: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6994: }
6995:
6996: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6997:
6998: gsl_vector_free(x); /* initial values */
6999: gsl_vector_free(ss); /* inital step size */
7000: for (it=0; it<NDIM; it++){
7001: p[it+1]=gsl_vector_get(sfm->x,it);
7002: fprintf(ficrespow," %.12lf", p[it]);
7003: }
7004: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7005: #endif
7006: #ifdef POWELL
7007: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7008: #endif
1.126 brouard 7009: fclose(ficrespow);
7010:
7011: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7012:
7013: for(i=1; i <=NDIM; i++)
7014: for(j=i+1;j<=NDIM;j++)
7015: matcov[i][j]=matcov[j][i];
7016:
7017: printf("\nCovariance matrix\n ");
7018: for(i=1; i <=NDIM; i++) {
7019: for(j=1;j<=NDIM;j++){
7020: printf("%f ",matcov[i][j]);
7021: }
7022: printf("\n ");
7023: }
7024:
7025: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7026: for (i=1;i<=NDIM;i++)
7027: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7028:
7029: lsurv=vector(1,AGESUP);
7030: lpop=vector(1,AGESUP);
7031: tpop=vector(1,AGESUP);
7032: lsurv[agegomp]=100000;
7033:
7034: for (k=agegomp;k<=AGESUP;k++) {
7035: agemortsup=k;
7036: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7037: }
7038:
7039: for (k=agegomp;k<agemortsup;k++)
7040: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7041:
7042: for (k=agegomp;k<agemortsup;k++){
7043: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7044: sumlpop=sumlpop+lpop[k];
7045: }
7046:
7047: tpop[agegomp]=sumlpop;
7048: for (k=agegomp;k<(agemortsup-3);k++){
7049: /* tpop[k+1]=2;*/
7050: tpop[k+1]=tpop[k]-lpop[k];
7051: }
7052:
7053:
7054: printf("\nAge lx qx dx Lx Tx e(x)\n");
7055: for (k=agegomp;k<(agemortsup-2);k++)
7056: 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]);
7057:
7058:
7059: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7060: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7061:
7062: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7063: stepm, weightopt,\
7064: model,imx,p,matcov,agemortsup);
7065:
7066: free_vector(lsurv,1,AGESUP);
7067: free_vector(lpop,1,AGESUP);
7068: free_vector(tpop,1,AGESUP);
1.136 brouard 7069: #ifdef GSL
7070: free_ivector(cens,1,n);
7071: free_vector(agecens,1,n);
7072: free_ivector(dcwave,1,n);
7073: free_matrix(ximort,1,NDIM,1,NDIM);
7074: #endif
1.186 brouard 7075: } /* Endof if mle==-3 mortality only */
7076: /* Standard maximisation */
1.126 brouard 7077: else{ /* For mle >=1 */
1.132 brouard 7078: globpr=0;/* debug */
1.186 brouard 7079: /* Computes likelihood for initial parameters */
1.132 brouard 7080: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7081: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7082: for (k=1; k<=npar;k++)
7083: printf(" %d %8.5f",k,p[k]);
7084: printf("\n");
1.186 brouard 7085: globpr=1; /* again, to print the contributions */
1.126 brouard 7086: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7087: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7088: for (k=1; k<=npar;k++)
7089: printf(" %d %8.5f",k,p[k]);
7090: printf("\n");
1.186 brouard 7091: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126 brouard 7092: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7093: }
7094:
7095: /*--------- results files --------------*/
1.187 brouard 7096: 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 7097:
7098:
7099: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7100: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7101: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7102: for(i=1,jk=1; i <=nlstate; i++){
7103: for(k=1; k <=(nlstate+ndeath); k++){
7104: if (k != i) {
7105: printf("%d%d ",i,k);
7106: fprintf(ficlog,"%d%d ",i,k);
7107: fprintf(ficres,"%1d%1d ",i,k);
7108: for(j=1; j <=ncovmodel; j++){
7109: printf("%lf ",p[jk]);
7110: fprintf(ficlog,"%lf ",p[jk]);
7111: fprintf(ficres,"%lf ",p[jk]);
7112: jk++;
7113: }
7114: printf("\n");
7115: fprintf(ficlog,"\n");
7116: fprintf(ficres,"\n");
7117: }
7118: }
7119: }
7120: if(mle!=0){
7121: /* Computing hessian and covariance matrix */
7122: ftolhess=ftol; /* Usually correct */
7123: hesscov(matcov, p, npar, delti, ftolhess, func);
7124: }
7125: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7126: printf("# Scales (for hessian or gradient estimation)\n");
7127: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7128: for(i=1,jk=1; i <=nlstate; i++){
7129: for(j=1; j <=nlstate+ndeath; j++){
7130: if (j!=i) {
7131: fprintf(ficres,"%1d%1d",i,j);
7132: printf("%1d%1d",i,j);
7133: fprintf(ficlog,"%1d%1d",i,j);
7134: for(k=1; k<=ncovmodel;k++){
7135: printf(" %.5e",delti[jk]);
7136: fprintf(ficlog," %.5e",delti[jk]);
7137: fprintf(ficres," %.5e",delti[jk]);
7138: jk++;
7139: }
7140: printf("\n");
7141: fprintf(ficlog,"\n");
7142: fprintf(ficres,"\n");
7143: }
7144: }
7145: }
7146:
7147: 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");
7148: if(mle>=1)
7149: 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");
7150: 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");
7151: /* # 121 Var(a12)\n\ */
7152: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7153: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7154: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7155: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7156: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7157: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7158: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7159:
7160:
7161: /* Just to have a covariance matrix which will be more understandable
7162: even is we still don't want to manage dictionary of variables
7163: */
7164: for(itimes=1;itimes<=2;itimes++){
7165: jj=0;
7166: for(i=1; i <=nlstate; i++){
7167: for(j=1; j <=nlstate+ndeath; j++){
7168: if(j==i) continue;
7169: for(k=1; k<=ncovmodel;k++){
7170: jj++;
7171: ca[0]= k+'a'-1;ca[1]='\0';
7172: if(itimes==1){
7173: if(mle>=1)
7174: printf("#%1d%1d%d",i,j,k);
7175: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7176: fprintf(ficres,"#%1d%1d%d",i,j,k);
7177: }else{
7178: if(mle>=1)
7179: printf("%1d%1d%d",i,j,k);
7180: fprintf(ficlog,"%1d%1d%d",i,j,k);
7181: fprintf(ficres,"%1d%1d%d",i,j,k);
7182: }
7183: ll=0;
7184: for(li=1;li <=nlstate; li++){
7185: for(lj=1;lj <=nlstate+ndeath; lj++){
7186: if(lj==li) continue;
7187: for(lk=1;lk<=ncovmodel;lk++){
7188: ll++;
7189: if(ll<=jj){
7190: cb[0]= lk +'a'-1;cb[1]='\0';
7191: if(ll<jj){
7192: if(itimes==1){
7193: if(mle>=1)
7194: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7195: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7196: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7197: }else{
7198: if(mle>=1)
7199: printf(" %.5e",matcov[jj][ll]);
7200: fprintf(ficlog," %.5e",matcov[jj][ll]);
7201: fprintf(ficres," %.5e",matcov[jj][ll]);
7202: }
7203: }else{
7204: if(itimes==1){
7205: if(mle>=1)
7206: printf(" Var(%s%1d%1d)",ca,i,j);
7207: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7208: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7209: }else{
7210: if(mle>=1)
7211: printf(" %.5e",matcov[jj][ll]);
7212: fprintf(ficlog," %.5e",matcov[jj][ll]);
7213: fprintf(ficres," %.5e",matcov[jj][ll]);
7214: }
7215: }
7216: }
7217: } /* end lk */
7218: } /* end lj */
7219: } /* end li */
7220: if(mle>=1)
7221: printf("\n");
7222: fprintf(ficlog,"\n");
7223: fprintf(ficres,"\n");
7224: numlinepar++;
7225: } /* end k*/
7226: } /*end j */
7227: } /* end i */
7228: } /* end itimes */
7229:
7230: fflush(ficlog);
7231: fflush(ficres);
7232:
7233: while((c=getc(ficpar))=='#' && c!= EOF){
7234: ungetc(c,ficpar);
7235: fgets(line, MAXLINE, ficpar);
1.141 brouard 7236: fputs(line,stdout);
1.126 brouard 7237: fputs(line,ficparo);
7238: }
7239: ungetc(c,ficpar);
7240:
7241: estepm=0;
7242: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7243: if (estepm==0 || estepm < stepm) estepm=stepm;
7244: if (fage <= 2) {
7245: bage = ageminpar;
7246: fage = agemaxpar;
7247: }
7248:
7249: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7250: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7251: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7252:
7253: /* Other stuffs, more or less useful */
1.126 brouard 7254: while((c=getc(ficpar))=='#' && c!= EOF){
7255: ungetc(c,ficpar);
7256: fgets(line, MAXLINE, ficpar);
1.141 brouard 7257: fputs(line,stdout);
1.126 brouard 7258: fputs(line,ficparo);
7259: }
7260: ungetc(c,ficpar);
7261:
7262: 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);
7263: 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);
7264: 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);
7265: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7266: 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);
7267:
7268: while((c=getc(ficpar))=='#' && c!= EOF){
7269: ungetc(c,ficpar);
7270: fgets(line, MAXLINE, ficpar);
1.141 brouard 7271: fputs(line,stdout);
1.126 brouard 7272: fputs(line,ficparo);
7273: }
7274: ungetc(c,ficpar);
7275:
7276:
7277: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7278: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7279:
7280: fscanf(ficpar,"pop_based=%d\n",&popbased);
7281: fprintf(ficparo,"pop_based=%d\n",popbased);
7282: fprintf(ficres,"pop_based=%d\n",popbased);
7283:
7284: while((c=getc(ficpar))=='#' && c!= EOF){
7285: ungetc(c,ficpar);
7286: fgets(line, MAXLINE, ficpar);
1.141 brouard 7287: fputs(line,stdout);
1.126 brouard 7288: fputs(line,ficparo);
7289: }
7290: ungetc(c,ficpar);
7291:
7292: 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);
7293: 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);
7294: 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);
7295: 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);
7296: 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);
7297: /* day and month of proj2 are not used but only year anproj2.*/
7298:
7299:
7300:
1.145 brouard 7301: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7302: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7303:
7304: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7305: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7306:
7307: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7308: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7309: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7310:
7311: /*------------ free_vector -------------*/
7312: /* chdir(path); */
7313:
7314: free_ivector(wav,1,imx);
7315: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7316: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7317: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7318: free_lvector(num,1,n);
7319: free_vector(agedc,1,n);
7320: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7321: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7322: fclose(ficparo);
7323: fclose(ficres);
7324:
7325:
1.186 brouard 7326: /* Other results (useful)*/
7327:
7328:
1.126 brouard 7329: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7330: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7331: prlim=matrix(1,nlstate,1,nlstate);
7332: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7333: fclose(ficrespl);
7334:
1.145 brouard 7335: #ifdef FREEEXIT2
7336: #include "freeexit2.h"
7337: #endif
7338:
1.126 brouard 7339: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7340: /*#include "hpijx.h"*/
7341: hPijx(p, bage, fage);
1.145 brouard 7342: fclose(ficrespij);
1.126 brouard 7343:
1.145 brouard 7344: /*-------------- Variance of one-step probabilities---*/
7345: k=1;
1.126 brouard 7346: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7347:
7348:
7349: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7350: for(i=1;i<=AGESUP;i++)
7351: for(j=1;j<=NCOVMAX;j++)
7352: for(k=1;k<=NCOVMAX;k++)
7353: probs[i][j][k]=0.;
7354:
7355: /*---------- Forecasting ------------------*/
7356: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7357: if(prevfcast==1){
7358: /* if(stepm ==1){*/
7359: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7360: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7361: /* } */
7362: /* else{ */
7363: /* erreur=108; */
7364: /* 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); */
7365: /* 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); */
7366: /* } */
7367: }
1.186 brouard 7368:
7369: /* ------ Other prevalence ratios------------ */
1.126 brouard 7370:
1.127 brouard 7371: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7372:
7373: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7374: /* 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",\
7375: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7376: */
1.126 brouard 7377:
1.127 brouard 7378: if (mobilav!=0) {
7379: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7380: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7381: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7382: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7383: }
1.126 brouard 7384: }
7385:
7386:
1.127 brouard 7387: /*---------- Health expectancies, no variances ------------*/
7388:
1.126 brouard 7389: strcpy(filerese,"e");
7390: strcat(filerese,fileres);
7391: if((ficreseij=fopen(filerese,"w"))==NULL) {
7392: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7393: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7394: }
7395: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7396: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7397: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7398: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7399:
7400: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7401: fprintf(ficreseij,"\n#****** ");
7402: for(j=1;j<=cptcoveff;j++) {
7403: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7404: }
7405: fprintf(ficreseij,"******\n");
7406:
7407: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7408: oldm=oldms;savm=savms;
7409: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7410:
7411: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7412: /*}*/
1.127 brouard 7413: }
7414: fclose(ficreseij);
7415:
7416:
7417: /*---------- Health expectancies and variances ------------*/
7418:
7419:
7420: strcpy(filerest,"t");
7421: strcat(filerest,fileres);
7422: if((ficrest=fopen(filerest,"w"))==NULL) {
7423: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7424: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7425: }
7426: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7427: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7428:
1.126 brouard 7429:
7430: strcpy(fileresstde,"stde");
7431: strcat(fileresstde,fileres);
7432: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7433: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7434: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7435: }
7436: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7437: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7438:
7439: strcpy(filerescve,"cve");
7440: strcat(filerescve,fileres);
7441: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7442: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7443: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7444: }
7445: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7446: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7447:
7448: strcpy(fileresv,"v");
7449: strcat(fileresv,fileres);
7450: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7451: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7452: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7453: }
7454: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7455: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7456:
1.145 brouard 7457: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7458: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7459:
7460: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7461: fprintf(ficrest,"\n#****** ");
1.126 brouard 7462: for(j=1;j<=cptcoveff;j++)
7463: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7464: fprintf(ficrest,"******\n");
7465:
7466: fprintf(ficresstdeij,"\n#****** ");
7467: fprintf(ficrescveij,"\n#****** ");
7468: for(j=1;j<=cptcoveff;j++) {
7469: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7470: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7471: }
7472: fprintf(ficresstdeij,"******\n");
7473: fprintf(ficrescveij,"******\n");
7474:
7475: fprintf(ficresvij,"\n#****** ");
7476: for(j=1;j<=cptcoveff;j++)
7477: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7478: fprintf(ficresvij,"******\n");
7479:
7480: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7481: oldm=oldms;savm=savms;
1.127 brouard 7482: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7483: /*
7484: */
7485: /* goto endfree; */
1.126 brouard 7486:
7487: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7488: pstamp(ficrest);
1.145 brouard 7489:
7490:
1.128 brouard 7491: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7492: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7493: cptcod= 0; /* To be deleted */
7494: 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 7495: 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 7496: if(vpopbased==1)
7497: 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);
7498: else
7499: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7500: fprintf(ficrest,"# Age e.. (std) ");
7501: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7502: fprintf(ficrest,"\n");
1.126 brouard 7503:
1.128 brouard 7504: epj=vector(1,nlstate+1);
7505: for(age=bage; age <=fage ;age++){
7506: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7507: if (vpopbased==1) {
7508: if(mobilav ==0){
7509: for(i=1; i<=nlstate;i++)
7510: prlim[i][i]=probs[(int)age][i][k];
7511: }else{ /* mobilav */
7512: for(i=1; i<=nlstate;i++)
7513: prlim[i][i]=mobaverage[(int)age][i][k];
7514: }
1.126 brouard 7515: }
7516:
1.128 brouard 7517: fprintf(ficrest," %4.0f",age);
7518: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7519: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7520: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7521: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7522: }
7523: epj[nlstate+1] +=epj[j];
1.126 brouard 7524: }
7525:
1.128 brouard 7526: for(i=1, vepp=0.;i <=nlstate;i++)
7527: for(j=1;j <=nlstate;j++)
7528: vepp += vareij[i][j][(int)age];
7529: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7530: for(j=1;j <=nlstate;j++){
7531: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7532: }
7533: fprintf(ficrest,"\n");
1.126 brouard 7534: }
7535: }
7536: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7537: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7538: free_vector(epj,1,nlstate+1);
1.145 brouard 7539: /*}*/
1.126 brouard 7540: }
7541: free_vector(weight,1,n);
1.145 brouard 7542: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7543: free_imatrix(s,1,maxwav+1,1,n);
7544: free_matrix(anint,1,maxwav,1,n);
7545: free_matrix(mint,1,maxwav,1,n);
7546: free_ivector(cod,1,n);
7547: free_ivector(tab,1,NCOVMAX);
7548: fclose(ficresstdeij);
7549: fclose(ficrescveij);
7550: fclose(ficresvij);
7551: fclose(ficrest);
7552: fclose(ficpar);
7553:
7554: /*------- Variance of period (stable) prevalence------*/
7555:
7556: strcpy(fileresvpl,"vpl");
7557: strcat(fileresvpl,fileres);
7558: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7559: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7560: exit(0);
7561: }
7562: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7563:
1.145 brouard 7564: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7565: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7566:
7567: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7568: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7569: for(j=1;j<=cptcoveff;j++)
7570: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7571: fprintf(ficresvpl,"******\n");
7572:
7573: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7574: oldm=oldms;savm=savms;
7575: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7576: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7577: /*}*/
1.126 brouard 7578: }
7579:
7580: fclose(ficresvpl);
7581:
7582: /*---------- End : free ----------------*/
7583: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7584: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7585: } /* mle==-3 arrives here for freeing */
1.164 brouard 7586: /* endfree:*/
1.141 brouard 7587: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7588: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7589: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7590: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7591: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7592: free_matrix(covar,0,NCOVMAX,1,n);
7593: free_matrix(matcov,1,npar,1,npar);
7594: /*free_vector(delti,1,npar);*/
7595: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7596: free_matrix(agev,1,maxwav,1,imx);
7597: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7598:
1.145 brouard 7599: free_ivector(ncodemax,1,NCOVMAX);
7600: free_ivector(Tvar,1,NCOVMAX);
7601: free_ivector(Tprod,1,NCOVMAX);
7602: free_ivector(Tvaraff,1,NCOVMAX);
7603: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7604:
7605: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7606: free_imatrix(codtab,1,100,1,10);
7607: fflush(fichtm);
7608: fflush(ficgp);
7609:
7610:
7611: if((nberr >0) || (nbwarn>0)){
7612: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7613: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7614: }else{
7615: printf("End of Imach\n");
7616: fprintf(ficlog,"End of Imach\n");
7617: }
7618: printf("See log file on %s\n",filelog);
7619: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7620: /*(void) gettimeofday(&end_time,&tzp);*/
7621: rend_time = time(NULL);
7622: end_time = *localtime(&rend_time);
7623: /* tml = *localtime(&end_time.tm_sec); */
7624: strcpy(strtend,asctime(&end_time));
1.126 brouard 7625: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7626: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7627: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7628:
1.157 brouard 7629: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7630: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7631: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7632: /* printf("Total time was %d uSec.\n", total_usecs);*/
7633: /* if(fileappend(fichtm,optionfilehtm)){ */
7634: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7635: fclose(fichtm);
7636: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7637: fclose(fichtmcov);
7638: fclose(ficgp);
7639: fclose(ficlog);
7640: /*------ End -----------*/
7641:
7642:
7643: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 7644: #ifdef WIN32
7645: if (_chdir(pathcd) != 0)
7646: printf("Can't move to directory %s!\n",path);
7647: if(_getcwd(pathcd,MAXLINE) > 0)
7648: #else
1.126 brouard 7649: if(chdir(pathcd) != 0)
1.184 brouard 7650: printf("Can't move to directory %s!\n", path);
7651: if (getcwd(pathcd, MAXLINE) > 0)
7652: #endif
1.126 brouard 7653: printf("Current directory %s!\n",pathcd);
7654: /*strcat(plotcmd,CHARSEPARATOR);*/
7655: sprintf(plotcmd,"gnuplot");
1.157 brouard 7656: #ifdef _WIN32
1.126 brouard 7657: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7658: #endif
7659: if(!stat(plotcmd,&info)){
1.158 brouard 7660: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7661: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7662: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7663: }else
7664: strcpy(pplotcmd,plotcmd);
1.157 brouard 7665: #ifdef __unix
1.126 brouard 7666: strcpy(plotcmd,GNUPLOTPROGRAM);
7667: if(!stat(plotcmd,&info)){
1.158 brouard 7668: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7669: }else
7670: strcpy(pplotcmd,plotcmd);
7671: #endif
7672: }else
7673: strcpy(pplotcmd,plotcmd);
7674:
7675: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7676: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7677:
7678: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7679: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7680: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7681: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7682: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7683: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7684: }
1.158 brouard 7685: printf(" Successful, please wait...");
1.126 brouard 7686: while (z[0] != 'q') {
7687: /* chdir(path); */
1.154 brouard 7688: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7689: scanf("%s",z);
7690: /* if (z[0] == 'c') system("./imach"); */
7691: if (z[0] == 'e') {
1.158 brouard 7692: #ifdef __APPLE__
1.152 brouard 7693: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7694: #elif __linux
7695: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7696: #else
1.152 brouard 7697: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7698: #endif
7699: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7700: system(pplotcmd);
1.126 brouard 7701: }
7702: else if (z[0] == 'g') system(plotcmd);
7703: else if (z[0] == 'q') exit(0);
7704: }
7705: end:
7706: while (z[0] != 'q') {
7707: printf("\nType q for exiting: ");
7708: scanf("%s",z);
7709: }
7710: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>