File:
[Local Repository] /
imach /
src /
imach.c
Revision
1.186:
download - view:
text,
annotated -
select for diffs
Thu Apr 23 12:01:52 2015 UTC (9 years, 5 months ago) by
brouard
Branches:
MAIN
CVS tags:
HEAD
Summary: V1*age is working now, version 0.98q1
Some codes had been disabled in order to simplify and Vn*age was
working in the optimization phase, ie, giving correct MLE parameters,
but, as usual, outputs were not correct and program core dumped.
1: /* $Id: imach.c,v 1.186 2015/04/23 12:01:52 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.186 2015/04/23 12:01:52 brouard
5: Summary: V1*age is working now, version 0.98q1
6:
7: Some codes had been disabled in order to simplify and Vn*age was
8: working in the optimization phase, ie, giving correct MLE parameters,
9: but, as usual, outputs were not correct and program core dumped.
10:
11: Revision 1.185 2015/03/11 13:26:42 brouard
12: Summary: Inclusion of compile and links command line for Intel Compiler
13:
14: Revision 1.184 2015/03/11 11:52:39 brouard
15: Summary: Back from Windows 8. Intel Compiler
16:
17: Revision 1.183 2015/03/10 20:34:32 brouard
18: Summary: 0.98q0, trying with directest, mnbrak fixed
19:
20: We use directest instead of original Powell test; probably no
21: incidence on the results, but better justifications;
22: We fixed Numerical Recipes mnbrak routine which was wrong and gave
23: wrong results.
24:
25: Revision 1.182 2015/02/12 08:19:57 brouard
26: Summary: Trying to keep directest which seems simpler and more general
27: Author: Nicolas Brouard
28:
29: Revision 1.181 2015/02/11 23:22:24 brouard
30: Summary: Comments on Powell added
31:
32: Author:
33:
34: Revision 1.180 2015/02/11 17:33:45 brouard
35: Summary: Finishing move from main to function (hpijx and prevalence_limit)
36:
37: Revision 1.179 2015/01/04 09:57:06 brouard
38: Summary: back to OS/X
39:
40: Revision 1.178 2015/01/04 09:35:48 brouard
41: *** empty log message ***
42:
43: Revision 1.177 2015/01/03 18:40:56 brouard
44: Summary: Still testing ilc32 on OSX
45:
46: Revision 1.176 2015/01/03 16:45:04 brouard
47: *** empty log message ***
48:
49: Revision 1.175 2015/01/03 16:33:42 brouard
50: *** empty log message ***
51:
52: Revision 1.174 2015/01/03 16:15:49 brouard
53: Summary: Still in cross-compilation
54:
55: Revision 1.173 2015/01/03 12:06:26 brouard
56: Summary: trying to detect cross-compilation
57:
58: Revision 1.172 2014/12/27 12:07:47 brouard
59: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
60:
61: Revision 1.171 2014/12/23 13:26:59 brouard
62: Summary: Back from Visual C
63:
64: Still problem with utsname.h on Windows
65:
66: Revision 1.170 2014/12/23 11:17:12 brouard
67: Summary: Cleaning some \%% back to %%
68:
69: The escape was mandatory for a specific compiler (which one?), but too many warnings.
70:
71: Revision 1.169 2014/12/22 23:08:31 brouard
72: Summary: 0.98p
73:
74: Outputs some informations on compiler used, OS etc. Testing on different platforms.
75:
76: Revision 1.168 2014/12/22 15:17:42 brouard
77: Summary: update
78:
79: Revision 1.167 2014/12/22 13:50:56 brouard
80: Summary: Testing uname and compiler version and if compiled 32 or 64
81:
82: Testing on Linux 64
83:
84: Revision 1.166 2014/12/22 11:40:47 brouard
85: *** empty log message ***
86:
87: Revision 1.165 2014/12/16 11:20:36 brouard
88: Summary: After compiling on Visual C
89:
90: * imach.c (Module): Merging 1.61 to 1.162
91:
92: Revision 1.164 2014/12/16 10:52:11 brouard
93: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
94:
95: * imach.c (Module): Merging 1.61 to 1.162
96:
97: Revision 1.163 2014/12/16 10:30:11 brouard
98: * imach.c (Module): Merging 1.61 to 1.162
99:
100: Revision 1.162 2014/09/25 11:43:39 brouard
101: Summary: temporary backup 0.99!
102:
103: Revision 1.1 2014/09/16 11:06:58 brouard
104: Summary: With some code (wrong) for nlopt
105:
106: Author:
107:
108: Revision 1.161 2014/09/15 20:41:41 brouard
109: Summary: Problem with macro SQR on Intel compiler
110:
111: Revision 1.160 2014/09/02 09:24:05 brouard
112: *** empty log message ***
113:
114: Revision 1.159 2014/09/01 10:34:10 brouard
115: Summary: WIN32
116: Author: Brouard
117:
118: Revision 1.158 2014/08/27 17:11:51 brouard
119: *** empty log message ***
120:
121: Revision 1.157 2014/08/27 16:26:55 brouard
122: Summary: Preparing windows Visual studio version
123: Author: Brouard
124:
125: In order to compile on Visual studio, time.h is now correct and time_t
126: and tm struct should be used. difftime should be used but sometimes I
127: just make the differences in raw time format (time(&now).
128: Trying to suppress #ifdef LINUX
129: Add xdg-open for __linux in order to open default browser.
130:
131: Revision 1.156 2014/08/25 20:10:10 brouard
132: *** empty log message ***
133:
134: Revision 1.155 2014/08/25 18:32:34 brouard
135: Summary: New compile, minor changes
136: Author: Brouard
137:
138: Revision 1.154 2014/06/20 17:32:08 brouard
139: Summary: Outputs now all graphs of convergence to period prevalence
140:
141: Revision 1.153 2014/06/20 16:45:46 brouard
142: Summary: If 3 live state, convergence to period prevalence on same graph
143: Author: Brouard
144:
145: Revision 1.152 2014/06/18 17:54:09 brouard
146: Summary: open browser, use gnuplot on same dir than imach if not found in the path
147:
148: Revision 1.151 2014/06/18 16:43:30 brouard
149: *** empty log message ***
150:
151: Revision 1.150 2014/06/18 16:42:35 brouard
152: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
153: Author: brouard
154:
155: Revision 1.149 2014/06/18 15:51:14 brouard
156: Summary: Some fixes in parameter files errors
157: Author: Nicolas Brouard
158:
159: Revision 1.148 2014/06/17 17:38:48 brouard
160: Summary: Nothing new
161: Author: Brouard
162:
163: Just a new packaging for OS/X version 0.98nS
164:
165: Revision 1.147 2014/06/16 10:33:11 brouard
166: *** empty log message ***
167:
168: Revision 1.146 2014/06/16 10:20:28 brouard
169: Summary: Merge
170: Author: Brouard
171:
172: Merge, before building revised version.
173:
174: Revision 1.145 2014/06/10 21:23:15 brouard
175: Summary: Debugging with valgrind
176: Author: Nicolas Brouard
177:
178: Lot of changes in order to output the results with some covariates
179: After the Edimburgh REVES conference 2014, it seems mandatory to
180: improve the code.
181: No more memory valgrind error but a lot has to be done in order to
182: continue the work of splitting the code into subroutines.
183: Also, decodemodel has been improved. Tricode is still not
184: optimal. nbcode should be improved. Documentation has been added in
185: the source code.
186:
187: Revision 1.143 2014/01/26 09:45:38 brouard
188: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
189:
190: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
191: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
192:
193: Revision 1.142 2014/01/26 03:57:36 brouard
194: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
195:
196: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
197:
198: Revision 1.141 2014/01/26 02:42:01 brouard
199: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
200:
201: Revision 1.140 2011/09/02 10:37:54 brouard
202: Summary: times.h is ok with mingw32 now.
203:
204: Revision 1.139 2010/06/14 07:50:17 brouard
205: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
206: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
207:
208: Revision 1.138 2010/04/30 18:19:40 brouard
209: *** empty log message ***
210:
211: Revision 1.137 2010/04/29 18:11:38 brouard
212: (Module): Checking covariates for more complex models
213: than V1+V2. A lot of change to be done. Unstable.
214:
215: Revision 1.136 2010/04/26 20:30:53 brouard
216: (Module): merging some libgsl code. Fixing computation
217: of likelione (using inter/intrapolation if mle = 0) in order to
218: get same likelihood as if mle=1.
219: Some cleaning of code and comments added.
220:
221: Revision 1.135 2009/10/29 15:33:14 brouard
222: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
223:
224: Revision 1.134 2009/10/29 13:18:53 brouard
225: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
226:
227: Revision 1.133 2009/07/06 10:21:25 brouard
228: just nforces
229:
230: Revision 1.132 2009/07/06 08:22:05 brouard
231: Many tings
232:
233: Revision 1.131 2009/06/20 16:22:47 brouard
234: Some dimensions resccaled
235:
236: Revision 1.130 2009/05/26 06:44:34 brouard
237: (Module): Max Covariate is now set to 20 instead of 8. A
238: lot of cleaning with variables initialized to 0. Trying to make
239: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
240:
241: Revision 1.129 2007/08/31 13:49:27 lievre
242: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
243:
244: Revision 1.128 2006/06/30 13:02:05 brouard
245: (Module): Clarifications on computing e.j
246:
247: Revision 1.127 2006/04/28 18:11:50 brouard
248: (Module): Yes the sum of survivors was wrong since
249: imach-114 because nhstepm was no more computed in the age
250: loop. Now we define nhstepma in the age loop.
251: (Module): In order to speed up (in case of numerous covariates) we
252: compute health expectancies (without variances) in a first step
253: and then all the health expectancies with variances or standard
254: deviation (needs data from the Hessian matrices) which slows the
255: computation.
256: In the future we should be able to stop the program is only health
257: expectancies and graph are needed without standard deviations.
258:
259: Revision 1.126 2006/04/28 17:23:28 brouard
260: (Module): Yes the sum of survivors was wrong since
261: imach-114 because nhstepm was no more computed in the age
262: loop. Now we define nhstepma in the age loop.
263: Version 0.98h
264:
265: Revision 1.125 2006/04/04 15:20:31 lievre
266: Errors in calculation of health expectancies. Age was not initialized.
267: Forecasting file added.
268:
269: Revision 1.124 2006/03/22 17:13:53 lievre
270: Parameters are printed with %lf instead of %f (more numbers after the comma).
271: The log-likelihood is printed in the log file
272:
273: Revision 1.123 2006/03/20 10:52:43 brouard
274: * imach.c (Module): <title> changed, corresponds to .htm file
275: name. <head> headers where missing.
276:
277: * imach.c (Module): Weights can have a decimal point as for
278: English (a comma might work with a correct LC_NUMERIC environment,
279: otherwise the weight is truncated).
280: Modification of warning when the covariates values are not 0 or
281: 1.
282: Version 0.98g
283:
284: Revision 1.122 2006/03/20 09:45:41 brouard
285: (Module): Weights can have a decimal point as for
286: English (a comma might work with a correct LC_NUMERIC environment,
287: otherwise the weight is truncated).
288: Modification of warning when the covariates values are not 0 or
289: 1.
290: Version 0.98g
291:
292: Revision 1.121 2006/03/16 17:45:01 lievre
293: * imach.c (Module): Comments concerning covariates added
294:
295: * imach.c (Module): refinements in the computation of lli if
296: status=-2 in order to have more reliable computation if stepm is
297: not 1 month. Version 0.98f
298:
299: Revision 1.120 2006/03/16 15:10:38 lievre
300: (Module): refinements in the computation of lli if
301: status=-2 in order to have more reliable computation if stepm is
302: not 1 month. Version 0.98f
303:
304: Revision 1.119 2006/03/15 17:42:26 brouard
305: (Module): Bug if status = -2, the loglikelihood was
306: computed as likelihood omitting the logarithm. Version O.98e
307:
308: Revision 1.118 2006/03/14 18:20:07 brouard
309: (Module): varevsij Comments added explaining the second
310: table of variances if popbased=1 .
311: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
312: (Module): Function pstamp added
313: (Module): Version 0.98d
314:
315: Revision 1.117 2006/03/14 17:16:22 brouard
316: (Module): varevsij Comments added explaining the second
317: table of variances if popbased=1 .
318: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
319: (Module): Function pstamp added
320: (Module): Version 0.98d
321:
322: Revision 1.116 2006/03/06 10:29:27 brouard
323: (Module): Variance-covariance wrong links and
324: varian-covariance of ej. is needed (Saito).
325:
326: Revision 1.115 2006/02/27 12:17:45 brouard
327: (Module): One freematrix added in mlikeli! 0.98c
328:
329: Revision 1.114 2006/02/26 12:57:58 brouard
330: (Module): Some improvements in processing parameter
331: filename with strsep.
332:
333: Revision 1.113 2006/02/24 14:20:24 brouard
334: (Module): Memory leaks checks with valgrind and:
335: datafile was not closed, some imatrix were not freed and on matrix
336: allocation too.
337:
338: Revision 1.112 2006/01/30 09:55:26 brouard
339: (Module): Back to gnuplot.exe instead of wgnuplot.exe
340:
341: Revision 1.111 2006/01/25 20:38:18 brouard
342: (Module): Lots of cleaning and bugs added (Gompertz)
343: (Module): Comments can be added in data file. Missing date values
344: can be a simple dot '.'.
345:
346: Revision 1.110 2006/01/25 00:51:50 brouard
347: (Module): Lots of cleaning and bugs added (Gompertz)
348:
349: Revision 1.109 2006/01/24 19:37:15 brouard
350: (Module): Comments (lines starting with a #) are allowed in data.
351:
352: Revision 1.108 2006/01/19 18:05:42 lievre
353: Gnuplot problem appeared...
354: To be fixed
355:
356: Revision 1.107 2006/01/19 16:20:37 brouard
357: Test existence of gnuplot in imach path
358:
359: Revision 1.106 2006/01/19 13:24:36 brouard
360: Some cleaning and links added in html output
361:
362: Revision 1.105 2006/01/05 20:23:19 lievre
363: *** empty log message ***
364:
365: Revision 1.104 2005/09/30 16:11:43 lievre
366: (Module): sump fixed, loop imx fixed, and simplifications.
367: (Module): If the status is missing at the last wave but we know
368: that the person is alive, then we can code his/her status as -2
369: (instead of missing=-1 in earlier versions) and his/her
370: contributions to the likelihood is 1 - Prob of dying from last
371: health status (= 1-p13= p11+p12 in the easiest case of somebody in
372: the healthy state at last known wave). Version is 0.98
373:
374: Revision 1.103 2005/09/30 15:54:49 lievre
375: (Module): sump fixed, loop imx fixed, and simplifications.
376:
377: Revision 1.102 2004/09/15 17:31:30 brouard
378: Add the possibility to read data file including tab characters.
379:
380: Revision 1.101 2004/09/15 10:38:38 brouard
381: Fix on curr_time
382:
383: Revision 1.100 2004/07/12 18:29:06 brouard
384: Add version for Mac OS X. Just define UNIX in Makefile
385:
386: Revision 1.99 2004/06/05 08:57:40 brouard
387: *** empty log message ***
388:
389: Revision 1.98 2004/05/16 15:05:56 brouard
390: New version 0.97 . First attempt to estimate force of mortality
391: directly from the data i.e. without the need of knowing the health
392: state at each age, but using a Gompertz model: log u =a + b*age .
393: This is the basic analysis of mortality and should be done before any
394: other analysis, in order to test if the mortality estimated from the
395: cross-longitudinal survey is different from the mortality estimated
396: from other sources like vital statistic data.
397:
398: The same imach parameter file can be used but the option for mle should be -3.
399:
400: Agnès, who wrote this part of the code, tried to keep most of the
401: former routines in order to include the new code within the former code.
402:
403: The output is very simple: only an estimate of the intercept and of
404: the slope with 95% confident intervals.
405:
406: Current limitations:
407: A) Even if you enter covariates, i.e. with the
408: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
409: B) There is no computation of Life Expectancy nor Life Table.
410:
411: Revision 1.97 2004/02/20 13:25:42 lievre
412: Version 0.96d. Population forecasting command line is (temporarily)
413: suppressed.
414:
415: Revision 1.96 2003/07/15 15:38:55 brouard
416: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
417: rewritten within the same printf. Workaround: many printfs.
418:
419: Revision 1.95 2003/07/08 07:54:34 brouard
420: * imach.c (Repository):
421: (Repository): Using imachwizard code to output a more meaningful covariance
422: matrix (cov(a12,c31) instead of numbers.
423:
424: Revision 1.94 2003/06/27 13:00:02 brouard
425: Just cleaning
426:
427: Revision 1.93 2003/06/25 16:33:55 brouard
428: (Module): On windows (cygwin) function asctime_r doesn't
429: exist so I changed back to asctime which exists.
430: (Module): Version 0.96b
431:
432: Revision 1.92 2003/06/25 16:30:45 brouard
433: (Module): On windows (cygwin) function asctime_r doesn't
434: exist so I changed back to asctime which exists.
435:
436: Revision 1.91 2003/06/25 15:30:29 brouard
437: * imach.c (Repository): Duplicated warning errors corrected.
438: (Repository): Elapsed time after each iteration is now output. It
439: helps to forecast when convergence will be reached. Elapsed time
440: is stamped in powell. We created a new html file for the graphs
441: concerning matrix of covariance. It has extension -cov.htm.
442:
443: Revision 1.90 2003/06/24 12:34:15 brouard
444: (Module): Some bugs corrected for windows. Also, when
445: mle=-1 a template is output in file "or"mypar.txt with the design
446: of the covariance matrix to be input.
447:
448: Revision 1.89 2003/06/24 12:30:52 brouard
449: (Module): Some bugs corrected for windows. Also, when
450: mle=-1 a template is output in file "or"mypar.txt with the design
451: of the covariance matrix to be input.
452:
453: Revision 1.88 2003/06/23 17:54:56 brouard
454: * 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.
455:
456: Revision 1.87 2003/06/18 12:26:01 brouard
457: Version 0.96
458:
459: Revision 1.86 2003/06/17 20:04:08 brouard
460: (Module): Change position of html and gnuplot routines and added
461: routine fileappend.
462:
463: Revision 1.85 2003/06/17 13:12:43 brouard
464: * imach.c (Repository): Check when date of death was earlier that
465: current date of interview. It may happen when the death was just
466: prior to the death. In this case, dh was negative and likelihood
467: was wrong (infinity). We still send an "Error" but patch by
468: assuming that the date of death was just one stepm after the
469: interview.
470: (Repository): Because some people have very long ID (first column)
471: we changed int to long in num[] and we added a new lvector for
472: memory allocation. But we also truncated to 8 characters (left
473: truncation)
474: (Repository): No more line truncation errors.
475:
476: Revision 1.84 2003/06/13 21:44:43 brouard
477: * imach.c (Repository): Replace "freqsummary" at a correct
478: place. It differs from routine "prevalence" which may be called
479: many times. Probs is memory consuming and must be used with
480: parcimony.
481: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
482:
483: Revision 1.83 2003/06/10 13:39:11 lievre
484: *** empty log message ***
485:
486: Revision 1.82 2003/06/05 15:57:20 brouard
487: Add log in imach.c and fullversion number is now printed.
488:
489: */
490: /*
491: Interpolated Markov Chain
492:
493: Short summary of the programme:
494:
495: This program computes Healthy Life Expectancies from
496: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
497: first survey ("cross") where individuals from different ages are
498: interviewed on their health status or degree of disability (in the
499: case of a health survey which is our main interest) -2- at least a
500: second wave of interviews ("longitudinal") which measure each change
501: (if any) in individual health status. Health expectancies are
502: computed from the time spent in each health state according to a
503: model. More health states you consider, more time is necessary to reach the
504: Maximum Likelihood of the parameters involved in the model. The
505: simplest model is the multinomial logistic model where pij is the
506: probability to be observed in state j at the second wave
507: conditional to be observed in state i at the first wave. Therefore
508: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
509: 'age' is age and 'sex' is a covariate. If you want to have a more
510: complex model than "constant and age", you should modify the program
511: where the markup *Covariates have to be included here again* invites
512: you to do it. More covariates you add, slower the
513: convergence.
514:
515: The advantage of this computer programme, compared to a simple
516: multinomial logistic model, is clear when the delay between waves is not
517: identical for each individual. Also, if a individual missed an
518: intermediate interview, the information is lost, but taken into
519: account using an interpolation or extrapolation.
520:
521: hPijx is the probability to be observed in state i at age x+h
522: conditional to the observed state i at age x. The delay 'h' can be
523: split into an exact number (nh*stepm) of unobserved intermediate
524: states. This elementary transition (by month, quarter,
525: semester or year) is modelled as a multinomial logistic. The hPx
526: matrix is simply the matrix product of nh*stepm elementary matrices
527: and the contribution of each individual to the likelihood is simply
528: hPijx.
529:
530: Also this programme outputs the covariance matrix of the parameters but also
531: of the life expectancies. It also computes the period (stable) prevalence.
532:
533: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
534: Institut national d'études démographiques, Paris.
535: This software have been partly granted by Euro-REVES, a concerted action
536: from the European Union.
537: It is copyrighted identically to a GNU software product, ie programme and
538: software can be distributed freely for non commercial use. Latest version
539: can be accessed at http://euroreves.ined.fr/imach .
540:
541: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
542: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
543:
544: **********************************************************************/
545: /*
546: main
547: read parameterfile
548: read datafile
549: concatwav
550: freqsummary
551: if (mle >= 1)
552: mlikeli
553: print results files
554: if mle==1
555: computes hessian
556: read end of parameter file: agemin, agemax, bage, fage, estepm
557: begin-prev-date,...
558: open gnuplot file
559: open html file
560: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
561: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
562: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
563: freexexit2 possible for memory heap.
564:
565: h Pij x | pij_nom ficrestpij
566: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
567: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
568: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
569:
570: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
571: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
572: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
573: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
574: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
575:
576: forecasting if prevfcast==1 prevforecast call prevalence()
577: health expectancies
578: Variance-covariance of DFLE
579: prevalence()
580: movingaverage()
581: varevsij()
582: if popbased==1 varevsij(,popbased)
583: total life expectancies
584: Variance of period (stable) prevalence
585: end
586: */
587:
588: #define POWELL /* Instead of NLOPT */
589: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
590: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
591:
592: #include <math.h>
593: #include <stdio.h>
594: #include <stdlib.h>
595: #include <string.h>
596:
597: #ifdef _WIN32
598: #include <io.h>
599: #include <windows.h>
600: #include <tchar.h>
601: #else
602: #include <unistd.h>
603: #endif
604:
605: #include <limits.h>
606: #include <sys/types.h>
607:
608: #if defined(__GNUC__)
609: #include <sys/utsname.h> /* Doesn't work on Windows */
610: #endif
611:
612: #include <sys/stat.h>
613: #include <errno.h>
614: /* extern int errno; */
615:
616: /* #ifdef LINUX */
617: /* #include <time.h> */
618: /* #include "timeval.h" */
619: /* #else */
620: /* #include <sys/time.h> */
621: /* #endif */
622:
623: #include <time.h>
624:
625: #ifdef GSL
626: #include <gsl/gsl_errno.h>
627: #include <gsl/gsl_multimin.h>
628: #endif
629:
630:
631: #ifdef NLOPT
632: #include <nlopt.h>
633: typedef struct {
634: double (* function)(double [] );
635: } myfunc_data ;
636: #endif
637:
638: /* #include <libintl.h> */
639: /* #define _(String) gettext (String) */
640:
641: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
642:
643: #define GNUPLOTPROGRAM "gnuplot"
644: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
645: #define FILENAMELENGTH 132
646:
647: #define GLOCK_ERROR_NOPATH -1 /* empty path */
648: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
649:
650: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
651: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
652:
653: #define NINTERVMAX 8
654: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
655: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
656: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
657: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
658: #define MAXN 20000
659: #define YEARM 12. /**< Number of months per year */
660: #define AGESUP 130
661: #define AGEBASE 40
662: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
663: #ifdef _WIN32
664: #define DIRSEPARATOR '\\'
665: #define CHARSEPARATOR "\\"
666: #define ODIRSEPARATOR '/'
667: #else
668: #define DIRSEPARATOR '/'
669: #define CHARSEPARATOR "/"
670: #define ODIRSEPARATOR '\\'
671: #endif
672:
673: /* $Id: imach.c,v 1.186 2015/04/23 12:01:52 brouard Exp $ */
674: /* $State: Exp $ */
675:
676: char version[]="Imach version 0.98q1, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
677: char fullversion[]="$Revision: 1.186 $ $Date: 2015/04/23 12:01:52 $";
678: char strstart[80];
679: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
680: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
681: int nvar=0, nforce=0; /* Number of variables, number of forces */
682: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
683: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
684: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
685: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
686: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
687: int cptcovprodnoage=0; /**< Number of covariate products without age */
688: int cptcoveff=0; /* Total number of covariates to vary for printing results */
689: int cptcov=0; /* Working variable */
690: int npar=NPARMAX;
691: int nlstate=2; /* Number of live states */
692: int ndeath=1; /* Number of dead states */
693: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
694: int popbased=0;
695:
696: int *wav; /* Number of waves for this individuual 0 is possible */
697: int maxwav=0; /* Maxim number of waves */
698: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
699: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
700: int gipmx=0, gsw=0; /* Global variables on the number of contributions
701: to the likelihood and the sum of weights (done by funcone)*/
702: int mle=1, weightopt=0;
703: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
704: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
705: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
706: * wave mi and wave mi+1 is not an exact multiple of stepm. */
707: int countcallfunc=0; /* Count the number of calls to func */
708: double jmean=1; /* Mean space between 2 waves */
709: double **matprod2(); /* test */
710: double **oldm, **newm, **savm; /* Working pointers to matrices */
711: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
712: /*FILE *fic ; */ /* Used in readdata only */
713: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
714: FILE *ficlog, *ficrespow;
715: int globpr=0; /* Global variable for printing or not */
716: double fretone; /* Only one call to likelihood */
717: long ipmx=0; /* Number of contributions */
718: double sw; /* Sum of weights */
719: char filerespow[FILENAMELENGTH];
720: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
721: FILE *ficresilk;
722: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
723: FILE *ficresprobmorprev;
724: FILE *fichtm, *fichtmcov; /* Html File */
725: FILE *ficreseij;
726: char filerese[FILENAMELENGTH];
727: FILE *ficresstdeij;
728: char fileresstde[FILENAMELENGTH];
729: FILE *ficrescveij;
730: char filerescve[FILENAMELENGTH];
731: FILE *ficresvij;
732: char fileresv[FILENAMELENGTH];
733: FILE *ficresvpl;
734: char fileresvpl[FILENAMELENGTH];
735: char title[MAXLINE];
736: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
737: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
738: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
739: char command[FILENAMELENGTH];
740: int outcmd=0;
741:
742: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
743:
744: char filelog[FILENAMELENGTH]; /* Log file */
745: char filerest[FILENAMELENGTH];
746: char fileregp[FILENAMELENGTH];
747: char popfile[FILENAMELENGTH];
748:
749: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
750:
751: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
752: /* struct timezone tzp; */
753: /* extern int gettimeofday(); */
754: struct tm tml, *gmtime(), *localtime();
755:
756: extern time_t time();
757:
758: struct tm start_time, end_time, curr_time, last_time, forecast_time;
759: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
760: struct tm tm;
761:
762: char strcurr[80], strfor[80];
763:
764: char *endptr;
765: long lval;
766: double dval;
767:
768: #define NR_END 1
769: #define FREE_ARG char*
770: #define FTOL 1.0e-10
771:
772: #define NRANSI
773: #define ITMAX 200
774:
775: #define TOL 2.0e-4
776:
777: #define CGOLD 0.3819660
778: #define ZEPS 1.0e-10
779: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
780:
781: #define GOLD 1.618034
782: #define GLIMIT 100.0
783: #define TINY 1.0e-20
784:
785: static double maxarg1,maxarg2;
786: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
787: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
788:
789: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
790: #define rint(a) floor(a+0.5)
791: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
792: #define mytinydouble 1.0e-16
793: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
794: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
795: /* static double dsqrarg; */
796: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
797: static double sqrarg;
798: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
799: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
800: int agegomp= AGEGOMP;
801:
802: int imx;
803: int stepm=1;
804: /* Stepm, step in month: minimum step interpolation*/
805:
806: int estepm;
807: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
808:
809: int m,nb;
810: long *num;
811: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
812: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
813: double **pmmij, ***probs;
814: double *ageexmed,*agecens;
815: double dateintmean=0;
816:
817: double *weight;
818: int **s; /* Status */
819: double *agedc;
820: double **covar; /**< covar[j,i], value of jth covariate for individual i,
821: * covar=matrix(0,NCOVMAX,1,n);
822: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
823: double idx;
824: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
825: int *Ndum; /** Freq of modality (tricode */
826: int **codtab; /**< codtab=imatrix(1,100,1,10); */
827: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
828: double *lsurv, *lpop, *tpop;
829:
830: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
831: double ftolhess; /**< Tolerance for computing hessian */
832:
833: /**************** split *************************/
834: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
835: {
836: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
837: the name of the file (name), its extension only (ext) and its first part of the name (finame)
838: */
839: char *ss; /* pointer */
840: int l1=0, l2=0; /* length counters */
841:
842: l1 = strlen(path ); /* length of path */
843: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
844: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
845: if ( ss == NULL ) { /* no directory, so determine current directory */
846: strcpy( name, path ); /* we got the fullname name because no directory */
847: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
848: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
849: /* get current working directory */
850: /* extern char* getcwd ( char *buf , int len);*/
851: #ifdef WIN32
852: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
853: #else
854: if (getcwd(dirc, FILENAME_MAX) == NULL) {
855: #endif
856: return( GLOCK_ERROR_GETCWD );
857: }
858: /* got dirc from getcwd*/
859: printf(" DIRC = %s \n",dirc);
860: } else { /* strip direcotry from path */
861: ss++; /* after this, the filename */
862: l2 = strlen( ss ); /* length of filename */
863: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
864: strcpy( name, ss ); /* save file name */
865: strncpy( dirc, path, l1 - l2 ); /* now the directory */
866: dirc[l1-l2] = '\0'; /* add zero */
867: printf(" DIRC2 = %s \n",dirc);
868: }
869: /* We add a separator at the end of dirc if not exists */
870: l1 = strlen( dirc ); /* length of directory */
871: if( dirc[l1-1] != DIRSEPARATOR ){
872: dirc[l1] = DIRSEPARATOR;
873: dirc[l1+1] = 0;
874: printf(" DIRC3 = %s \n",dirc);
875: }
876: ss = strrchr( name, '.' ); /* find last / */
877: if (ss >0){
878: ss++;
879: strcpy(ext,ss); /* save extension */
880: l1= strlen( name);
881: l2= strlen(ss)+1;
882: strncpy( finame, name, l1-l2);
883: finame[l1-l2]= 0;
884: }
885:
886: return( 0 ); /* we're done */
887: }
888:
889:
890: /******************************************/
891:
892: void replace_back_to_slash(char *s, char*t)
893: {
894: int i;
895: int lg=0;
896: i=0;
897: lg=strlen(t);
898: for(i=0; i<= lg; i++) {
899: (s[i] = t[i]);
900: if (t[i]== '\\') s[i]='/';
901: }
902: }
903:
904: char *trimbb(char *out, char *in)
905: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
906: char *s;
907: s=out;
908: while (*in != '\0'){
909: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
910: in++;
911: }
912: *out++ = *in++;
913: }
914: *out='\0';
915: return s;
916: }
917:
918: char *cutl(char *blocc, char *alocc, char *in, char occ)
919: {
920: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
921: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
922: gives blocc="abcdef2ghi" and alocc="j".
923: If occ is not found blocc is null and alocc is equal to in. Returns blocc
924: */
925: char *s, *t;
926: t=in;s=in;
927: while ((*in != occ) && (*in != '\0')){
928: *alocc++ = *in++;
929: }
930: if( *in == occ){
931: *(alocc)='\0';
932: s=++in;
933: }
934:
935: if (s == t) {/* occ not found */
936: *(alocc-(in-s))='\0';
937: in=s;
938: }
939: while ( *in != '\0'){
940: *blocc++ = *in++;
941: }
942:
943: *blocc='\0';
944: return t;
945: }
946: char *cutv(char *blocc, char *alocc, char *in, char occ)
947: {
948: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
949: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
950: gives blocc="abcdef2ghi" and alocc="j".
951: If occ is not found blocc is null and alocc is equal to in. Returns alocc
952: */
953: char *s, *t;
954: t=in;s=in;
955: while (*in != '\0'){
956: while( *in == occ){
957: *blocc++ = *in++;
958: s=in;
959: }
960: *blocc++ = *in++;
961: }
962: if (s == t) /* occ not found */
963: *(blocc-(in-s))='\0';
964: else
965: *(blocc-(in-s)-1)='\0';
966: in=s;
967: while ( *in != '\0'){
968: *alocc++ = *in++;
969: }
970:
971: *alocc='\0';
972: return s;
973: }
974:
975: int nbocc(char *s, char occ)
976: {
977: int i,j=0;
978: int lg=20;
979: i=0;
980: lg=strlen(s);
981: for(i=0; i<= lg; i++) {
982: if (s[i] == occ ) j++;
983: }
984: return j;
985: }
986:
987: /* void cutv(char *u,char *v, char*t, char occ) */
988: /* { */
989: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
990: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
991: /* gives u="abcdef2ghi" and v="j" *\/ */
992: /* int i,lg,j,p=0; */
993: /* i=0; */
994: /* lg=strlen(t); */
995: /* for(j=0; j<=lg-1; j++) { */
996: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
997: /* } */
998:
999: /* for(j=0; j<p; j++) { */
1000: /* (u[j] = t[j]); */
1001: /* } */
1002: /* u[p]='\0'; */
1003:
1004: /* for(j=0; j<= lg; j++) { */
1005: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1006: /* } */
1007: /* } */
1008:
1009: #ifdef _WIN32
1010: char * strsep(char **pp, const char *delim)
1011: {
1012: char *p, *q;
1013:
1014: if ((p = *pp) == NULL)
1015: return 0;
1016: if ((q = strpbrk (p, delim)) != NULL)
1017: {
1018: *pp = q + 1;
1019: *q = '\0';
1020: }
1021: else
1022: *pp = 0;
1023: return p;
1024: }
1025: #endif
1026:
1027: /********************** nrerror ********************/
1028:
1029: void nrerror(char error_text[])
1030: {
1031: fprintf(stderr,"ERREUR ...\n");
1032: fprintf(stderr,"%s\n",error_text);
1033: exit(EXIT_FAILURE);
1034: }
1035: /*********************** vector *******************/
1036: double *vector(int nl, int nh)
1037: {
1038: double *v;
1039: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1040: if (!v) nrerror("allocation failure in vector");
1041: return v-nl+NR_END;
1042: }
1043:
1044: /************************ free vector ******************/
1045: void free_vector(double*v, int nl, int nh)
1046: {
1047: free((FREE_ARG)(v+nl-NR_END));
1048: }
1049:
1050: /************************ivector *******************************/
1051: int *ivector(long nl,long nh)
1052: {
1053: int *v;
1054: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1055: if (!v) nrerror("allocation failure in ivector");
1056: return v-nl+NR_END;
1057: }
1058:
1059: /******************free ivector **************************/
1060: void free_ivector(int *v, long nl, long nh)
1061: {
1062: free((FREE_ARG)(v+nl-NR_END));
1063: }
1064:
1065: /************************lvector *******************************/
1066: long *lvector(long nl,long nh)
1067: {
1068: long *v;
1069: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1070: if (!v) nrerror("allocation failure in ivector");
1071: return v-nl+NR_END;
1072: }
1073:
1074: /******************free lvector **************************/
1075: void free_lvector(long *v, long nl, long nh)
1076: {
1077: free((FREE_ARG)(v+nl-NR_END));
1078: }
1079:
1080: /******************* imatrix *******************************/
1081: int **imatrix(long nrl, long nrh, long ncl, long nch)
1082: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1083: {
1084: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1085: int **m;
1086:
1087: /* allocate pointers to rows */
1088: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1089: if (!m) nrerror("allocation failure 1 in matrix()");
1090: m += NR_END;
1091: m -= nrl;
1092:
1093:
1094: /* allocate rows and set pointers to them */
1095: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1096: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1097: m[nrl] += NR_END;
1098: m[nrl] -= ncl;
1099:
1100: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1101:
1102: /* return pointer to array of pointers to rows */
1103: return m;
1104: }
1105:
1106: /****************** free_imatrix *************************/
1107: void free_imatrix(m,nrl,nrh,ncl,nch)
1108: int **m;
1109: long nch,ncl,nrh,nrl;
1110: /* free an int matrix allocated by imatrix() */
1111: {
1112: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1113: free((FREE_ARG) (m+nrl-NR_END));
1114: }
1115:
1116: /******************* matrix *******************************/
1117: double **matrix(long nrl, long nrh, long ncl, long nch)
1118: {
1119: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1120: double **m;
1121:
1122: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1123: if (!m) nrerror("allocation failure 1 in matrix()");
1124: m += NR_END;
1125: m -= nrl;
1126:
1127: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1128: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1129: m[nrl] += NR_END;
1130: m[nrl] -= ncl;
1131:
1132: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1133: return m;
1134: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1135: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1136: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1137: */
1138: }
1139:
1140: /*************************free matrix ************************/
1141: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1142: {
1143: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1144: free((FREE_ARG)(m+nrl-NR_END));
1145: }
1146:
1147: /******************* ma3x *******************************/
1148: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1149: {
1150: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1151: double ***m;
1152:
1153: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1154: if (!m) nrerror("allocation failure 1 in matrix()");
1155: m += NR_END;
1156: m -= nrl;
1157:
1158: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1159: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1160: m[nrl] += NR_END;
1161: m[nrl] -= ncl;
1162:
1163: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1164:
1165: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1166: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1167: m[nrl][ncl] += NR_END;
1168: m[nrl][ncl] -= nll;
1169: for (j=ncl+1; j<=nch; j++)
1170: m[nrl][j]=m[nrl][j-1]+nlay;
1171:
1172: for (i=nrl+1; i<=nrh; i++) {
1173: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1174: for (j=ncl+1; j<=nch; j++)
1175: m[i][j]=m[i][j-1]+nlay;
1176: }
1177: return m;
1178: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1179: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1180: */
1181: }
1182:
1183: /*************************free ma3x ************************/
1184: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1185: {
1186: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1187: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1188: free((FREE_ARG)(m+nrl-NR_END));
1189: }
1190:
1191: /*************** function subdirf ***********/
1192: char *subdirf(char fileres[])
1193: {
1194: /* Caution optionfilefiname is hidden */
1195: strcpy(tmpout,optionfilefiname);
1196: strcat(tmpout,"/"); /* Add to the right */
1197: strcat(tmpout,fileres);
1198: return tmpout;
1199: }
1200:
1201: /*************** function subdirf2 ***********/
1202: char *subdirf2(char fileres[], char *preop)
1203: {
1204:
1205: /* Caution optionfilefiname is hidden */
1206: strcpy(tmpout,optionfilefiname);
1207: strcat(tmpout,"/");
1208: strcat(tmpout,preop);
1209: strcat(tmpout,fileres);
1210: return tmpout;
1211: }
1212:
1213: /*************** function subdirf3 ***********/
1214: char *subdirf3(char fileres[], char *preop, char *preop2)
1215: {
1216:
1217: /* Caution optionfilefiname is hidden */
1218: strcpy(tmpout,optionfilefiname);
1219: strcat(tmpout,"/");
1220: strcat(tmpout,preop);
1221: strcat(tmpout,preop2);
1222: strcat(tmpout,fileres);
1223: return tmpout;
1224: }
1225:
1226: char *asc_diff_time(long time_sec, char ascdiff[])
1227: {
1228: long sec_left, days, hours, minutes;
1229: days = (time_sec) / (60*60*24);
1230: sec_left = (time_sec) % (60*60*24);
1231: hours = (sec_left) / (60*60) ;
1232: sec_left = (sec_left) %(60*60);
1233: minutes = (sec_left) /60;
1234: sec_left = (sec_left) % (60);
1235: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1236: return ascdiff;
1237: }
1238:
1239: /***************** f1dim *************************/
1240: extern int ncom;
1241: extern double *pcom,*xicom;
1242: extern double (*nrfunc)(double []);
1243:
1244: double f1dim(double x)
1245: {
1246: int j;
1247: double f;
1248: double *xt;
1249:
1250: xt=vector(1,ncom);
1251: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1252: f=(*nrfunc)(xt);
1253: free_vector(xt,1,ncom);
1254: return f;
1255: }
1256:
1257: /*****************brent *************************/
1258: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1259: {
1260: int iter;
1261: double a,b,d,etemp;
1262: double fu=0,fv,fw,fx;
1263: double ftemp=0.;
1264: double p,q,r,tol1,tol2,u,v,w,x,xm;
1265: double e=0.0;
1266:
1267: a=(ax < cx ? ax : cx);
1268: b=(ax > cx ? ax : cx);
1269: x=w=v=bx;
1270: fw=fv=fx=(*f)(x);
1271: for (iter=1;iter<=ITMAX;iter++) {
1272: xm=0.5*(a+b);
1273: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1274: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1275: printf(".");fflush(stdout);
1276: fprintf(ficlog,".");fflush(ficlog);
1277: #ifdef DEBUGBRENT
1278: 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);
1279: 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);
1280: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1281: #endif
1282: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1283: *xmin=x;
1284: return fx;
1285: }
1286: ftemp=fu;
1287: if (fabs(e) > tol1) {
1288: r=(x-w)*(fx-fv);
1289: q=(x-v)*(fx-fw);
1290: p=(x-v)*q-(x-w)*r;
1291: q=2.0*(q-r);
1292: if (q > 0.0) p = -p;
1293: q=fabs(q);
1294: etemp=e;
1295: e=d;
1296: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1297: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1298: else {
1299: d=p/q;
1300: u=x+d;
1301: if (u-a < tol2 || b-u < tol2)
1302: d=SIGN(tol1,xm-x);
1303: }
1304: } else {
1305: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1306: }
1307: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1308: fu=(*f)(u);
1309: if (fu <= fx) {
1310: if (u >= x) a=x; else b=x;
1311: SHFT(v,w,x,u)
1312: SHFT(fv,fw,fx,fu)
1313: } else {
1314: if (u < x) a=u; else b=u;
1315: if (fu <= fw || w == x) {
1316: v=w;
1317: w=u;
1318: fv=fw;
1319: fw=fu;
1320: } else if (fu <= fv || v == x || v == w) {
1321: v=u;
1322: fv=fu;
1323: }
1324: }
1325: }
1326: nrerror("Too many iterations in brent");
1327: *xmin=x;
1328: return fx;
1329: }
1330:
1331: /****************** mnbrak ***********************/
1332:
1333: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1334: double (*func)(double))
1335: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1336: the downhill direction (defined by the function as evaluated at the initial points) and returns
1337: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1338: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1339: */
1340: double ulim,u,r,q, dum;
1341: double fu;
1342:
1343: *fa=(*func)(*ax);
1344: *fb=(*func)(*bx);
1345: if (*fb > *fa) {
1346: SHFT(dum,*ax,*bx,dum)
1347: SHFT(dum,*fb,*fa,dum)
1348: }
1349: *cx=(*bx)+GOLD*(*bx-*ax);
1350: *fc=(*func)(*cx);
1351: #ifdef DEBUG
1352: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1353: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1354: #endif
1355: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1356: r=(*bx-*ax)*(*fb-*fc);
1357: q=(*bx-*cx)*(*fb-*fa);
1358: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1359: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1360: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1361: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1362: fu=(*func)(u);
1363: #ifdef DEBUG
1364: /* f(x)=A(x-u)**2+f(u) */
1365: double A, fparabu;
1366: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1367: fparabu= *fa - A*(*ax-u)*(*ax-u);
1368: 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);
1369: 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);
1370: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1371: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1372: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1373: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1374: #endif
1375: #ifdef MNBRAKORIGINAL
1376: #else
1377: if (fu > *fc) {
1378: #ifdef DEBUG
1379: printf("mnbrak4 fu > fc \n");
1380: fprintf(ficlog, "mnbrak4 fu > fc\n");
1381: #endif
1382: /* 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 *\/ */
1383: /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\/ */
1384: dum=u; /* Shifting c and u */
1385: u = *cx;
1386: *cx = dum;
1387: dum = fu;
1388: fu = *fc;
1389: *fc =dum;
1390: } else { /* end */
1391: #ifdef DEBUG
1392: printf("mnbrak3 fu < fc \n");
1393: fprintf(ficlog, "mnbrak3 fu < fc\n");
1394: #endif
1395: dum=u; /* Shifting c and u */
1396: u = *cx;
1397: *cx = dum;
1398: dum = fu;
1399: fu = *fc;
1400: *fc =dum;
1401: }
1402: #endif
1403: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1404: #ifdef DEBUG
1405: printf("mnbrak2 u after c but before ulim\n");
1406: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1407: #endif
1408: fu=(*func)(u);
1409: if (fu < *fc) {
1410: #ifdef DEBUG
1411: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1412: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1413: #endif
1414: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1415: SHFT(*fb,*fc,fu,(*func)(u))
1416: }
1417: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1418: #ifdef DEBUG
1419: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1420: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1421: #endif
1422: u=ulim;
1423: fu=(*func)(u);
1424: } else { /* u could be left to b (if r > q parabola has a maximum) */
1425: #ifdef DEBUG
1426: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1427: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1428: #endif
1429: u=(*cx)+GOLD*(*cx-*bx);
1430: fu=(*func)(u);
1431: } /* end tests */
1432: SHFT(*ax,*bx,*cx,u)
1433: SHFT(*fa,*fb,*fc,fu)
1434: #ifdef DEBUG
1435: 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);
1436: 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);
1437: #endif
1438: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1439: }
1440:
1441: /*************** linmin ************************/
1442: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1443: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1444: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1445: the value of func at the returned location p . This is actually all accomplished by calling the
1446: routines mnbrak and brent .*/
1447: int ncom;
1448: double *pcom,*xicom;
1449: double (*nrfunc)(double []);
1450:
1451: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1452: {
1453: double brent(double ax, double bx, double cx,
1454: double (*f)(double), double tol, double *xmin);
1455: double f1dim(double x);
1456: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1457: double *fc, double (*func)(double));
1458: int j;
1459: double xx,xmin,bx,ax;
1460: double fx,fb,fa;
1461:
1462: ncom=n;
1463: pcom=vector(1,n);
1464: xicom=vector(1,n);
1465: nrfunc=func;
1466: for (j=1;j<=n;j++) {
1467: pcom[j]=p[j];
1468: xicom[j]=xi[j];
1469: }
1470: ax=0.0;
1471: xx=1.0;
1472: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1473: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1474: #ifdef DEBUG
1475: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1476: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1477: #endif
1478: for (j=1;j<=n;j++) {
1479: xi[j] *= xmin;
1480: p[j] += xi[j];
1481: }
1482: free_vector(xicom,1,n);
1483: free_vector(pcom,1,n);
1484: }
1485:
1486:
1487: /*************** powell ************************/
1488: /*
1489: Minimization of a function func of n variables. Input consists of an initial starting point
1490: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1491: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1492: such that failure to decrease by more than this amount on one iteration signals doneness. On
1493: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1494: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1495: */
1496: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1497: double (*func)(double []))
1498: {
1499: void linmin(double p[], double xi[], int n, double *fret,
1500: double (*func)(double []));
1501: int i,ibig,j;
1502: double del,t,*pt,*ptt,*xit;
1503: double directest;
1504: double fp,fptt;
1505: double *xits;
1506: int niterf, itmp;
1507:
1508: pt=vector(1,n);
1509: ptt=vector(1,n);
1510: xit=vector(1,n);
1511: xits=vector(1,n);
1512: *fret=(*func)(p);
1513: for (j=1;j<=n;j++) pt[j]=p[j];
1514: rcurr_time = time(NULL);
1515: for (*iter=1;;++(*iter)) {
1516: fp=(*fret);
1517: ibig=0;
1518: del=0.0;
1519: rlast_time=rcurr_time;
1520: /* (void) gettimeofday(&curr_time,&tzp); */
1521: rcurr_time = time(NULL);
1522: curr_time = *localtime(&rcurr_time);
1523: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1524: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1525: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1526: for (i=1;i<=n;i++) {
1527: printf(" %d %.12f",i, p[i]);
1528: fprintf(ficlog," %d %.12lf",i, p[i]);
1529: fprintf(ficrespow," %.12lf", p[i]);
1530: }
1531: printf("\n");
1532: fprintf(ficlog,"\n");
1533: fprintf(ficrespow,"\n");fflush(ficrespow);
1534: if(*iter <=3){
1535: tml = *localtime(&rcurr_time);
1536: strcpy(strcurr,asctime(&tml));
1537: rforecast_time=rcurr_time;
1538: itmp = strlen(strcurr);
1539: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1540: strcurr[itmp-1]='\0';
1541: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1542: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1543: for(niterf=10;niterf<=30;niterf+=10){
1544: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1545: forecast_time = *localtime(&rforecast_time);
1546: strcpy(strfor,asctime(&forecast_time));
1547: itmp = strlen(strfor);
1548: if(strfor[itmp-1]=='\n')
1549: strfor[itmp-1]='\0';
1550: 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);
1551: 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);
1552: }
1553: }
1554: for (i=1;i<=n;i++) {
1555: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1556: fptt=(*fret);
1557: #ifdef DEBUG
1558: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1559: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1560: #endif
1561: printf("%d",i);fflush(stdout);
1562: fprintf(ficlog,"%d",i);fflush(ficlog);
1563: linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
1564: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1565: because that direction will be replaced unless the gain del is small
1566: in comparison with the 'probable' gain, mu^2, with the last average direction.
1567: Unless the n directions are conjugate some gain in the determinant may be obtained
1568: with the new direction.
1569: */
1570: del=fabs(fptt-(*fret));
1571: ibig=i;
1572: }
1573: #ifdef DEBUG
1574: printf("%d %.12e",i,(*fret));
1575: fprintf(ficlog,"%d %.12e",i,(*fret));
1576: for (j=1;j<=n;j++) {
1577: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1578: printf(" x(%d)=%.12e",j,xit[j]);
1579: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1580: }
1581: for(j=1;j<=n;j++) {
1582: printf(" p(%d)=%.12e",j,p[j]);
1583: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1584: }
1585: printf("\n");
1586: fprintf(ficlog,"\n");
1587: #endif
1588: } /* end i */
1589: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1590: #ifdef DEBUG
1591: int k[2],l;
1592: k[0]=1;
1593: k[1]=-1;
1594: printf("Max: %.12e",(*func)(p));
1595: fprintf(ficlog,"Max: %.12e",(*func)(p));
1596: for (j=1;j<=n;j++) {
1597: printf(" %.12e",p[j]);
1598: fprintf(ficlog," %.12e",p[j]);
1599: }
1600: printf("\n");
1601: fprintf(ficlog,"\n");
1602: for(l=0;l<=1;l++) {
1603: for (j=1;j<=n;j++) {
1604: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1605: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1606: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1607: }
1608: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1609: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1610: }
1611: #endif
1612:
1613:
1614: free_vector(xit,1,n);
1615: free_vector(xits,1,n);
1616: free_vector(ptt,1,n);
1617: free_vector(pt,1,n);
1618: return;
1619: }
1620: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1621: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1622: ptt[j]=2.0*p[j]-pt[j];
1623: xit[j]=p[j]-pt[j];
1624: pt[j]=p[j];
1625: }
1626: fptt=(*func)(ptt); /* f_3 */
1627: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1628: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1629: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1630: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1631: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1632: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1633: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1634: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1635: #ifdef NRCORIGINAL
1636: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1637: #else
1638: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1639: t= t- del*SQR(fp-fptt);
1640: #endif
1641: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1642: #ifdef DEBUG
1643: 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);
1644: 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);
1645: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1646: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1647: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1648: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1649: 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);
1650: 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);
1651: #endif
1652: #ifdef POWELLORIGINAL
1653: if (t < 0.0) { /* Then we use it for new direction */
1654: #else
1655: if (directest*t < 0.0) { /* Contradiction between both tests */
1656: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1657: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1658: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1659: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1660: }
1661: if (directest < 0.0) { /* Then we use it for new direction */
1662: #endif
1663: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1664: for (j=1;j<=n;j++) {
1665: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1666: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1667: }
1668: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1669: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1670:
1671: #ifdef DEBUG
1672: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1673: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1674: for(j=1;j<=n;j++){
1675: printf(" %.12e",xit[j]);
1676: fprintf(ficlog," %.12e",xit[j]);
1677: }
1678: printf("\n");
1679: fprintf(ficlog,"\n");
1680: #endif
1681: } /* end of t negative */
1682: } /* end if (fptt < fp) */
1683: }
1684: }
1685:
1686: /**** Prevalence limit (stable or period prevalence) ****************/
1687:
1688: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1689: {
1690: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1691: matrix by transitions matrix until convergence is reached */
1692:
1693: int i, ii,j,k;
1694: double min, max, maxmin, maxmax,sumnew=0.;
1695: /* double **matprod2(); */ /* test */
1696: double **out, cov[NCOVMAX+1], **pmij();
1697: double **newm;
1698: double agefin, delaymax=50 ; /* Max number of years to converge */
1699:
1700: for (ii=1;ii<=nlstate+ndeath;ii++)
1701: for (j=1;j<=nlstate+ndeath;j++){
1702: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1703: }
1704:
1705: cov[1]=1.;
1706:
1707: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1708: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1709: newm=savm;
1710: /* Covariates have to be included here again */
1711: cov[2]=agefin;
1712:
1713: for (k=1; k<=cptcovn;k++) {
1714: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1715: /*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]]);*/
1716: }
1717: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1718: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1719: for (k=1; k<=cptcovprod;k++) /* Useless */
1720: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1721:
1722: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1723: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1724: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1725: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1726: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1727: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1728:
1729: savm=oldm;
1730: oldm=newm;
1731: maxmax=0.;
1732: for(j=1;j<=nlstate;j++){
1733: min=1.;
1734: max=0.;
1735: for(i=1; i<=nlstate; i++) {
1736: sumnew=0;
1737: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1738: prlim[i][j]= newm[i][j]/(1-sumnew);
1739: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1740: max=FMAX(max,prlim[i][j]);
1741: min=FMIN(min,prlim[i][j]);
1742: }
1743: maxmin=max-min;
1744: maxmax=FMAX(maxmax,maxmin);
1745: } /* j loop */
1746: if(maxmax < ftolpl){
1747: return prlim;
1748: }
1749: } /* age loop */
1750: return prlim; /* should not reach here */
1751: }
1752:
1753: /*************** transition probabilities ***************/
1754:
1755: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1756: {
1757: /* According to parameters values stored in x and the covariate's values stored in cov,
1758: computes the probability to be observed in state j being in state i by appying the
1759: model to the ncovmodel covariates (including constant and age).
1760: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1761: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1762: ncth covariate in the global vector x is given by the formula:
1763: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1764: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1765: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1766: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1767: Outputs ps[i][j] the probability to be observed in j being in j according to
1768: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1769: */
1770: double s1, lnpijopii;
1771: /*double t34;*/
1772: int i,j, nc, ii, jj;
1773:
1774: for(i=1; i<= nlstate; i++){
1775: for(j=1; j<i;j++){
1776: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1777: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1778: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1779: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1780: }
1781: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1782: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1783: }
1784: for(j=i+1; j<=nlstate+ndeath;j++){
1785: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1786: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1787: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1788: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1789: }
1790: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1791: }
1792: }
1793:
1794: for(i=1; i<= nlstate; i++){
1795: s1=0;
1796: for(j=1; j<i; j++){
1797: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1798: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1799: }
1800: for(j=i+1; j<=nlstate+ndeath; j++){
1801: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1802: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1803: }
1804: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1805: ps[i][i]=1./(s1+1.);
1806: /* Computing other pijs */
1807: for(j=1; j<i; j++)
1808: ps[i][j]= exp(ps[i][j])*ps[i][i];
1809: for(j=i+1; j<=nlstate+ndeath; j++)
1810: ps[i][j]= exp(ps[i][j])*ps[i][i];
1811: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1812: } /* end i */
1813:
1814: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1815: for(jj=1; jj<= nlstate+ndeath; jj++){
1816: ps[ii][jj]=0;
1817: ps[ii][ii]=1;
1818: }
1819: }
1820:
1821:
1822: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1823: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1824: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1825: /* } */
1826: /* printf("\n "); */
1827: /* } */
1828: /* printf("\n ");printf("%lf ",cov[2]);*/
1829: /*
1830: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1831: goto end;*/
1832: return ps;
1833: }
1834:
1835: /**************** Product of 2 matrices ******************/
1836:
1837: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1838: {
1839: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1840: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1841: /* in, b, out are matrice of pointers which should have been initialized
1842: before: only the contents of out is modified. The function returns
1843: a pointer to pointers identical to out */
1844: int i, j, k;
1845: for(i=nrl; i<= nrh; i++)
1846: for(k=ncolol; k<=ncoloh; k++){
1847: out[i][k]=0.;
1848: for(j=ncl; j<=nch; j++)
1849: out[i][k] +=in[i][j]*b[j][k];
1850: }
1851: return out;
1852: }
1853:
1854:
1855: /************* Higher Matrix Product ***************/
1856:
1857: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1858: {
1859: /* Computes the transition matrix starting at age 'age' over
1860: 'nhstepm*hstepm*stepm' months (i.e. until
1861: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1862: nhstepm*hstepm matrices.
1863: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1864: (typically every 2 years instead of every month which is too big
1865: for the memory).
1866: Model is determined by parameters x and covariates have to be
1867: included manually here.
1868:
1869: */
1870:
1871: int i, j, d, h, k;
1872: double **out, cov[NCOVMAX+1];
1873: double **newm;
1874:
1875: /* Hstepm could be zero and should return the unit matrix */
1876: for (i=1;i<=nlstate+ndeath;i++)
1877: for (j=1;j<=nlstate+ndeath;j++){
1878: oldm[i][j]=(i==j ? 1.0 : 0.0);
1879: po[i][j][0]=(i==j ? 1.0 : 0.0);
1880: }
1881: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1882: for(h=1; h <=nhstepm; h++){
1883: for(d=1; d <=hstepm; d++){
1884: newm=savm;
1885: /* Covariates have to be included here again */
1886: cov[1]=1.;
1887: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1888: for (k=1; k<=cptcovn;k++)
1889: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1890: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1891: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1892: cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1893: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1894: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1895:
1896:
1897: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1898: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1899: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1900: pmij(pmmij,cov,ncovmodel,x,nlstate));
1901: savm=oldm;
1902: oldm=newm;
1903: }
1904: for(i=1; i<=nlstate+ndeath; i++)
1905: for(j=1;j<=nlstate+ndeath;j++) {
1906: po[i][j][h]=newm[i][j];
1907: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1908: }
1909: /*printf("h=%d ",h);*/
1910: } /* end h */
1911: /* printf("\n H=%d \n",h); */
1912: return po;
1913: }
1914:
1915: #ifdef NLOPT
1916: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1917: double fret;
1918: double *xt;
1919: int j;
1920: myfunc_data *d2 = (myfunc_data *) pd;
1921: /* xt = (p1-1); */
1922: xt=vector(1,n);
1923: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1924:
1925: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1926: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1927: printf("Function = %.12lf ",fret);
1928: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1929: printf("\n");
1930: free_vector(xt,1,n);
1931: return fret;
1932: }
1933: #endif
1934:
1935: /*************** log-likelihood *************/
1936: double func( double *x)
1937: {
1938: int i, ii, j, k, mi, d, kk;
1939: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1940: double **out;
1941: double sw; /* Sum of weights */
1942: double lli; /* Individual log likelihood */
1943: int s1, s2;
1944: double bbh, survp;
1945: long ipmx;
1946: /*extern weight */
1947: /* We are differentiating ll according to initial status */
1948: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1949: /*for(i=1;i<imx;i++)
1950: printf(" %d\n",s[4][i]);
1951: */
1952:
1953: ++countcallfunc;
1954:
1955: cov[1]=1.;
1956:
1957: for(k=1; k<=nlstate; k++) ll[k]=0.;
1958:
1959: if(mle==1){
1960: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1961: /* Computes the values of the ncovmodel covariates of the model
1962: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1963: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1964: to be observed in j being in i according to the model.
1965: */
1966: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1967: cov[2+k]=covar[Tvar[k]][i];
1968: }
1969: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1970: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1971: has been calculated etc */
1972: for(mi=1; mi<= wav[i]-1; mi++){
1973: for (ii=1;ii<=nlstate+ndeath;ii++)
1974: for (j=1;j<=nlstate+ndeath;j++){
1975: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1976: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1977: }
1978: for(d=0; d<dh[mi][i]; d++){
1979: newm=savm;
1980: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1981: for (kk=1; kk<=cptcovage;kk++) {
1982: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1983: }
1984: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1985: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1986: savm=oldm;
1987: oldm=newm;
1988: } /* end mult */
1989:
1990: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1991: /* But now since version 0.9 we anticipate for bias at large stepm.
1992: * If stepm is larger than one month (smallest stepm) and if the exact delay
1993: * (in months) between two waves is not a multiple of stepm, we rounded to
1994: * the nearest (and in case of equal distance, to the lowest) interval but now
1995: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1996: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1997: * probability in order to take into account the bias as a fraction of the way
1998: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1999: * -stepm/2 to stepm/2 .
2000: * For stepm=1 the results are the same as for previous versions of Imach.
2001: * For stepm > 1 the results are less biased than in previous versions.
2002: */
2003: s1=s[mw[mi][i]][i];
2004: s2=s[mw[mi+1][i]][i];
2005: bbh=(double)bh[mi][i]/(double)stepm;
2006: /* bias bh is positive if real duration
2007: * is higher than the multiple of stepm and negative otherwise.
2008: */
2009: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2010: if( s2 > nlstate){
2011: /* i.e. if s2 is a death state and if the date of death is known
2012: then the contribution to the likelihood is the probability to
2013: die between last step unit time and current step unit time,
2014: which is also equal to probability to die before dh
2015: minus probability to die before dh-stepm .
2016: In version up to 0.92 likelihood was computed
2017: as if date of death was unknown. Death was treated as any other
2018: health state: the date of the interview describes the actual state
2019: and not the date of a change in health state. The former idea was
2020: to consider that at each interview the state was recorded
2021: (healthy, disable or death) and IMaCh was corrected; but when we
2022: introduced the exact date of death then we should have modified
2023: the contribution of an exact death to the likelihood. This new
2024: contribution is smaller and very dependent of the step unit
2025: stepm. It is no more the probability to die between last interview
2026: and month of death but the probability to survive from last
2027: interview up to one month before death multiplied by the
2028: probability to die within a month. Thanks to Chris
2029: Jackson for correcting this bug. Former versions increased
2030: mortality artificially. The bad side is that we add another loop
2031: which slows down the processing. The difference can be up to 10%
2032: lower mortality.
2033: */
2034: /* If, at the beginning of the maximization mostly, the
2035: cumulative probability or probability to be dead is
2036: constant (ie = 1) over time d, the difference is equal to
2037: 0. out[s1][3] = savm[s1][3]: probability, being at state
2038: s1 at precedent wave, to be dead a month before current
2039: wave is equal to probability, being at state s1 at
2040: precedent wave, to be dead at mont of the current
2041: wave. Then the observed probability (that this person died)
2042: is null according to current estimated parameter. In fact,
2043: it should be very low but not zero otherwise the log go to
2044: infinity.
2045: */
2046: /* #ifdef INFINITYORIGINAL */
2047: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2048: /* #else */
2049: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2050: /* lli=log(mytinydouble); */
2051: /* else */
2052: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2053: /* #endif */
2054: lli=log(out[s1][s2] - savm[s1][s2]);
2055:
2056: } else if (s2==-2) {
2057: for (j=1,survp=0. ; j<=nlstate; j++)
2058: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2059: /*survp += out[s1][j]; */
2060: lli= log(survp);
2061: }
2062:
2063: else if (s2==-4) {
2064: for (j=3,survp=0. ; j<=nlstate; j++)
2065: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2066: lli= log(survp);
2067: }
2068:
2069: else if (s2==-5) {
2070: for (j=1,survp=0. ; j<=2; j++)
2071: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2072: lli= log(survp);
2073: }
2074:
2075: else{
2076: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2077: /* 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 */
2078: }
2079: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2080: /*if(lli ==000.0)*/
2081: /*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); */
2082: ipmx +=1;
2083: sw += weight[i];
2084: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2085: /* if (lli < log(mytinydouble)){ */
2086: /* 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); */
2087: /* 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]); */
2088: /* } */
2089: } /* end of wave */
2090: } /* end of individual */
2091: } else if(mle==2){
2092: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2093: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2094: for(mi=1; mi<= wav[i]-1; mi++){
2095: for (ii=1;ii<=nlstate+ndeath;ii++)
2096: for (j=1;j<=nlstate+ndeath;j++){
2097: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2098: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2099: }
2100: for(d=0; d<=dh[mi][i]; d++){
2101: newm=savm;
2102: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2103: for (kk=1; kk<=cptcovage;kk++) {
2104: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2105: }
2106: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2107: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2108: savm=oldm;
2109: oldm=newm;
2110: } /* end mult */
2111:
2112: s1=s[mw[mi][i]][i];
2113: s2=s[mw[mi+1][i]][i];
2114: bbh=(double)bh[mi][i]/(double)stepm;
2115: 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 */
2116: ipmx +=1;
2117: sw += weight[i];
2118: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2119: } /* end of wave */
2120: } /* end of individual */
2121: } else if(mle==3){ /* exponential inter-extrapolation */
2122: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2123: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2124: for(mi=1; mi<= wav[i]-1; mi++){
2125: for (ii=1;ii<=nlstate+ndeath;ii++)
2126: for (j=1;j<=nlstate+ndeath;j++){
2127: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2128: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2129: }
2130: for(d=0; d<dh[mi][i]; d++){
2131: newm=savm;
2132: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2133: for (kk=1; kk<=cptcovage;kk++) {
2134: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2135: }
2136: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2137: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2138: savm=oldm;
2139: oldm=newm;
2140: } /* end mult */
2141:
2142: s1=s[mw[mi][i]][i];
2143: s2=s[mw[mi+1][i]][i];
2144: bbh=(double)bh[mi][i]/(double)stepm;
2145: 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 */
2146: ipmx +=1;
2147: sw += weight[i];
2148: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2149: } /* end of wave */
2150: } /* end of individual */
2151: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2152: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2153: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2154: for(mi=1; mi<= wav[i]-1; mi++){
2155: for (ii=1;ii<=nlstate+ndeath;ii++)
2156: for (j=1;j<=nlstate+ndeath;j++){
2157: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2158: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2159: }
2160: for(d=0; d<dh[mi][i]; d++){
2161: newm=savm;
2162: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2163: for (kk=1; kk<=cptcovage;kk++) {
2164: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2165: }
2166:
2167: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2168: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2169: savm=oldm;
2170: oldm=newm;
2171: } /* end mult */
2172:
2173: s1=s[mw[mi][i]][i];
2174: s2=s[mw[mi+1][i]][i];
2175: if( s2 > nlstate){
2176: lli=log(out[s1][s2] - savm[s1][s2]);
2177: }else{
2178: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2179: }
2180: ipmx +=1;
2181: sw += weight[i];
2182: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2183: /* 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]); */
2184: } /* end of wave */
2185: } /* end of individual */
2186: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2187: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2188: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2189: for(mi=1; mi<= wav[i]-1; mi++){
2190: for (ii=1;ii<=nlstate+ndeath;ii++)
2191: for (j=1;j<=nlstate+ndeath;j++){
2192: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2193: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2194: }
2195: for(d=0; d<dh[mi][i]; d++){
2196: newm=savm;
2197: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2198: for (kk=1; kk<=cptcovage;kk++) {
2199: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2200: }
2201:
2202: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2203: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2204: savm=oldm;
2205: oldm=newm;
2206: } /* end mult */
2207:
2208: s1=s[mw[mi][i]][i];
2209: s2=s[mw[mi+1][i]][i];
2210: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2211: ipmx +=1;
2212: sw += weight[i];
2213: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2214: /*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]);*/
2215: } /* end of wave */
2216: } /* end of individual */
2217: } /* End of if */
2218: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2219: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2220: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2221: return -l;
2222: }
2223:
2224: /*************** log-likelihood *************/
2225: double funcone( double *x)
2226: {
2227: /* Same as likeli but slower because of a lot of printf and if */
2228: int i, ii, j, k, mi, d, kk;
2229: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2230: double **out;
2231: double lli; /* Individual log likelihood */
2232: double llt;
2233: int s1, s2;
2234: double bbh, survp;
2235: /*extern weight */
2236: /* We are differentiating ll according to initial status */
2237: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2238: /*for(i=1;i<imx;i++)
2239: printf(" %d\n",s[4][i]);
2240: */
2241: cov[1]=1.;
2242:
2243: for(k=1; k<=nlstate; k++) ll[k]=0.;
2244:
2245: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2246: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2247: for(mi=1; mi<= wav[i]-1; mi++){
2248: for (ii=1;ii<=nlstate+ndeath;ii++)
2249: for (j=1;j<=nlstate+ndeath;j++){
2250: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2251: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2252: }
2253: for(d=0; d<dh[mi][i]; d++){
2254: newm=savm;
2255: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2256: for (kk=1; kk<=cptcovage;kk++) {
2257: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2258: }
2259: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2260: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2261: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2262: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2263: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2264: savm=oldm;
2265: oldm=newm;
2266: } /* end mult */
2267:
2268: s1=s[mw[mi][i]][i];
2269: s2=s[mw[mi+1][i]][i];
2270: bbh=(double)bh[mi][i]/(double)stepm;
2271: /* bias is positive if real duration
2272: * is higher than the multiple of stepm and negative otherwise.
2273: */
2274: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2275: lli=log(out[s1][s2] - savm[s1][s2]);
2276: } else if (s2==-2) {
2277: for (j=1,survp=0. ; j<=nlstate; j++)
2278: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2279: lli= log(survp);
2280: }else if (mle==1){
2281: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2282: } else if(mle==2){
2283: 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 */
2284: } else if(mle==3){ /* exponential inter-extrapolation */
2285: 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 */
2286: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2287: lli=log(out[s1][s2]); /* Original formula */
2288: } else{ /* mle=0 back to 1 */
2289: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2290: /*lli=log(out[s1][s2]); */ /* Original formula */
2291: } /* End of if */
2292: ipmx +=1;
2293: sw += weight[i];
2294: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2295: /*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]); */
2296: if(globpr){
2297: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2298: %11.6f %11.6f %11.6f ", \
2299: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2300: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2301: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2302: llt +=ll[k]*gipmx/gsw;
2303: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2304: }
2305: fprintf(ficresilk," %10.6f\n", -llt);
2306: }
2307: } /* end of wave */
2308: } /* end of individual */
2309: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2310: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2311: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2312: if(globpr==0){ /* First time we count the contributions and weights */
2313: gipmx=ipmx;
2314: gsw=sw;
2315: }
2316: return -l;
2317: }
2318:
2319:
2320: /*************** function likelione ***********/
2321: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2322: {
2323: /* This routine should help understanding what is done with
2324: the selection of individuals/waves and
2325: to check the exact contribution to the likelihood.
2326: Plotting could be done.
2327: */
2328: int k;
2329:
2330: if(*globpri !=0){ /* Just counts and sums, no printings */
2331: strcpy(fileresilk,"ilk");
2332: strcat(fileresilk,fileres);
2333: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2334: printf("Problem with resultfile: %s\n", fileresilk);
2335: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2336: }
2337: 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");
2338: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2339: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2340: for(k=1; k<=nlstate; k++)
2341: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2342: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2343: }
2344:
2345: *fretone=(*funcone)(p);
2346: if(*globpri !=0){
2347: fclose(ficresilk);
2348: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2349: fflush(fichtm);
2350: }
2351: return;
2352: }
2353:
2354:
2355: /*********** Maximum Likelihood Estimation ***************/
2356:
2357: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2358: {
2359: int i,j, iter=0;
2360: double **xi;
2361: double fret;
2362: double fretone; /* Only one call to likelihood */
2363: /* char filerespow[FILENAMELENGTH];*/
2364:
2365: #ifdef NLOPT
2366: int creturn;
2367: nlopt_opt opt;
2368: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2369: double *lb;
2370: double minf; /* the minimum objective value, upon return */
2371: double * p1; /* Shifted parameters from 0 instead of 1 */
2372: myfunc_data dinst, *d = &dinst;
2373: #endif
2374:
2375:
2376: xi=matrix(1,npar,1,npar);
2377: for (i=1;i<=npar;i++)
2378: for (j=1;j<=npar;j++)
2379: xi[i][j]=(i==j ? 1.0 : 0.0);
2380: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2381: strcpy(filerespow,"pow");
2382: strcat(filerespow,fileres);
2383: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2384: printf("Problem with resultfile: %s\n", filerespow);
2385: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2386: }
2387: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2388: for (i=1;i<=nlstate;i++)
2389: for(j=1;j<=nlstate+ndeath;j++)
2390: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2391: fprintf(ficrespow,"\n");
2392: #ifdef POWELL
2393: powell(p,xi,npar,ftol,&iter,&fret,func);
2394: #endif
2395:
2396: #ifdef NLOPT
2397: #ifdef NEWUOA
2398: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2399: #else
2400: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2401: #endif
2402: lb=vector(0,npar-1);
2403: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2404: nlopt_set_lower_bounds(opt, lb);
2405: nlopt_set_initial_step1(opt, 0.1);
2406:
2407: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2408: d->function = func;
2409: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2410: nlopt_set_min_objective(opt, myfunc, d);
2411: nlopt_set_xtol_rel(opt, ftol);
2412: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2413: printf("nlopt failed! %d\n",creturn);
2414: }
2415: else {
2416: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2417: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2418: iter=1; /* not equal */
2419: }
2420: nlopt_destroy(opt);
2421: #endif
2422: free_matrix(xi,1,npar,1,npar);
2423: fclose(ficrespow);
2424: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2425: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2426: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2427:
2428: }
2429:
2430: /**** Computes Hessian and covariance matrix ***/
2431: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2432: {
2433: double **a,**y,*x,pd;
2434: double **hess;
2435: int i, j;
2436: int *indx;
2437:
2438: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2439: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2440: void lubksb(double **a, int npar, int *indx, double b[]) ;
2441: void ludcmp(double **a, int npar, int *indx, double *d) ;
2442: double gompertz(double p[]);
2443: hess=matrix(1,npar,1,npar);
2444:
2445: printf("\nCalculation of the hessian matrix. Wait...\n");
2446: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2447: for (i=1;i<=npar;i++){
2448: printf("%d",i);fflush(stdout);
2449: fprintf(ficlog,"%d",i);fflush(ficlog);
2450:
2451: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2452:
2453: /* printf(" %f ",p[i]);
2454: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2455: }
2456:
2457: for (i=1;i<=npar;i++) {
2458: for (j=1;j<=npar;j++) {
2459: if (j>i) {
2460: printf(".%d%d",i,j);fflush(stdout);
2461: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2462: hess[i][j]=hessij(p,delti,i,j,func,npar);
2463:
2464: hess[j][i]=hess[i][j];
2465: /*printf(" %lf ",hess[i][j]);*/
2466: }
2467: }
2468: }
2469: printf("\n");
2470: fprintf(ficlog,"\n");
2471:
2472: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2473: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2474:
2475: a=matrix(1,npar,1,npar);
2476: y=matrix(1,npar,1,npar);
2477: x=vector(1,npar);
2478: indx=ivector(1,npar);
2479: for (i=1;i<=npar;i++)
2480: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2481: ludcmp(a,npar,indx,&pd);
2482:
2483: for (j=1;j<=npar;j++) {
2484: for (i=1;i<=npar;i++) x[i]=0;
2485: x[j]=1;
2486: lubksb(a,npar,indx,x);
2487: for (i=1;i<=npar;i++){
2488: matcov[i][j]=x[i];
2489: }
2490: }
2491:
2492: printf("\n#Hessian matrix#\n");
2493: fprintf(ficlog,"\n#Hessian matrix#\n");
2494: for (i=1;i<=npar;i++) {
2495: for (j=1;j<=npar;j++) {
2496: printf("%.3e ",hess[i][j]);
2497: fprintf(ficlog,"%.3e ",hess[i][j]);
2498: }
2499: printf("\n");
2500: fprintf(ficlog,"\n");
2501: }
2502:
2503: /* Recompute Inverse */
2504: for (i=1;i<=npar;i++)
2505: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2506: ludcmp(a,npar,indx,&pd);
2507:
2508: /* printf("\n#Hessian matrix recomputed#\n");
2509:
2510: for (j=1;j<=npar;j++) {
2511: for (i=1;i<=npar;i++) x[i]=0;
2512: x[j]=1;
2513: lubksb(a,npar,indx,x);
2514: for (i=1;i<=npar;i++){
2515: y[i][j]=x[i];
2516: printf("%.3e ",y[i][j]);
2517: fprintf(ficlog,"%.3e ",y[i][j]);
2518: }
2519: printf("\n");
2520: fprintf(ficlog,"\n");
2521: }
2522: */
2523:
2524: free_matrix(a,1,npar,1,npar);
2525: free_matrix(y,1,npar,1,npar);
2526: free_vector(x,1,npar);
2527: free_ivector(indx,1,npar);
2528: free_matrix(hess,1,npar,1,npar);
2529:
2530:
2531: }
2532:
2533: /*************** hessian matrix ****************/
2534: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2535: {
2536: int i;
2537: int l=1, lmax=20;
2538: double k1,k2;
2539: double p2[MAXPARM+1]; /* identical to x */
2540: double res;
2541: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2542: double fx;
2543: int k=0,kmax=10;
2544: double l1;
2545:
2546: fx=func(x);
2547: for (i=1;i<=npar;i++) p2[i]=x[i];
2548: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2549: l1=pow(10,l);
2550: delts=delt;
2551: for(k=1 ; k <kmax; k=k+1){
2552: delt = delta*(l1*k);
2553: p2[theta]=x[theta] +delt;
2554: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2555: p2[theta]=x[theta]-delt;
2556: k2=func(p2)-fx;
2557: /*res= (k1-2.0*fx+k2)/delt/delt; */
2558: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2559:
2560: #ifdef DEBUGHESS
2561: 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);
2562: 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);
2563: #endif
2564: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2565: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2566: k=kmax;
2567: }
2568: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2569: k=kmax; l=lmax*10;
2570: }
2571: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2572: delts=delt;
2573: }
2574: }
2575: }
2576: delti[theta]=delts;
2577: return res;
2578:
2579: }
2580:
2581: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2582: {
2583: int i;
2584: int l=1, lmax=20;
2585: double k1,k2,k3,k4,res,fx;
2586: double p2[MAXPARM+1];
2587: int k;
2588:
2589: fx=func(x);
2590: for (k=1; k<=2; k++) {
2591: for (i=1;i<=npar;i++) p2[i]=x[i];
2592: p2[thetai]=x[thetai]+delti[thetai]/k;
2593: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2594: k1=func(p2)-fx;
2595:
2596: p2[thetai]=x[thetai]+delti[thetai]/k;
2597: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2598: k2=func(p2)-fx;
2599:
2600: p2[thetai]=x[thetai]-delti[thetai]/k;
2601: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2602: k3=func(p2)-fx;
2603:
2604: p2[thetai]=x[thetai]-delti[thetai]/k;
2605: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2606: k4=func(p2)-fx;
2607: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2608: #ifdef DEBUG
2609: 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);
2610: 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);
2611: #endif
2612: }
2613: return res;
2614: }
2615:
2616: /************** Inverse of matrix **************/
2617: void ludcmp(double **a, int n, int *indx, double *d)
2618: {
2619: int i,imax,j,k;
2620: double big,dum,sum,temp;
2621: double *vv;
2622:
2623: vv=vector(1,n);
2624: *d=1.0;
2625: for (i=1;i<=n;i++) {
2626: big=0.0;
2627: for (j=1;j<=n;j++)
2628: if ((temp=fabs(a[i][j])) > big) big=temp;
2629: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2630: vv[i]=1.0/big;
2631: }
2632: for (j=1;j<=n;j++) {
2633: for (i=1;i<j;i++) {
2634: sum=a[i][j];
2635: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2636: a[i][j]=sum;
2637: }
2638: big=0.0;
2639: for (i=j;i<=n;i++) {
2640: sum=a[i][j];
2641: for (k=1;k<j;k++)
2642: sum -= a[i][k]*a[k][j];
2643: a[i][j]=sum;
2644: if ( (dum=vv[i]*fabs(sum)) >= big) {
2645: big=dum;
2646: imax=i;
2647: }
2648: }
2649: if (j != imax) {
2650: for (k=1;k<=n;k++) {
2651: dum=a[imax][k];
2652: a[imax][k]=a[j][k];
2653: a[j][k]=dum;
2654: }
2655: *d = -(*d);
2656: vv[imax]=vv[j];
2657: }
2658: indx[j]=imax;
2659: if (a[j][j] == 0.0) a[j][j]=TINY;
2660: if (j != n) {
2661: dum=1.0/(a[j][j]);
2662: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2663: }
2664: }
2665: free_vector(vv,1,n); /* Doesn't work */
2666: ;
2667: }
2668:
2669: void lubksb(double **a, int n, int *indx, double b[])
2670: {
2671: int i,ii=0,ip,j;
2672: double sum;
2673:
2674: for (i=1;i<=n;i++) {
2675: ip=indx[i];
2676: sum=b[ip];
2677: b[ip]=b[i];
2678: if (ii)
2679: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2680: else if (sum) ii=i;
2681: b[i]=sum;
2682: }
2683: for (i=n;i>=1;i--) {
2684: sum=b[i];
2685: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2686: b[i]=sum/a[i][i];
2687: }
2688: }
2689:
2690: void pstamp(FILE *fichier)
2691: {
2692: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2693: }
2694:
2695: /************ Frequencies ********************/
2696: 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[])
2697: { /* Some frequencies */
2698:
2699: int i, m, jk, j1, bool, z1,j;
2700: int first;
2701: double ***freq; /* Frequencies */
2702: double *pp, **prop;
2703: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2704: char fileresp[FILENAMELENGTH];
2705:
2706: pp=vector(1,nlstate);
2707: prop=matrix(1,nlstate,iagemin,iagemax+3);
2708: strcpy(fileresp,"p");
2709: strcat(fileresp,fileres);
2710: if((ficresp=fopen(fileresp,"w"))==NULL) {
2711: printf("Problem with prevalence resultfile: %s\n", fileresp);
2712: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2713: exit(0);
2714: }
2715: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2716: j1=0;
2717:
2718: j=cptcoveff;
2719: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2720:
2721: first=1;
2722:
2723: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2724: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2725: /* j1++; */
2726: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2727: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2728: scanf("%d", i);*/
2729: for (i=-5; i<=nlstate+ndeath; i++)
2730: for (jk=-5; jk<=nlstate+ndeath; jk++)
2731: for(m=iagemin; m <= iagemax+3; m++)
2732: freq[i][jk][m]=0;
2733:
2734: for (i=1; i<=nlstate; i++)
2735: for(m=iagemin; m <= iagemax+3; m++)
2736: prop[i][m]=0;
2737:
2738: dateintsum=0;
2739: k2cpt=0;
2740: for (i=1; i<=imx; i++) {
2741: bool=1;
2742: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2743: for (z1=1; z1<=cptcoveff; z1++)
2744: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2745: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2746: bool=0;
2747: /* 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",
2748: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2749: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2750: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2751: }
2752: }
2753:
2754: if (bool==1){
2755: for(m=firstpass; m<=lastpass; m++){
2756: k2=anint[m][i]+(mint[m][i]/12.);
2757: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2758: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2759: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2760: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2761: if (m<lastpass) {
2762: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2763: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2764: }
2765:
2766: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2767: dateintsum=dateintsum+k2;
2768: k2cpt++;
2769: }
2770: /*}*/
2771: }
2772: }
2773: } /* end i */
2774:
2775: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2776: pstamp(ficresp);
2777: if (cptcovn>0) {
2778: fprintf(ficresp, "\n#********** Variable ");
2779: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2780: fprintf(ficresp, "**********\n#");
2781: fprintf(ficlog, "\n#********** Variable ");
2782: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2783: fprintf(ficlog, "**********\n#");
2784: }
2785: for(i=1; i<=nlstate;i++)
2786: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2787: fprintf(ficresp, "\n");
2788:
2789: for(i=iagemin; i <= iagemax+3; i++){
2790: if(i==iagemax+3){
2791: fprintf(ficlog,"Total");
2792: }else{
2793: if(first==1){
2794: first=0;
2795: printf("See log file for details...\n");
2796: }
2797: fprintf(ficlog,"Age %d", i);
2798: }
2799: for(jk=1; jk <=nlstate ; jk++){
2800: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2801: pp[jk] += freq[jk][m][i];
2802: }
2803: for(jk=1; jk <=nlstate ; jk++){
2804: for(m=-1, pos=0; m <=0 ; m++)
2805: pos += freq[jk][m][i];
2806: if(pp[jk]>=1.e-10){
2807: if(first==1){
2808: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2809: }
2810: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2811: }else{
2812: if(first==1)
2813: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2814: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2815: }
2816: }
2817:
2818: for(jk=1; jk <=nlstate ; jk++){
2819: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2820: pp[jk] += freq[jk][m][i];
2821: }
2822: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2823: pos += pp[jk];
2824: posprop += prop[jk][i];
2825: }
2826: for(jk=1; jk <=nlstate ; jk++){
2827: if(pos>=1.e-5){
2828: if(first==1)
2829: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2830: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2831: }else{
2832: if(first==1)
2833: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2834: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2835: }
2836: if( i <= iagemax){
2837: if(pos>=1.e-5){
2838: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2839: /*probs[i][jk][j1]= pp[jk]/pos;*/
2840: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2841: }
2842: else
2843: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2844: }
2845: }
2846:
2847: for(jk=-1; jk <=nlstate+ndeath; jk++)
2848: for(m=-1; m <=nlstate+ndeath; m++)
2849: if(freq[jk][m][i] !=0 ) {
2850: if(first==1)
2851: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2852: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2853: }
2854: if(i <= iagemax)
2855: fprintf(ficresp,"\n");
2856: if(first==1)
2857: printf("Others in log...\n");
2858: fprintf(ficlog,"\n");
2859: }
2860: /*}*/
2861: }
2862: dateintmean=dateintsum/k2cpt;
2863:
2864: fclose(ficresp);
2865: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2866: free_vector(pp,1,nlstate);
2867: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2868: /* End of Freq */
2869: }
2870:
2871: /************ Prevalence ********************/
2872: 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)
2873: {
2874: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2875: in each health status at the date of interview (if between dateprev1 and dateprev2).
2876: We still use firstpass and lastpass as another selection.
2877: */
2878:
2879: int i, m, jk, j1, bool, z1,j;
2880:
2881: double **prop;
2882: double posprop;
2883: double y2; /* in fractional years */
2884: int iagemin, iagemax;
2885: int first; /** to stop verbosity which is redirected to log file */
2886:
2887: iagemin= (int) agemin;
2888: iagemax= (int) agemax;
2889: /*pp=vector(1,nlstate);*/
2890: prop=matrix(1,nlstate,iagemin,iagemax+3);
2891: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2892: j1=0;
2893:
2894: /*j=cptcoveff;*/
2895: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2896:
2897: first=1;
2898: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2899: /*for(i1=1; i1<=ncodemax[k1];i1++){
2900: j1++;*/
2901:
2902: for (i=1; i<=nlstate; i++)
2903: for(m=iagemin; m <= iagemax+3; m++)
2904: prop[i][m]=0.0;
2905:
2906: for (i=1; i<=imx; i++) { /* Each individual */
2907: bool=1;
2908: if (cptcovn>0) {
2909: for (z1=1; z1<=cptcoveff; z1++)
2910: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2911: bool=0;
2912: }
2913: if (bool==1) {
2914: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2915: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2916: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2917: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2918: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2919: 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);
2920: if (s[m][i]>0 && s[m][i]<=nlstate) {
2921: /*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]]);*/
2922: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2923: prop[s[m][i]][iagemax+3] += weight[i];
2924: }
2925: }
2926: } /* end selection of waves */
2927: }
2928: }
2929: for(i=iagemin; i <= iagemax+3; i++){
2930: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2931: posprop += prop[jk][i];
2932: }
2933:
2934: for(jk=1; jk <=nlstate ; jk++){
2935: if( i <= iagemax){
2936: if(posprop>=1.e-5){
2937: probs[i][jk][j1]= prop[jk][i]/posprop;
2938: } else{
2939: if(first==1){
2940: first=0;
2941: 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]);
2942: }
2943: }
2944: }
2945: }/* end jk */
2946: }/* end i */
2947: /*} *//* end i1 */
2948: } /* end j1 */
2949:
2950: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2951: /*free_vector(pp,1,nlstate);*/
2952: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2953: } /* End of prevalence */
2954:
2955: /************* Waves Concatenation ***************/
2956:
2957: 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)
2958: {
2959: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2960: Death is a valid wave (if date is known).
2961: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2962: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2963: and mw[mi+1][i]. dh depends on stepm.
2964: */
2965:
2966: int i, mi, m;
2967: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2968: double sum=0., jmean=0.;*/
2969: int first;
2970: int j, k=0,jk, ju, jl;
2971: double sum=0.;
2972: first=0;
2973: jmin=100000;
2974: jmax=-1;
2975: jmean=0.;
2976: for(i=1; i<=imx; i++){
2977: mi=0;
2978: m=firstpass;
2979: while(s[m][i] <= nlstate){
2980: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2981: mw[++mi][i]=m;
2982: if(m >=lastpass)
2983: break;
2984: else
2985: m++;
2986: }/* end while */
2987: if (s[m][i] > nlstate){
2988: mi++; /* Death is another wave */
2989: /* if(mi==0) never been interviewed correctly before death */
2990: /* Only death is a correct wave */
2991: mw[mi][i]=m;
2992: }
2993:
2994: wav[i]=mi;
2995: if(mi==0){
2996: nbwarn++;
2997: if(first==0){
2998: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2999: first=1;
3000: }
3001: if(first==1){
3002: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3003: }
3004: } /* end mi==0 */
3005: } /* End individuals */
3006:
3007: for(i=1; i<=imx; i++){
3008: for(mi=1; mi<wav[i];mi++){
3009: if (stepm <=0)
3010: dh[mi][i]=1;
3011: else{
3012: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3013: if (agedc[i] < 2*AGESUP) {
3014: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3015: if(j==0) j=1; /* Survives at least one month after exam */
3016: else if(j<0){
3017: nberr++;
3018: 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]);
3019: j=1; /* Temporary Dangerous patch */
3020: 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);
3021: 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]);
3022: 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);
3023: }
3024: k=k+1;
3025: if (j >= jmax){
3026: jmax=j;
3027: ijmax=i;
3028: }
3029: if (j <= jmin){
3030: jmin=j;
3031: ijmin=i;
3032: }
3033: sum=sum+j;
3034: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3035: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3036: }
3037: }
3038: else{
3039: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3040: /* 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]); */
3041:
3042: k=k+1;
3043: if (j >= jmax) {
3044: jmax=j;
3045: ijmax=i;
3046: }
3047: else if (j <= jmin){
3048: jmin=j;
3049: ijmin=i;
3050: }
3051: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3052: /*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]);*/
3053: if(j<0){
3054: nberr++;
3055: 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]);
3056: 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]);
3057: }
3058: sum=sum+j;
3059: }
3060: jk= j/stepm;
3061: jl= j -jk*stepm;
3062: ju= j -(jk+1)*stepm;
3063: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3064: if(jl==0){
3065: dh[mi][i]=jk;
3066: bh[mi][i]=0;
3067: }else{ /* We want a negative bias in order to only have interpolation ie
3068: * to avoid the price of an extra matrix product in likelihood */
3069: dh[mi][i]=jk+1;
3070: bh[mi][i]=ju;
3071: }
3072: }else{
3073: if(jl <= -ju){
3074: dh[mi][i]=jk;
3075: bh[mi][i]=jl; /* bias is positive if real duration
3076: * is higher than the multiple of stepm and negative otherwise.
3077: */
3078: }
3079: else{
3080: dh[mi][i]=jk+1;
3081: bh[mi][i]=ju;
3082: }
3083: if(dh[mi][i]==0){
3084: dh[mi][i]=1; /* At least one step */
3085: bh[mi][i]=ju; /* At least one step */
3086: /* 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);*/
3087: }
3088: } /* end if mle */
3089: }
3090: } /* end wave */
3091: }
3092: jmean=sum/k;
3093: 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);
3094: 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);
3095: }
3096:
3097: /*********** Tricode ****************************/
3098: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3099: {
3100: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3101: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3102: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3103: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3104: * nbcode[Tvar[j]][1]=
3105: */
3106:
3107: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3108: int modmaxcovj=0; /* Modality max of covariates j */
3109: int cptcode=0; /* Modality max of covariates j */
3110: int modmincovj=0; /* Modality min of covariates j */
3111:
3112:
3113: cptcoveff=0;
3114:
3115: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3116: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3117:
3118: /* Loop on covariates without age and products */
3119: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3120: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3121: modality of this covariate Vj*/
3122: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3123: * If product of Vn*Vm, still boolean *:
3124: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3125: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3126: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3127: modality of the nth covariate of individual i. */
3128: if (ij > modmaxcovj)
3129: modmaxcovj=ij;
3130: else if (ij < modmincovj)
3131: modmincovj=ij;
3132: if ((ij < -1) && (ij > NCOVMAX)){
3133: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3134: exit(1);
3135: }else
3136: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3137: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3138: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3139: /* getting the maximum value of the modality of the covariate
3140: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3141: female is 1, then modmaxcovj=1.*/
3142: }
3143: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3144: cptcode=modmaxcovj;
3145: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3146: /*for (i=0; i<=cptcode; i++) {*/
3147: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3148: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3149: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3150: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3151: }
3152: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3153: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3154: } /* Ndum[-1] number of undefined modalities */
3155:
3156: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3157: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3158: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3159: modmincovj=3; modmaxcovj = 7;
3160: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3161: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3162: defining two dummy variables: variables V1_1 and V1_2.
3163: nbcode[Tvar[j]][ij]=k;
3164: nbcode[Tvar[j]][1]=0;
3165: nbcode[Tvar[j]][2]=1;
3166: nbcode[Tvar[j]][3]=2;
3167: */
3168: ij=1; /* ij is similar to i but can jumps over null modalities */
3169: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3170: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3171: /*recode from 0 */
3172: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3173: nbcode[Tvar[j]][ij]=k; /* stores the modality k in an array nbcode.
3174: k is a modality. If we have model=V1+V1*sex
3175: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3176: ij++;
3177: }
3178: if (ij > ncodemax[j]) break;
3179: } /* end of loop on */
3180: } /* end of loop on modality */
3181: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3182:
3183: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3184:
3185: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3186: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3187: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3188: Ndum[ij]++;
3189: }
3190:
3191: ij=1;
3192: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3193: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3194: if((Ndum[i]!=0) && (i<=ncovcol)){
3195: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3196: Tvaraff[ij]=i; /*For printing (unclear) */
3197: ij++;
3198: }else
3199: Tvaraff[ij]=0;
3200: }
3201: ij--;
3202: cptcoveff=ij; /*Number of total covariates*/
3203:
3204: }
3205:
3206:
3207: /*********** Health Expectancies ****************/
3208:
3209: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3210:
3211: {
3212: /* Health expectancies, no variances */
3213: int i, j, nhstepm, hstepm, h, nstepm;
3214: int nhstepma, nstepma; /* Decreasing with age */
3215: double age, agelim, hf;
3216: double ***p3mat;
3217: double eip;
3218:
3219: pstamp(ficreseij);
3220: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3221: fprintf(ficreseij,"# Age");
3222: for(i=1; i<=nlstate;i++){
3223: for(j=1; j<=nlstate;j++){
3224: fprintf(ficreseij," e%1d%1d ",i,j);
3225: }
3226: fprintf(ficreseij," e%1d. ",i);
3227: }
3228: fprintf(ficreseij,"\n");
3229:
3230:
3231: if(estepm < stepm){
3232: printf ("Problem %d lower than %d\n",estepm, stepm);
3233: }
3234: else hstepm=estepm;
3235: /* We compute the life expectancy from trapezoids spaced every estepm months
3236: * This is mainly to measure the difference between two models: for example
3237: * if stepm=24 months pijx are given only every 2 years and by summing them
3238: * we are calculating an estimate of the Life Expectancy assuming a linear
3239: * progression in between and thus overestimating or underestimating according
3240: * to the curvature of the survival function. If, for the same date, we
3241: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3242: * to compare the new estimate of Life expectancy with the same linear
3243: * hypothesis. A more precise result, taking into account a more precise
3244: * curvature will be obtained if estepm is as small as stepm. */
3245:
3246: /* For example we decided to compute the life expectancy with the smallest unit */
3247: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3248: nhstepm is the number of hstepm from age to agelim
3249: nstepm is the number of stepm from age to agelin.
3250: Look at hpijx to understand the reason of that which relies in memory size
3251: and note for a fixed period like estepm months */
3252: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3253: survival function given by stepm (the optimization length). Unfortunately it
3254: means that if the survival funtion is printed only each two years of age and if
3255: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3256: results. So we changed our mind and took the option of the best precision.
3257: */
3258: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3259:
3260: agelim=AGESUP;
3261: /* If stepm=6 months */
3262: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3263: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3264:
3265: /* nhstepm age range expressed in number of stepm */
3266: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3267: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3268: /* if (stepm >= YEARM) hstepm=1;*/
3269: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3270: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3271:
3272: for (age=bage; age<=fage; age ++){
3273: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3274: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3275: /* if (stepm >= YEARM) hstepm=1;*/
3276: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3277:
3278: /* If stepm=6 months */
3279: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3280: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3281:
3282: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3283:
3284: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3285:
3286: printf("%d|",(int)age);fflush(stdout);
3287: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3288:
3289: /* Computing expectancies */
3290: for(i=1; i<=nlstate;i++)
3291: for(j=1; j<=nlstate;j++)
3292: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3293: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3294:
3295: /* 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]);*/
3296:
3297: }
3298:
3299: fprintf(ficreseij,"%3.0f",age );
3300: for(i=1; i<=nlstate;i++){
3301: eip=0;
3302: for(j=1; j<=nlstate;j++){
3303: eip +=eij[i][j][(int)age];
3304: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3305: }
3306: fprintf(ficreseij,"%9.4f", eip );
3307: }
3308: fprintf(ficreseij,"\n");
3309:
3310: }
3311: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3312: printf("\n");
3313: fprintf(ficlog,"\n");
3314:
3315: }
3316:
3317: 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[] )
3318:
3319: {
3320: /* Covariances of health expectancies eij and of total life expectancies according
3321: to initial status i, ei. .
3322: */
3323: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3324: int nhstepma, nstepma; /* Decreasing with age */
3325: double age, agelim, hf;
3326: double ***p3matp, ***p3matm, ***varhe;
3327: double **dnewm,**doldm;
3328: double *xp, *xm;
3329: double **gp, **gm;
3330: double ***gradg, ***trgradg;
3331: int theta;
3332:
3333: double eip, vip;
3334:
3335: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3336: xp=vector(1,npar);
3337: xm=vector(1,npar);
3338: dnewm=matrix(1,nlstate*nlstate,1,npar);
3339: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3340:
3341: pstamp(ficresstdeij);
3342: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3343: fprintf(ficresstdeij,"# Age");
3344: for(i=1; i<=nlstate;i++){
3345: for(j=1; j<=nlstate;j++)
3346: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3347: fprintf(ficresstdeij," e%1d. ",i);
3348: }
3349: fprintf(ficresstdeij,"\n");
3350:
3351: pstamp(ficrescveij);
3352: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3353: fprintf(ficrescveij,"# Age");
3354: for(i=1; i<=nlstate;i++)
3355: for(j=1; j<=nlstate;j++){
3356: cptj= (j-1)*nlstate+i;
3357: for(i2=1; i2<=nlstate;i2++)
3358: for(j2=1; j2<=nlstate;j2++){
3359: cptj2= (j2-1)*nlstate+i2;
3360: if(cptj2 <= cptj)
3361: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3362: }
3363: }
3364: fprintf(ficrescveij,"\n");
3365:
3366: if(estepm < stepm){
3367: printf ("Problem %d lower than %d\n",estepm, stepm);
3368: }
3369: else hstepm=estepm;
3370: /* We compute the life expectancy from trapezoids spaced every estepm months
3371: * This is mainly to measure the difference between two models: for example
3372: * if stepm=24 months pijx are given only every 2 years and by summing them
3373: * we are calculating an estimate of the Life Expectancy assuming a linear
3374: * progression in between and thus overestimating or underestimating according
3375: * to the curvature of the survival function. If, for the same date, we
3376: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3377: * to compare the new estimate of Life expectancy with the same linear
3378: * hypothesis. A more precise result, taking into account a more precise
3379: * curvature will be obtained if estepm is as small as stepm. */
3380:
3381: /* For example we decided to compute the life expectancy with the smallest unit */
3382: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3383: nhstepm is the number of hstepm from age to agelim
3384: nstepm is the number of stepm from age to agelin.
3385: Look at hpijx to understand the reason of that which relies in memory size
3386: and note for a fixed period like estepm months */
3387: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3388: survival function given by stepm (the optimization length). Unfortunately it
3389: means that if the survival funtion is printed only each two years of age and if
3390: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3391: results. So we changed our mind and took the option of the best precision.
3392: */
3393: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3394:
3395: /* If stepm=6 months */
3396: /* nhstepm age range expressed in number of stepm */
3397: agelim=AGESUP;
3398: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3399: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3400: /* if (stepm >= YEARM) hstepm=1;*/
3401: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3402:
3403: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3404: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3405: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3406: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3407: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3408: gm=matrix(0,nhstepm,1,nlstate*nlstate);
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: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3421:
3422: /* Computing Variances of health expectancies */
3423: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3424: decrease memory allocation */
3425: for(theta=1; theta <=npar; theta++){
3426: for(i=1; i<=npar; i++){
3427: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3428: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3429: }
3430: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3431: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3432:
3433: for(j=1; j<= nlstate; j++){
3434: for(i=1; i<=nlstate; i++){
3435: for(h=0; h<=nhstepm-1; h++){
3436: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3437: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3438: }
3439: }
3440: }
3441:
3442: for(ij=1; ij<= nlstate*nlstate; ij++)
3443: for(h=0; h<=nhstepm-1; h++){
3444: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3445: }
3446: }/* End theta */
3447:
3448:
3449: for(h=0; h<=nhstepm-1; h++)
3450: for(j=1; j<=nlstate*nlstate;j++)
3451: for(theta=1; theta <=npar; theta++)
3452: trgradg[h][j][theta]=gradg[h][theta][j];
3453:
3454:
3455: for(ij=1;ij<=nlstate*nlstate;ij++)
3456: for(ji=1;ji<=nlstate*nlstate;ji++)
3457: varhe[ij][ji][(int)age] =0.;
3458:
3459: printf("%d|",(int)age);fflush(stdout);
3460: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3461: for(h=0;h<=nhstepm-1;h++){
3462: for(k=0;k<=nhstepm-1;k++){
3463: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3464: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3465: for(ij=1;ij<=nlstate*nlstate;ij++)
3466: for(ji=1;ji<=nlstate*nlstate;ji++)
3467: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3468: }
3469: }
3470:
3471: /* Computing expectancies */
3472: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3473: for(i=1; i<=nlstate;i++)
3474: for(j=1; j<=nlstate;j++)
3475: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3476: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3477:
3478: /* 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]);*/
3479:
3480: }
3481:
3482: fprintf(ficresstdeij,"%3.0f",age );
3483: for(i=1; i<=nlstate;i++){
3484: eip=0.;
3485: vip=0.;
3486: for(j=1; j<=nlstate;j++){
3487: eip += eij[i][j][(int)age];
3488: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3489: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3490: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3491: }
3492: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3493: }
3494: fprintf(ficresstdeij,"\n");
3495:
3496: fprintf(ficrescveij,"%3.0f",age );
3497: for(i=1; i<=nlstate;i++)
3498: for(j=1; j<=nlstate;j++){
3499: cptj= (j-1)*nlstate+i;
3500: for(i2=1; i2<=nlstate;i2++)
3501: for(j2=1; j2<=nlstate;j2++){
3502: cptj2= (j2-1)*nlstate+i2;
3503: if(cptj2 <= cptj)
3504: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3505: }
3506: }
3507: fprintf(ficrescveij,"\n");
3508:
3509: }
3510: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3511: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3512: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3513: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3514: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3515: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3516: printf("\n");
3517: fprintf(ficlog,"\n");
3518:
3519: free_vector(xm,1,npar);
3520: free_vector(xp,1,npar);
3521: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3522: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3523: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3524: }
3525:
3526: /************ Variance ******************/
3527: 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[])
3528: {
3529: /* Variance of health expectancies */
3530: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3531: /* double **newm;*/
3532: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3533:
3534: int movingaverage();
3535: double **dnewm,**doldm;
3536: double **dnewmp,**doldmp;
3537: int i, j, nhstepm, hstepm, h, nstepm ;
3538: int k;
3539: double *xp;
3540: double **gp, **gm; /* for var eij */
3541: double ***gradg, ***trgradg; /*for var eij */
3542: double **gradgp, **trgradgp; /* for var p point j */
3543: double *gpp, *gmp; /* for var p point j */
3544: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3545: double ***p3mat;
3546: double age,agelim, hf;
3547: double ***mobaverage;
3548: int theta;
3549: char digit[4];
3550: char digitp[25];
3551:
3552: char fileresprobmorprev[FILENAMELENGTH];
3553:
3554: if(popbased==1){
3555: if(mobilav!=0)
3556: strcpy(digitp,"-populbased-mobilav-");
3557: else strcpy(digitp,"-populbased-nomobil-");
3558: }
3559: else
3560: strcpy(digitp,"-stablbased-");
3561:
3562: if (mobilav!=0) {
3563: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3564: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3565: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3566: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3567: }
3568: }
3569:
3570: strcpy(fileresprobmorprev,"prmorprev");
3571: sprintf(digit,"%-d",ij);
3572: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3573: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3574: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3575: strcat(fileresprobmorprev,fileres);
3576: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3577: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3578: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3579: }
3580: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3581:
3582: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3583: pstamp(ficresprobmorprev);
3584: 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);
3585: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3586: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3587: fprintf(ficresprobmorprev," p.%-d SE",j);
3588: for(i=1; i<=nlstate;i++)
3589: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3590: }
3591: fprintf(ficresprobmorprev,"\n");
3592: fprintf(ficgp,"\n# Routine varevsij");
3593: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3594: 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");
3595: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3596: /* } */
3597: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3598: pstamp(ficresvij);
3599: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3600: if(popbased==1)
3601: 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);
3602: else
3603: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3604: fprintf(ficresvij,"# Age");
3605: for(i=1; i<=nlstate;i++)
3606: for(j=1; j<=nlstate;j++)
3607: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3608: fprintf(ficresvij,"\n");
3609:
3610: xp=vector(1,npar);
3611: dnewm=matrix(1,nlstate,1,npar);
3612: doldm=matrix(1,nlstate,1,nlstate);
3613: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3614: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3615:
3616: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3617: gpp=vector(nlstate+1,nlstate+ndeath);
3618: gmp=vector(nlstate+1,nlstate+ndeath);
3619: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3620:
3621: if(estepm < stepm){
3622: printf ("Problem %d lower than %d\n",estepm, stepm);
3623: }
3624: else hstepm=estepm;
3625: /* For example we decided to compute the life expectancy with the smallest unit */
3626: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3627: nhstepm is the number of hstepm from age to agelim
3628: nstepm is the number of stepm from age to agelin.
3629: Look at function hpijx to understand why (it is linked to memory size questions) */
3630: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3631: survival function given by stepm (the optimization length). Unfortunately it
3632: means that if the survival funtion is printed every two years of age and if
3633: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3634: results. So we changed our mind and took the option of the best precision.
3635: */
3636: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3637: agelim = AGESUP;
3638: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3639: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3640: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3641: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3642: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3643: gp=matrix(0,nhstepm,1,nlstate);
3644: gm=matrix(0,nhstepm,1,nlstate);
3645:
3646:
3647: for(theta=1; theta <=npar; theta++){
3648: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3649: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3650: }
3651: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3652: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3653:
3654: if (popbased==1) {
3655: if(mobilav ==0){
3656: for(i=1; i<=nlstate;i++)
3657: prlim[i][i]=probs[(int)age][i][ij];
3658: }else{ /* mobilav */
3659: for(i=1; i<=nlstate;i++)
3660: prlim[i][i]=mobaverage[(int)age][i][ij];
3661: }
3662: }
3663:
3664: for(j=1; j<= nlstate; j++){
3665: for(h=0; h<=nhstepm; h++){
3666: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3667: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3668: }
3669: }
3670: /* This for computing probability of death (h=1 means
3671: computed over hstepm matrices product = hstepm*stepm months)
3672: as a weighted average of prlim.
3673: */
3674: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3675: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3676: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3677: }
3678: /* end probability of death */
3679:
3680: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3681: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3682: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3683: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3684:
3685: if (popbased==1) {
3686: if(mobilav ==0){
3687: for(i=1; i<=nlstate;i++)
3688: prlim[i][i]=probs[(int)age][i][ij];
3689: }else{ /* mobilav */
3690: for(i=1; i<=nlstate;i++)
3691: prlim[i][i]=mobaverage[(int)age][i][ij];
3692: }
3693: }
3694:
3695: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3696: for(h=0; h<=nhstepm; h++){
3697: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3698: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3699: }
3700: }
3701: /* This for computing probability of death (h=1 means
3702: computed over hstepm matrices product = hstepm*stepm months)
3703: as a weighted average of prlim.
3704: */
3705: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3706: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3707: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3708: }
3709: /* end probability of death */
3710:
3711: for(j=1; j<= nlstate; j++) /* vareij */
3712: for(h=0; h<=nhstepm; h++){
3713: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3714: }
3715:
3716: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3717: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3718: }
3719:
3720: } /* End theta */
3721:
3722: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3723:
3724: for(h=0; h<=nhstepm; h++) /* veij */
3725: for(j=1; j<=nlstate;j++)
3726: for(theta=1; theta <=npar; theta++)
3727: trgradg[h][j][theta]=gradg[h][theta][j];
3728:
3729: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3730: for(theta=1; theta <=npar; theta++)
3731: trgradgp[j][theta]=gradgp[theta][j];
3732:
3733:
3734: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3735: for(i=1;i<=nlstate;i++)
3736: for(j=1;j<=nlstate;j++)
3737: vareij[i][j][(int)age] =0.;
3738:
3739: for(h=0;h<=nhstepm;h++){
3740: for(k=0;k<=nhstepm;k++){
3741: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3742: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3743: for(i=1;i<=nlstate;i++)
3744: for(j=1;j<=nlstate;j++)
3745: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3746: }
3747: }
3748:
3749: /* pptj */
3750: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3751: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3752: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3753: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3754: varppt[j][i]=doldmp[j][i];
3755: /* end ppptj */
3756: /* x centered again */
3757: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3758: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3759:
3760: if (popbased==1) {
3761: if(mobilav ==0){
3762: for(i=1; i<=nlstate;i++)
3763: prlim[i][i]=probs[(int)age][i][ij];
3764: }else{ /* mobilav */
3765: for(i=1; i<=nlstate;i++)
3766: prlim[i][i]=mobaverage[(int)age][i][ij];
3767: }
3768: }
3769:
3770: /* This for computing probability of death (h=1 means
3771: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3772: as a weighted average of prlim.
3773: */
3774: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3775: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3776: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3777: }
3778: /* end probability of death */
3779:
3780: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3781: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3782: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3783: for(i=1; i<=nlstate;i++){
3784: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3785: }
3786: }
3787: fprintf(ficresprobmorprev,"\n");
3788:
3789: fprintf(ficresvij,"%.0f ",age );
3790: for(i=1; i<=nlstate;i++)
3791: for(j=1; j<=nlstate;j++){
3792: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3793: }
3794: fprintf(ficresvij,"\n");
3795: free_matrix(gp,0,nhstepm,1,nlstate);
3796: free_matrix(gm,0,nhstepm,1,nlstate);
3797: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3798: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3799: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3800: } /* End age */
3801: free_vector(gpp,nlstate+1,nlstate+ndeath);
3802: free_vector(gmp,nlstate+1,nlstate+ndeath);
3803: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3804: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3805: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3806: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3807: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3808: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3809: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3810: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3811: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3812: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3813: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3814: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3815: 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);
3816: /* 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);
3817: */
3818: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3819: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3820:
3821: free_vector(xp,1,npar);
3822: free_matrix(doldm,1,nlstate,1,nlstate);
3823: free_matrix(dnewm,1,nlstate,1,npar);
3824: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3825: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3826: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3827: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3828: fclose(ficresprobmorprev);
3829: fflush(ficgp);
3830: fflush(fichtm);
3831: } /* end varevsij */
3832:
3833: /************ Variance of prevlim ******************/
3834: 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[])
3835: {
3836: /* Variance of prevalence limit */
3837: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3838:
3839: double **dnewm,**doldm;
3840: int i, j, nhstepm, hstepm;
3841: double *xp;
3842: double *gp, *gm;
3843: double **gradg, **trgradg;
3844: double age,agelim;
3845: int theta;
3846:
3847: pstamp(ficresvpl);
3848: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3849: fprintf(ficresvpl,"# Age");
3850: for(i=1; i<=nlstate;i++)
3851: fprintf(ficresvpl," %1d-%1d",i,i);
3852: fprintf(ficresvpl,"\n");
3853:
3854: xp=vector(1,npar);
3855: dnewm=matrix(1,nlstate,1,npar);
3856: doldm=matrix(1,nlstate,1,nlstate);
3857:
3858: hstepm=1*YEARM; /* Every year of age */
3859: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3860: agelim = AGESUP;
3861: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3862: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3863: if (stepm >= YEARM) hstepm=1;
3864: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3865: gradg=matrix(1,npar,1,nlstate);
3866: gp=vector(1,nlstate);
3867: gm=vector(1,nlstate);
3868:
3869: for(theta=1; theta <=npar; theta++){
3870: for(i=1; i<=npar; i++){ /* Computes gradient */
3871: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3872: }
3873: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3874: for(i=1;i<=nlstate;i++)
3875: gp[i] = prlim[i][i];
3876:
3877: for(i=1; i<=npar; i++) /* Computes gradient */
3878: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3879: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3880: for(i=1;i<=nlstate;i++)
3881: gm[i] = prlim[i][i];
3882:
3883: for(i=1;i<=nlstate;i++)
3884: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3885: } /* End theta */
3886:
3887: trgradg =matrix(1,nlstate,1,npar);
3888:
3889: for(j=1; j<=nlstate;j++)
3890: for(theta=1; theta <=npar; theta++)
3891: trgradg[j][theta]=gradg[theta][j];
3892:
3893: for(i=1;i<=nlstate;i++)
3894: varpl[i][(int)age] =0.;
3895: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3896: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3897: for(i=1;i<=nlstate;i++)
3898: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3899:
3900: fprintf(ficresvpl,"%.0f ",age );
3901: for(i=1; i<=nlstate;i++)
3902: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3903: fprintf(ficresvpl,"\n");
3904: free_vector(gp,1,nlstate);
3905: free_vector(gm,1,nlstate);
3906: free_matrix(gradg,1,npar,1,nlstate);
3907: free_matrix(trgradg,1,nlstate,1,npar);
3908: } /* End age */
3909:
3910: free_vector(xp,1,npar);
3911: free_matrix(doldm,1,nlstate,1,npar);
3912: free_matrix(dnewm,1,nlstate,1,nlstate);
3913:
3914: }
3915:
3916: /************ Variance of one-step probabilities ******************/
3917: 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[])
3918: {
3919: int i, j=0, k1, l1, tj;
3920: int k2, l2, j1, z1;
3921: int k=0, l;
3922: int first=1, first1, first2;
3923: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3924: double **dnewm,**doldm;
3925: double *xp;
3926: double *gp, *gm;
3927: double **gradg, **trgradg;
3928: double **mu;
3929: double age, cov[NCOVMAX+1];
3930: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3931: int theta;
3932: char fileresprob[FILENAMELENGTH];
3933: char fileresprobcov[FILENAMELENGTH];
3934: char fileresprobcor[FILENAMELENGTH];
3935: double ***varpij;
3936:
3937: strcpy(fileresprob,"prob");
3938: strcat(fileresprob,fileres);
3939: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3940: printf("Problem with resultfile: %s\n", fileresprob);
3941: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3942: }
3943: strcpy(fileresprobcov,"probcov");
3944: strcat(fileresprobcov,fileres);
3945: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3946: printf("Problem with resultfile: %s\n", fileresprobcov);
3947: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3948: }
3949: strcpy(fileresprobcor,"probcor");
3950: strcat(fileresprobcor,fileres);
3951: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3952: printf("Problem with resultfile: %s\n", fileresprobcor);
3953: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3954: }
3955: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3956: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3957: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3958: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3959: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3960: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3961: pstamp(ficresprob);
3962: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3963: fprintf(ficresprob,"# Age");
3964: pstamp(ficresprobcov);
3965: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3966: fprintf(ficresprobcov,"# Age");
3967: pstamp(ficresprobcor);
3968: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3969: fprintf(ficresprobcor,"# Age");
3970:
3971:
3972: for(i=1; i<=nlstate;i++)
3973: for(j=1; j<=(nlstate+ndeath);j++){
3974: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3975: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3976: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3977: }
3978: /* fprintf(ficresprob,"\n");
3979: fprintf(ficresprobcov,"\n");
3980: fprintf(ficresprobcor,"\n");
3981: */
3982: xp=vector(1,npar);
3983: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3984: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3985: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3986: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3987: first=1;
3988: fprintf(ficgp,"\n# Routine varprob");
3989: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3990: fprintf(fichtm,"\n");
3991:
3992: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3993: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3994: file %s<br>\n",optionfilehtmcov);
3995: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3996: and drawn. It helps understanding how is the covariance between two incidences.\
3997: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3998: 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. \
3999: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4000: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4001: standard deviations wide on each axis. <br>\
4002: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4003: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4004: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4005:
4006: cov[1]=1;
4007: /* tj=cptcoveff; */
4008: tj = (int) pow(2,cptcoveff);
4009: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4010: j1=0;
4011: for(j1=1; j1<=tj;j1++){
4012: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4013: /*j1++;*/
4014: if (cptcovn>0) {
4015: fprintf(ficresprob, "\n#********** Variable ");
4016: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4017: fprintf(ficresprob, "**********\n#\n");
4018: fprintf(ficresprobcov, "\n#********** Variable ");
4019: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4020: fprintf(ficresprobcov, "**********\n#\n");
4021:
4022: fprintf(ficgp, "\n#********** Variable ");
4023: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4024: fprintf(ficgp, "**********\n#\n");
4025:
4026:
4027: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4028: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4029: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4030:
4031: fprintf(ficresprobcor, "\n#********** Variable ");
4032: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4033: fprintf(ficresprobcor, "**********\n#");
4034: }
4035:
4036: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4037: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4038: gp=vector(1,(nlstate)*(nlstate+ndeath));
4039: gm=vector(1,(nlstate)*(nlstate+ndeath));
4040: for (age=bage; age<=fage; age ++){
4041: cov[2]=age;
4042: for (k=1; k<=cptcovn;k++) {
4043: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
4044: * 1 1 1 1 1
4045: * 2 2 1 1 1
4046: * 3 1 2 1 1
4047: */
4048: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4049: }
4050: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4051: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
4052: for (k=1; k<=cptcovprod;k++)
4053: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
4054:
4055:
4056: for(theta=1; theta <=npar; theta++){
4057: for(i=1; i<=npar; i++)
4058: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4059:
4060: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4061:
4062: k=0;
4063: for(i=1; i<= (nlstate); i++){
4064: for(j=1; j<=(nlstate+ndeath);j++){
4065: k=k+1;
4066: gp[k]=pmmij[i][j];
4067: }
4068: }
4069:
4070: for(i=1; i<=npar; i++)
4071: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4072:
4073: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4074: k=0;
4075: for(i=1; i<=(nlstate); i++){
4076: for(j=1; j<=(nlstate+ndeath);j++){
4077: k=k+1;
4078: gm[k]=pmmij[i][j];
4079: }
4080: }
4081:
4082: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4083: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4084: }
4085:
4086: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4087: for(theta=1; theta <=npar; theta++)
4088: trgradg[j][theta]=gradg[theta][j];
4089:
4090: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4091: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4092:
4093: pmij(pmmij,cov,ncovmodel,x,nlstate);
4094:
4095: k=0;
4096: for(i=1; i<=(nlstate); i++){
4097: for(j=1; j<=(nlstate+ndeath);j++){
4098: k=k+1;
4099: mu[k][(int) age]=pmmij[i][j];
4100: }
4101: }
4102: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4103: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4104: varpij[i][j][(int)age] = doldm[i][j];
4105:
4106: /*printf("\n%d ",(int)age);
4107: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4108: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4109: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4110: }*/
4111:
4112: fprintf(ficresprob,"\n%d ",(int)age);
4113: fprintf(ficresprobcov,"\n%d ",(int)age);
4114: fprintf(ficresprobcor,"\n%d ",(int)age);
4115:
4116: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4117: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4118: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4119: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4120: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4121: }
4122: i=0;
4123: for (k=1; k<=(nlstate);k++){
4124: for (l=1; l<=(nlstate+ndeath);l++){
4125: i++;
4126: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4127: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4128: for (j=1; j<=i;j++){
4129: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4130: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4131: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4132: }
4133: }
4134: }/* end of loop for state */
4135: } /* end of loop for age */
4136: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4137: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4138: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4139: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4140:
4141: /* Confidence intervalle of pij */
4142: /*
4143: fprintf(ficgp,"\nunset parametric;unset label");
4144: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4145: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4146: 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);
4147: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4148: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4149: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4150: */
4151:
4152: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4153: first1=1;first2=2;
4154: for (k2=1; k2<=(nlstate);k2++){
4155: for (l2=1; l2<=(nlstate+ndeath);l2++){
4156: if(l2==k2) continue;
4157: j=(k2-1)*(nlstate+ndeath)+l2;
4158: for (k1=1; k1<=(nlstate);k1++){
4159: for (l1=1; l1<=(nlstate+ndeath);l1++){
4160: if(l1==k1) continue;
4161: i=(k1-1)*(nlstate+ndeath)+l1;
4162: if(i<=j) continue;
4163: for (age=bage; age<=fage; age ++){
4164: if ((int)age %5==0){
4165: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4166: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4167: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4168: mu1=mu[i][(int) age]/stepm*YEARM ;
4169: mu2=mu[j][(int) age]/stepm*YEARM;
4170: c12=cv12/sqrt(v1*v2);
4171: /* Computing eigen value of matrix of covariance */
4172: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4173: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4174: if ((lc2 <0) || (lc1 <0) ){
4175: if(first2==1){
4176: first1=0;
4177: 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);
4178: }
4179: 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);
4180: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4181: /* lc2=fabs(lc2); */
4182: }
4183:
4184: /* Eigen vectors */
4185: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4186: /*v21=sqrt(1.-v11*v11); *//* error */
4187: v21=(lc1-v1)/cv12*v11;
4188: v12=-v21;
4189: v22=v11;
4190: tnalp=v21/v11;
4191: if(first1==1){
4192: first1=0;
4193: 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);
4194: }
4195: 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);
4196: /*printf(fignu*/
4197: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4198: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4199: if(first==1){
4200: first=0;
4201: fprintf(ficgp,"\nset parametric;unset label");
4202: 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);
4203: fprintf(ficgp,"\nset ter png small size 320, 240");
4204: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4205: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4206: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4207: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4208: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4209: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4210: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4211: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4212: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4213: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4214: 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",\
4215: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4216: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4217: }else{
4218: first=0;
4219: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4220: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4221: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4222: 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",\
4223: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4224: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4225: }/* if first */
4226: } /* age mod 5 */
4227: } /* end loop age */
4228: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4229: first=1;
4230: } /*l12 */
4231: } /* k12 */
4232: } /*l1 */
4233: }/* k1 */
4234: /* } */ /* loop covariates */
4235: }
4236: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4237: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4238: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4239: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4240: free_vector(xp,1,npar);
4241: fclose(ficresprob);
4242: fclose(ficresprobcov);
4243: fclose(ficresprobcor);
4244: fflush(ficgp);
4245: fflush(fichtmcov);
4246: }
4247:
4248:
4249: /******************* Printing html file ***********/
4250: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4251: int lastpass, int stepm, int weightopt, char model[],\
4252: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4253: int popforecast, int estepm ,\
4254: double jprev1, double mprev1,double anprev1, \
4255: double jprev2, double mprev2,double anprev2){
4256: int jj1, k1, i1, cpt;
4257:
4258: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4259: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4260: </ul>");
4261: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4262: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4263: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4264: fprintf(fichtm,"\
4265: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4266: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4267: fprintf(fichtm,"\
4268: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4269: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4270: fprintf(fichtm,"\
4271: - (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): \
4272: <a href=\"%s\">%s</a> <br>\n",
4273: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4274: fprintf(fichtm,"\
4275: - Population projections by age and states: \
4276: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4277:
4278: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4279:
4280: m=pow(2,cptcoveff);
4281: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4282:
4283: jj1=0;
4284: for(k1=1; k1<=m;k1++){
4285: for(i1=1; i1<=ncodemax[k1];i1++){
4286: jj1++;
4287: if (cptcovn > 0) {
4288: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4289: for (cpt=1; cpt<=cptcoveff;cpt++)
4290: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4291: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4292: }
4293: /* Pij */
4294: 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> \
4295: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4296: /* Quasi-incidences */
4297: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4298: 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> \
4299: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4300: /* Period (stable) prevalence in each health state */
4301: for(cpt=1; cpt<=nlstate;cpt++){
4302: 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> \
4303: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4304: }
4305: for(cpt=1; cpt<=nlstate;cpt++) {
4306: 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> \
4307: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4308: }
4309: } /* end i1 */
4310: }/* End k1 */
4311: fprintf(fichtm,"</ul>");
4312:
4313:
4314: fprintf(fichtm,"\
4315: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4316: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4317:
4318: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4319: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4320: fprintf(fichtm,"\
4321: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4322: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4323:
4324: fprintf(fichtm,"\
4325: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4326: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4327: fprintf(fichtm,"\
4328: - 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): \
4329: <a href=\"%s\">%s</a> <br>\n</li>",
4330: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4331: fprintf(fichtm,"\
4332: - (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): \
4333: <a href=\"%s\">%s</a> <br>\n</li>",
4334: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4335: fprintf(fichtm,"\
4336: - 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",
4337: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4338: fprintf(fichtm,"\
4339: - 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",
4340: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4341: fprintf(fichtm,"\
4342: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4343: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4344:
4345: /* if(popforecast==1) fprintf(fichtm,"\n */
4346: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4347: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4348: /* <br>",fileres,fileres,fileres,fileres); */
4349: /* else */
4350: /* 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); */
4351: fflush(fichtm);
4352: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4353:
4354: m=pow(2,cptcoveff);
4355: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4356:
4357: jj1=0;
4358: for(k1=1; k1<=m;k1++){
4359: for(i1=1; i1<=ncodemax[k1];i1++){
4360: jj1++;
4361: if (cptcovn > 0) {
4362: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4363: for (cpt=1; cpt<=cptcoveff;cpt++)
4364: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4365: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4366: }
4367: for(cpt=1; cpt<=nlstate;cpt++) {
4368: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4369: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4370: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4371: }
4372: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4373: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4374: true period expectancies (those weighted with period prevalences are also\
4375: drawn in addition to the population based expectancies computed using\
4376: observed and cahotic prevalences: %s%d.png<br>\
4377: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4378: } /* end i1 */
4379: }/* End k1 */
4380: fprintf(fichtm,"</ul>");
4381: fflush(fichtm);
4382: }
4383:
4384: /******************* Gnuplot file **************/
4385: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4386:
4387: char dirfileres[132],optfileres[132];
4388: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4389: int ng=0;
4390: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4391: /* printf("Problem with file %s",optionfilegnuplot); */
4392: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4393: /* } */
4394:
4395: /*#ifdef windows */
4396: fprintf(ficgp,"cd \"%s\" \n",pathc);
4397: /*#endif */
4398: m=pow(2,cptcoveff);
4399:
4400: strcpy(dirfileres,optionfilefiname);
4401: strcpy(optfileres,"vpl");
4402: /* 1eme*/
4403: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4404: for (cpt=1; cpt<= nlstate ; cpt ++) {
4405: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4406: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4407: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4408: fprintf(ficgp,"set xlabel \"Age\" \n\
4409: set ylabel \"Probability\" \n\
4410: set ter png small size 320, 240\n\
4411: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4412:
4413: for (i=1; i<= nlstate ; i ++) {
4414: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4415: else fprintf(ficgp," %%*lf (%%*lf)");
4416: }
4417: 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);
4418: for (i=1; i<= nlstate ; i ++) {
4419: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4420: else fprintf(ficgp," %%*lf (%%*lf)");
4421: }
4422: 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);
4423: for (i=1; i<= nlstate ; i ++) {
4424: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4425: else fprintf(ficgp," %%*lf (%%*lf)");
4426: }
4427: 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));
4428: }
4429: }
4430: /*2 eme*/
4431: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4432: for (k1=1; k1<= m ; k1 ++) {
4433: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4434: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4435:
4436: for (i=1; i<= nlstate+1 ; i ++) {
4437: k=2*i;
4438: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4439: for (j=1; j<= nlstate+1 ; j ++) {
4440: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4441: else fprintf(ficgp," %%*lf (%%*lf)");
4442: }
4443: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4444: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4445: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4446: for (j=1; j<= nlstate+1 ; j ++) {
4447: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4448: else fprintf(ficgp," %%*lf (%%*lf)");
4449: }
4450: fprintf(ficgp,"\" t\"\" w l lt 0,");
4451: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4452: for (j=1; j<= nlstate+1 ; j ++) {
4453: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4454: else fprintf(ficgp," %%*lf (%%*lf)");
4455: }
4456: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4457: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4458: }
4459: }
4460:
4461: /*3eme*/
4462:
4463: for (k1=1; k1<= m ; k1 ++) {
4464: for (cpt=1; cpt<= nlstate ; cpt ++) {
4465: /* k=2+nlstate*(2*cpt-2); */
4466: k=2+(nlstate+1)*(cpt-1);
4467: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4468: fprintf(ficgp,"set ter png small size 320, 240\n\
4469: 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);
4470: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4471: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4472: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4473: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4474: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4475: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4476:
4477: */
4478: for (i=1; i< nlstate ; i ++) {
4479: 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);
4480: /* 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);*/
4481:
4482: }
4483: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4484: }
4485: }
4486:
4487: /* CV preval stable (period) */
4488: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4489: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4490: k=3;
4491: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4492: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4493: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4494: set ter png small size 320, 240\n\
4495: unset log y\n\
4496: plot [%.f:%.f] ", ageminpar, agemaxpar);
4497: for (i=1; i<= nlstate ; i ++){
4498: if(i==1)
4499: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4500: else
4501: fprintf(ficgp,", '' ");
4502: l=(nlstate+ndeath)*(i-1)+1;
4503: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4504: for (j=1; j<= (nlstate-1) ; j ++)
4505: fprintf(ficgp,"+$%d",k+l+j);
4506: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4507: } /* nlstate */
4508: fprintf(ficgp,"\n");
4509: } /* end cpt state*/
4510: } /* end covariate */
4511:
4512: /* proba elementaires */
4513: for(i=1,jk=1; i <=nlstate; i++){
4514: for(k=1; k <=(nlstate+ndeath); k++){
4515: if (k != i) {
4516: for(j=1; j <=ncovmodel; j++){
4517: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4518: jk++;
4519: fprintf(ficgp,"\n");
4520: }
4521: }
4522: }
4523: }
4524: /*goto avoid;*/
4525: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4526: for(jk=1; jk <=m; jk++) {
4527: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4528: if (ng==2)
4529: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4530: else
4531: fprintf(ficgp,"\nset title \"Probability\"\n");
4532: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4533: i=1;
4534: for(k2=1; k2<=nlstate; k2++) {
4535: k3=i;
4536: for(k=1; k<=(nlstate+ndeath); k++) {
4537: if (k != k2){
4538: if(ng==2)
4539: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4540: else
4541: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4542: ij=1;/* To be checked else nbcode[0][0] wrong */
4543: for(j=3; j <=ncovmodel; j++) {
4544: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
4545: fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
4546: ij++;
4547: }
4548: else
4549: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4550: }
4551: fprintf(ficgp,")/(1");
4552:
4553: for(k1=1; k1 <=nlstate; k1++){
4554: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4555: ij=1;
4556: for(j=3; j <=ncovmodel; j++){
4557: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
4558: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
4559: ij++;
4560: }
4561: else
4562: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4563: }
4564: fprintf(ficgp,")");
4565: }
4566: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4567: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4568: i=i+ncovmodel;
4569: }
4570: } /* end k */
4571: } /* end k2 */
4572: } /* end jk */
4573: } /* end ng */
4574: /* avoid: */
4575: fflush(ficgp);
4576: } /* end gnuplot */
4577:
4578:
4579: /*************** Moving average **************/
4580: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4581:
4582: int i, cpt, cptcod;
4583: int modcovmax =1;
4584: int mobilavrange, mob;
4585: double age;
4586:
4587: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4588: a covariate has 2 modalities */
4589: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4590:
4591: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4592: if(mobilav==1) mobilavrange=5; /* default */
4593: else mobilavrange=mobilav;
4594: for (age=bage; age<=fage; age++)
4595: for (i=1; i<=nlstate;i++)
4596: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4597: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4598: /* We keep the original values on the extreme ages bage, fage and for
4599: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4600: we use a 5 terms etc. until the borders are no more concerned.
4601: */
4602: for (mob=3;mob <=mobilavrange;mob=mob+2){
4603: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4604: for (i=1; i<=nlstate;i++){
4605: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4606: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4607: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4608: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4609: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4610: }
4611: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4612: }
4613: }
4614: }/* end age */
4615: }/* end mob */
4616: }else return -1;
4617: return 0;
4618: }/* End movingaverage */
4619:
4620:
4621: /************** Forecasting ******************/
4622: 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){
4623: /* proj1, year, month, day of starting projection
4624: agemin, agemax range of age
4625: dateprev1 dateprev2 range of dates during which prevalence is computed
4626: anproj2 year of en of projection (same day and month as proj1).
4627: */
4628: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4629: double agec; /* generic age */
4630: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4631: double *popeffectif,*popcount;
4632: double ***p3mat;
4633: double ***mobaverage;
4634: char fileresf[FILENAMELENGTH];
4635:
4636: agelim=AGESUP;
4637: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4638:
4639: strcpy(fileresf,"f");
4640: strcat(fileresf,fileres);
4641: if((ficresf=fopen(fileresf,"w"))==NULL) {
4642: printf("Problem with forecast resultfile: %s\n", fileresf);
4643: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4644: }
4645: printf("Computing forecasting: result on file '%s' \n", fileresf);
4646: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4647:
4648: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4649:
4650: if (mobilav!=0) {
4651: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4652: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4653: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4654: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4655: }
4656: }
4657:
4658: stepsize=(int) (stepm+YEARM-1)/YEARM;
4659: if (stepm<=12) stepsize=1;
4660: if(estepm < stepm){
4661: printf ("Problem %d lower than %d\n",estepm, stepm);
4662: }
4663: else hstepm=estepm;
4664:
4665: hstepm=hstepm/stepm;
4666: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4667: fractional in yp1 */
4668: anprojmean=yp;
4669: yp2=modf((yp1*12),&yp);
4670: mprojmean=yp;
4671: yp1=modf((yp2*30.5),&yp);
4672: jprojmean=yp;
4673: if(jprojmean==0) jprojmean=1;
4674: if(mprojmean==0) jprojmean=1;
4675:
4676: i1=cptcoveff;
4677: if (cptcovn < 1){i1=1;}
4678:
4679: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4680:
4681: fprintf(ficresf,"#****** Routine prevforecast **\n");
4682:
4683: /* if (h==(int)(YEARM*yearp)){ */
4684: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4685: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4686: k=k+1;
4687: fprintf(ficresf,"\n#******");
4688: for(j=1;j<=cptcoveff;j++) {
4689: 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]]);
4690: }
4691: fprintf(ficresf,"******\n");
4692: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4693: for(j=1; j<=nlstate+ndeath;j++){
4694: for(i=1; i<=nlstate;i++)
4695: fprintf(ficresf," p%d%d",i,j);
4696: fprintf(ficresf," p.%d",j);
4697: }
4698: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4699: fprintf(ficresf,"\n");
4700: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4701:
4702: for (agec=fage; agec>=(ageminpar-1); agec--){
4703: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4704: nhstepm = nhstepm/hstepm;
4705: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4706: oldm=oldms;savm=savms;
4707: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4708:
4709: for (h=0; h<=nhstepm; h++){
4710: if (h*hstepm/YEARM*stepm ==yearp) {
4711: fprintf(ficresf,"\n");
4712: for(j=1;j<=cptcoveff;j++)
4713: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4714: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4715: }
4716: for(j=1; j<=nlstate+ndeath;j++) {
4717: ppij=0.;
4718: for(i=1; i<=nlstate;i++) {
4719: if (mobilav==1)
4720: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4721: else {
4722: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4723: }
4724: if (h*hstepm/YEARM*stepm== yearp) {
4725: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4726: }
4727: } /* end i */
4728: if (h*hstepm/YEARM*stepm==yearp) {
4729: fprintf(ficresf," %.3f", ppij);
4730: }
4731: }/* end j */
4732: } /* end h */
4733: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4734: } /* end agec */
4735: } /* end yearp */
4736: } /* end cptcod */
4737: } /* end cptcov */
4738:
4739: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4740:
4741: fclose(ficresf);
4742: }
4743:
4744: /************** Forecasting *****not tested NB*************/
4745: 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){
4746:
4747: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4748: int *popage;
4749: double calagedatem, agelim, kk1, kk2;
4750: double *popeffectif,*popcount;
4751: double ***p3mat,***tabpop,***tabpopprev;
4752: double ***mobaverage;
4753: char filerespop[FILENAMELENGTH];
4754:
4755: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4756: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4757: agelim=AGESUP;
4758: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4759:
4760: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4761:
4762:
4763: strcpy(filerespop,"pop");
4764: strcat(filerespop,fileres);
4765: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4766: printf("Problem with forecast resultfile: %s\n", filerespop);
4767: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4768: }
4769: printf("Computing forecasting: result on file '%s' \n", filerespop);
4770: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4771:
4772: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4773:
4774: if (mobilav!=0) {
4775: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4776: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4777: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4778: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4779: }
4780: }
4781:
4782: stepsize=(int) (stepm+YEARM-1)/YEARM;
4783: if (stepm<=12) stepsize=1;
4784:
4785: agelim=AGESUP;
4786:
4787: hstepm=1;
4788: hstepm=hstepm/stepm;
4789:
4790: if (popforecast==1) {
4791: if((ficpop=fopen(popfile,"r"))==NULL) {
4792: printf("Problem with population file : %s\n",popfile);exit(0);
4793: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4794: }
4795: popage=ivector(0,AGESUP);
4796: popeffectif=vector(0,AGESUP);
4797: popcount=vector(0,AGESUP);
4798:
4799: i=1;
4800: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4801:
4802: imx=i;
4803: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4804: }
4805:
4806: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4807: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4808: k=k+1;
4809: fprintf(ficrespop,"\n#******");
4810: for(j=1;j<=cptcoveff;j++) {
4811: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4812: }
4813: fprintf(ficrespop,"******\n");
4814: fprintf(ficrespop,"# Age");
4815: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4816: if (popforecast==1) fprintf(ficrespop," [Population]");
4817:
4818: for (cpt=0; cpt<=0;cpt++) {
4819: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4820:
4821: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4822: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4823: nhstepm = nhstepm/hstepm;
4824:
4825: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4826: oldm=oldms;savm=savms;
4827: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4828:
4829: for (h=0; h<=nhstepm; h++){
4830: if (h==(int) (calagedatem+YEARM*cpt)) {
4831: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4832: }
4833: for(j=1; j<=nlstate+ndeath;j++) {
4834: kk1=0.;kk2=0;
4835: for(i=1; i<=nlstate;i++) {
4836: if (mobilav==1)
4837: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4838: else {
4839: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4840: }
4841: }
4842: if (h==(int)(calagedatem+12*cpt)){
4843: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4844: /*fprintf(ficrespop," %.3f", kk1);
4845: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4846: }
4847: }
4848: for(i=1; i<=nlstate;i++){
4849: kk1=0.;
4850: for(j=1; j<=nlstate;j++){
4851: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4852: }
4853: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4854: }
4855:
4856: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4857: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4858: }
4859: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4860: }
4861: }
4862:
4863: /******/
4864:
4865: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4866: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4867: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4868: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4869: nhstepm = nhstepm/hstepm;
4870:
4871: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4872: oldm=oldms;savm=savms;
4873: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4874: for (h=0; h<=nhstepm; h++){
4875: if (h==(int) (calagedatem+YEARM*cpt)) {
4876: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4877: }
4878: for(j=1; j<=nlstate+ndeath;j++) {
4879: kk1=0.;kk2=0;
4880: for(i=1; i<=nlstate;i++) {
4881: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4882: }
4883: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4884: }
4885: }
4886: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4887: }
4888: }
4889: }
4890: }
4891:
4892: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4893:
4894: if (popforecast==1) {
4895: free_ivector(popage,0,AGESUP);
4896: free_vector(popeffectif,0,AGESUP);
4897: free_vector(popcount,0,AGESUP);
4898: }
4899: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4900: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4901: fclose(ficrespop);
4902: } /* End of popforecast */
4903:
4904: int fileappend(FILE *fichier, char *optionfich)
4905: {
4906: if((fichier=fopen(optionfich,"a"))==NULL) {
4907: printf("Problem with file: %s\n", optionfich);
4908: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4909: return (0);
4910: }
4911: fflush(fichier);
4912: return (1);
4913: }
4914:
4915:
4916: /**************** function prwizard **********************/
4917: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4918: {
4919:
4920: /* Wizard to print covariance matrix template */
4921:
4922: char ca[32], cb[32];
4923: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4924: int numlinepar;
4925:
4926: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4927: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4928: for(i=1; i <=nlstate; i++){
4929: jj=0;
4930: for(j=1; j <=nlstate+ndeath; j++){
4931: if(j==i) continue;
4932: jj++;
4933: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4934: printf("%1d%1d",i,j);
4935: fprintf(ficparo,"%1d%1d",i,j);
4936: for(k=1; k<=ncovmodel;k++){
4937: /* printf(" %lf",param[i][j][k]); */
4938: /* fprintf(ficparo," %lf",param[i][j][k]); */
4939: printf(" 0.");
4940: fprintf(ficparo," 0.");
4941: }
4942: printf("\n");
4943: fprintf(ficparo,"\n");
4944: }
4945: }
4946: printf("# Scales (for hessian or gradient estimation)\n");
4947: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4948: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4949: for(i=1; i <=nlstate; i++){
4950: jj=0;
4951: for(j=1; j <=nlstate+ndeath; j++){
4952: if(j==i) continue;
4953: jj++;
4954: fprintf(ficparo,"%1d%1d",i,j);
4955: printf("%1d%1d",i,j);
4956: fflush(stdout);
4957: for(k=1; k<=ncovmodel;k++){
4958: /* printf(" %le",delti3[i][j][k]); */
4959: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4960: printf(" 0.");
4961: fprintf(ficparo," 0.");
4962: }
4963: numlinepar++;
4964: printf("\n");
4965: fprintf(ficparo,"\n");
4966: }
4967: }
4968: printf("# Covariance matrix\n");
4969: /* # 121 Var(a12)\n\ */
4970: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4971: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4972: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4973: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4974: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4975: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4976: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4977: fflush(stdout);
4978: fprintf(ficparo,"# Covariance matrix\n");
4979: /* # 121 Var(a12)\n\ */
4980: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4981: /* # ...\n\ */
4982: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4983:
4984: for(itimes=1;itimes<=2;itimes++){
4985: jj=0;
4986: for(i=1; i <=nlstate; i++){
4987: for(j=1; j <=nlstate+ndeath; j++){
4988: if(j==i) continue;
4989: for(k=1; k<=ncovmodel;k++){
4990: jj++;
4991: ca[0]= k+'a'-1;ca[1]='\0';
4992: if(itimes==1){
4993: printf("#%1d%1d%d",i,j,k);
4994: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4995: }else{
4996: printf("%1d%1d%d",i,j,k);
4997: fprintf(ficparo,"%1d%1d%d",i,j,k);
4998: /* printf(" %.5le",matcov[i][j]); */
4999: }
5000: ll=0;
5001: for(li=1;li <=nlstate; li++){
5002: for(lj=1;lj <=nlstate+ndeath; lj++){
5003: if(lj==li) continue;
5004: for(lk=1;lk<=ncovmodel;lk++){
5005: ll++;
5006: if(ll<=jj){
5007: cb[0]= lk +'a'-1;cb[1]='\0';
5008: if(ll<jj){
5009: if(itimes==1){
5010: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5011: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5012: }else{
5013: printf(" 0.");
5014: fprintf(ficparo," 0.");
5015: }
5016: }else{
5017: if(itimes==1){
5018: printf(" Var(%s%1d%1d)",ca,i,j);
5019: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5020: }else{
5021: printf(" 0.");
5022: fprintf(ficparo," 0.");
5023: }
5024: }
5025: }
5026: } /* end lk */
5027: } /* end lj */
5028: } /* end li */
5029: printf("\n");
5030: fprintf(ficparo,"\n");
5031: numlinepar++;
5032: } /* end k*/
5033: } /*end j */
5034: } /* end i */
5035: } /* end itimes */
5036:
5037: } /* end of prwizard */
5038: /******************* Gompertz Likelihood ******************************/
5039: double gompertz(double x[])
5040: {
5041: double A,B,L=0.0,sump=0.,num=0.;
5042: int i,n=0; /* n is the size of the sample */
5043:
5044: for (i=0;i<=imx-1 ; i++) {
5045: sump=sump+weight[i];
5046: /* sump=sump+1;*/
5047: num=num+1;
5048: }
5049:
5050:
5051: /* for (i=0; i<=imx; i++)
5052: 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]);*/
5053:
5054: for (i=1;i<=imx ; i++)
5055: {
5056: if (cens[i] == 1 && wav[i]>1)
5057: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5058:
5059: if (cens[i] == 0 && wav[i]>1)
5060: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5061: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5062:
5063: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5064: if (wav[i] > 1 ) { /* ??? */
5065: L=L+A*weight[i];
5066: /* 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]);*/
5067: }
5068: }
5069:
5070: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5071:
5072: return -2*L*num/sump;
5073: }
5074:
5075: #ifdef GSL
5076: /******************* Gompertz_f Likelihood ******************************/
5077: double gompertz_f(const gsl_vector *v, void *params)
5078: {
5079: double A,B,LL=0.0,sump=0.,num=0.;
5080: double *x= (double *) v->data;
5081: int i,n=0; /* n is the size of the sample */
5082:
5083: for (i=0;i<=imx-1 ; i++) {
5084: sump=sump+weight[i];
5085: /* sump=sump+1;*/
5086: num=num+1;
5087: }
5088:
5089:
5090: /* for (i=0; i<=imx; i++)
5091: 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]);*/
5092: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5093: for (i=1;i<=imx ; i++)
5094: {
5095: if (cens[i] == 1 && wav[i]>1)
5096: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5097:
5098: if (cens[i] == 0 && wav[i]>1)
5099: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5100: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5101:
5102: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5103: if (wav[i] > 1 ) { /* ??? */
5104: LL=LL+A*weight[i];
5105: /* 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]);*/
5106: }
5107: }
5108:
5109: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5110: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5111:
5112: return -2*LL*num/sump;
5113: }
5114: #endif
5115:
5116: /******************* Printing html file ***********/
5117: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5118: int lastpass, int stepm, int weightopt, char model[],\
5119: int imx, double p[],double **matcov,double agemortsup){
5120: int i,k;
5121:
5122: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5123: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5124: for (i=1;i<=2;i++)
5125: 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]));
5126: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5127: fprintf(fichtm,"</ul>");
5128:
5129: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5130:
5131: 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>");
5132:
5133: for (k=agegomp;k<(agemortsup-2);k++)
5134: 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]);
5135:
5136:
5137: fflush(fichtm);
5138: }
5139:
5140: /******************* Gnuplot file **************/
5141: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5142:
5143: char dirfileres[132],optfileres[132];
5144:
5145: int ng;
5146:
5147:
5148: /*#ifdef windows */
5149: fprintf(ficgp,"cd \"%s\" \n",pathc);
5150: /*#endif */
5151:
5152:
5153: strcpy(dirfileres,optionfilefiname);
5154: strcpy(optfileres,"vpl");
5155: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5156: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5157: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5158: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5159: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5160:
5161: }
5162:
5163: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5164: {
5165:
5166: /*-------- data file ----------*/
5167: FILE *fic;
5168: char dummy[]=" ";
5169: int i=0, j=0, n=0;
5170: int linei, month, year,iout;
5171: char line[MAXLINE], linetmp[MAXLINE];
5172: char stra[MAXLINE], strb[MAXLINE];
5173: char *stratrunc;
5174: int lstra;
5175:
5176:
5177: if((fic=fopen(datafile,"r"))==NULL) {
5178: printf("Problem while opening datafile: %s\n", datafile);return 1;
5179: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5180: }
5181:
5182: i=1;
5183: linei=0;
5184: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5185: linei=linei+1;
5186: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5187: if(line[j] == '\t')
5188: line[j] = ' ';
5189: }
5190: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5191: ;
5192: };
5193: line[j+1]=0; /* Trims blanks at end of line */
5194: if(line[0]=='#'){
5195: fprintf(ficlog,"Comment line\n%s\n",line);
5196: printf("Comment line\n%s\n",line);
5197: continue;
5198: }
5199: trimbb(linetmp,line); /* Trims multiple blanks in line */
5200: strcpy(line, linetmp);
5201:
5202:
5203: for (j=maxwav;j>=1;j--){
5204: cutv(stra, strb, line, ' ');
5205: if(strb[0]=='.') { /* Missing status */
5206: lval=-1;
5207: }else{
5208: errno=0;
5209: lval=strtol(strb,&endptr,10);
5210: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5211: if( strb[0]=='\0' || (*endptr != '\0')){
5212: 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);
5213: 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);
5214: return 1;
5215: }
5216: }
5217: s[j][i]=lval;
5218:
5219: strcpy(line,stra);
5220: cutv(stra, strb,line,' ');
5221: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5222: }
5223: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5224: month=99;
5225: year=9999;
5226: }else{
5227: 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);
5228: 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);
5229: return 1;
5230: }
5231: anint[j][i]= (double) year;
5232: mint[j][i]= (double)month;
5233: strcpy(line,stra);
5234: } /* ENd Waves */
5235:
5236: cutv(stra, strb,line,' ');
5237: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5238: }
5239: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5240: month=99;
5241: year=9999;
5242: }else{
5243: 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);
5244: 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);
5245: return 1;
5246: }
5247: andc[i]=(double) year;
5248: moisdc[i]=(double) month;
5249: strcpy(line,stra);
5250:
5251: cutv(stra, strb,line,' ');
5252: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5253: }
5254: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5255: month=99;
5256: year=9999;
5257: }else{
5258: 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);
5259: 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);
5260: return 1;
5261: }
5262: if (year==9999) {
5263: 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);
5264: 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);
5265: return 1;
5266:
5267: }
5268: annais[i]=(double)(year);
5269: moisnais[i]=(double)(month);
5270: strcpy(line,stra);
5271:
5272: cutv(stra, strb,line,' ');
5273: errno=0;
5274: dval=strtod(strb,&endptr);
5275: if( strb[0]=='\0' || (*endptr != '\0')){
5276: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5277: 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);
5278: fflush(ficlog);
5279: return 1;
5280: }
5281: weight[i]=dval;
5282: strcpy(line,stra);
5283:
5284: for (j=ncovcol;j>=1;j--){
5285: cutv(stra, strb,line,' ');
5286: if(strb[0]=='.') { /* Missing status */
5287: lval=-1;
5288: }else{
5289: errno=0;
5290: lval=strtol(strb,&endptr,10);
5291: if( strb[0]=='\0' || (*endptr != '\0')){
5292: 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);
5293: 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);
5294: return 1;
5295: }
5296: }
5297: if(lval <-1 || lval >1){
5298: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5299: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5300: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5301: For example, for multinomial values like 1, 2 and 3,\n \
5302: build V1=0 V2=0 for the reference value (1),\n \
5303: V1=1 V2=0 for (2) \n \
5304: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5305: output of IMaCh is often meaningless.\n \
5306: Exiting.\n",lval,linei, i,line,j);
5307: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5308: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5309: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5310: For example, for multinomial values like 1, 2 and 3,\n \
5311: build V1=0 V2=0 for the reference value (1),\n \
5312: V1=1 V2=0 for (2) \n \
5313: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5314: output of IMaCh is often meaningless.\n \
5315: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5316: return 1;
5317: }
5318: covar[j][i]=(double)(lval);
5319: strcpy(line,stra);
5320: }
5321: lstra=strlen(stra);
5322:
5323: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5324: stratrunc = &(stra[lstra-9]);
5325: num[i]=atol(stratrunc);
5326: }
5327: else
5328: num[i]=atol(stra);
5329: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5330: 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;}*/
5331:
5332: i=i+1;
5333: } /* End loop reading data */
5334:
5335: *imax=i-1; /* Number of individuals */
5336: fclose(fic);
5337:
5338: return (0);
5339: /* endread: */
5340: printf("Exiting readdata: ");
5341: fclose(fic);
5342: return (1);
5343:
5344:
5345:
5346: }
5347: void removespace(char *str) {
5348: char *p1 = str, *p2 = str;
5349: do
5350: while (*p2 == ' ')
5351: p2++;
5352: while (*p1++ == *p2++);
5353: }
5354:
5355: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5356: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5357: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5358: * - cptcovn or number of covariates k of the models excluding age*products =6
5359: * - cptcovage number of covariates with age*products =2
5360: * - cptcovs number of simple covariates
5361: * - 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
5362: * which is a new column after the 9 (ncovcol) variables.
5363: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5364: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5365: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5366: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5367: */
5368: {
5369: int i, j, k, ks;
5370: int j1, k1, k2;
5371: char modelsav[80];
5372: char stra[80], strb[80], strc[80], strd[80],stre[80];
5373:
5374: /*removespace(model);*/
5375: if (strlen(model) >1){ /* If there is at least 1 covariate */
5376: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5377: j=nbocc(model,'+'); /**< j=Number of '+' */
5378: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5379: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5380: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5381: /* including age products which are counted in cptcovage.
5382: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5383: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5384: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5385: strcpy(modelsav,model);
5386: if (strstr(model,"AGE") !=0){
5387: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5388: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5389: return 1;
5390: }
5391: if (strstr(model,"v") !=0){
5392: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5393: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5394: return 1;
5395: }
5396:
5397: /* Design
5398: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5399: * < ncovcol=8 >
5400: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5401: * k= 1 2 3 4 5 6 7 8
5402: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5403: * covar[k,i], value of kth covariate if not including age for individual i:
5404: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5405: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5406: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5407: * Tage[++cptcovage]=k
5408: * if products, new covar are created after ncovcol with k1
5409: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5410: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5411: * 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
5412: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5413: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5414: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5415: * < ncovcol=8 >
5416: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5417: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5418: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5419: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5420: * p Tprod[1]@2={ 6, 5}
5421: *p Tvard[1][1]@4= {7, 8, 5, 6}
5422: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5423: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5424: *How to reorganize?
5425: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5426: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5427: * {2, 1, 4, 8, 5, 6, 3, 7}
5428: * Struct []
5429: */
5430:
5431: /* This loop fills the array Tvar from the string 'model'.*/
5432: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5433: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5434: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5435: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5436: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5437: /* k=1 Tvar[1]=2 (from V2) */
5438: /* k=5 Tvar[5] */
5439: /* for (k=1; k<=cptcovn;k++) { */
5440: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5441: /* } */
5442: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
5443: /*
5444: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5445: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5446: Tvar[k]=0;
5447: cptcovage=0;
5448: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5449: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5450: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5451: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5452: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5453: /*scanf("%d",i);*/
5454: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5455: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5456: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5457: /* covar is not filled and then is empty */
5458: cptcovprod--;
5459: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5460: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5461: cptcovage++; /* Sums the number of covariates which include age as a product */
5462: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5463: /*printf("stre=%s ", stre);*/
5464: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5465: cptcovprod--;
5466: cutl(stre,strb,strc,'V');
5467: Tvar[k]=atoi(stre);
5468: cptcovage++;
5469: Tage[cptcovage]=k;
5470: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5471: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5472: cptcovn++;
5473: cptcovprodnoage++;k1++;
5474: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5475: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5476: because this model-covariate is a construction we invent a new column
5477: ncovcol + k1
5478: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5479: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5480: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5481: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5482: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5483: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5484: k2=k2+2;
5485: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5486: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5487: for (i=1; i<=lastobs;i++){
5488: /* Computes the new covariate which is a product of
5489: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5490: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5491: }
5492: } /* End age is not in the model */
5493: } /* End if model includes a product */
5494: else { /* no more sum */
5495: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5496: /* scanf("%d",i);*/
5497: cutl(strd,strc,strb,'V');
5498: ks++; /**< Number of simple covariates */
5499: cptcovn++;
5500: Tvar[k]=atoi(strd);
5501: }
5502: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5503: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5504: scanf("%d",i);*/
5505: } /* end of loop + */
5506: } /* end model */
5507:
5508: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5509: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5510:
5511: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5512: printf("cptcovprod=%d ", cptcovprod);
5513: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5514:
5515: scanf("%d ",i);*/
5516:
5517:
5518: return (0); /* with covar[new additional covariate if product] and Tage if age */
5519: /*endread:*/
5520: printf("Exiting decodemodel: ");
5521: return (1);
5522: }
5523:
5524: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5525: {
5526: int i, m;
5527:
5528: for (i=1; i<=imx; i++) {
5529: for(m=2; (m<= maxwav); m++) {
5530: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5531: anint[m][i]=9999;
5532: s[m][i]=-1;
5533: }
5534: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5535: *nberr = *nberr + 1;
5536: 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);
5537: 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);
5538: s[m][i]=-1;
5539: }
5540: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5541: (*nberr)++;
5542: 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]);
5543: 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]);
5544: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5545: }
5546: }
5547: }
5548:
5549: for (i=1; i<=imx; i++) {
5550: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5551: for(m=firstpass; (m<= lastpass); m++){
5552: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5553: if (s[m][i] >= nlstate+1) {
5554: if(agedc[i]>0){
5555: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5556: agev[m][i]=agedc[i];
5557: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5558: }else {
5559: if ((int)andc[i]!=9999){
5560: nbwarn++;
5561: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5562: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5563: agev[m][i]=-1;
5564: }
5565: }
5566: } /* agedc > 0 */
5567: }
5568: else if(s[m][i] !=9){ /* Standard case, age in fractional
5569: years but with the precision of a month */
5570: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5571: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5572: agev[m][i]=1;
5573: else if(agev[m][i] < *agemin){
5574: *agemin=agev[m][i];
5575: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5576: }
5577: else if(agev[m][i] >*agemax){
5578: *agemax=agev[m][i];
5579: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5580: }
5581: /*agev[m][i]=anint[m][i]-annais[i];*/
5582: /* agev[m][i] = age[i]+2*m;*/
5583: }
5584: else { /* =9 */
5585: agev[m][i]=1;
5586: s[m][i]=-1;
5587: }
5588: }
5589: else /*= 0 Unknown */
5590: agev[m][i]=1;
5591: }
5592:
5593: }
5594: for (i=1; i<=imx; i++) {
5595: for(m=firstpass; (m<=lastpass); m++){
5596: if (s[m][i] > (nlstate+ndeath)) {
5597: (*nberr)++;
5598: 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);
5599: 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);
5600: return 1;
5601: }
5602: }
5603: }
5604:
5605: /*for (i=1; i<=imx; i++){
5606: for (m=firstpass; (m<lastpass); m++){
5607: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5608: }
5609:
5610: }*/
5611:
5612:
5613: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5614: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5615:
5616: return (0);
5617: /* endread:*/
5618: printf("Exiting calandcheckages: ");
5619: return (1);
5620: }
5621:
5622: #if defined(_MSC_VER)
5623: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5624: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5625: //#include "stdafx.h"
5626: //#include <stdio.h>
5627: //#include <tchar.h>
5628: //#include <windows.h>
5629: //#include <iostream>
5630: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5631:
5632: LPFN_ISWOW64PROCESS fnIsWow64Process;
5633:
5634: BOOL IsWow64()
5635: {
5636: BOOL bIsWow64 = FALSE;
5637:
5638: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5639: // (HANDLE, PBOOL);
5640:
5641: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5642:
5643: HMODULE module = GetModuleHandle(_T("kernel32"));
5644: const char funcName[] = "IsWow64Process";
5645: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5646: GetProcAddress(module, funcName);
5647:
5648: if (NULL != fnIsWow64Process)
5649: {
5650: if (!fnIsWow64Process(GetCurrentProcess(),
5651: &bIsWow64))
5652: //throw std::exception("Unknown error");
5653: printf("Unknown error\n");
5654: }
5655: return bIsWow64 != FALSE;
5656: }
5657: #endif
5658:
5659: void syscompilerinfo()
5660: {
5661: /* #include "syscompilerinfo.h"*/
5662: /* command line Intel compiler 32bit windows, XP compatible:*/
5663: /* /GS /W3 /Gy
5664: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5665: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5666: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
5667: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5668: */
5669: /* 64 bits */
5670: /*
5671: /GS /W3 /Gy
5672: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5673: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5674: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5675: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5676: /* Optimization are useless and O3 is slower than O2 */
5677: /*
5678: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
5679: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
5680: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
5681: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
5682: */
5683: /* Link is */ /* /OUT:"visual studio
5684: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
5685: /PDB:"visual studio
5686: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
5687: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
5688: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
5689: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
5690: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
5691: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
5692: uiAccess='false'"
5693: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
5694: /NOLOGO /TLBID:1
5695: */
5696: #if defined __INTEL_COMPILER
5697: #if defined(__GNUC__)
5698: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5699: #endif
5700: #elif defined(__GNUC__)
5701: #ifndef __APPLE__
5702: #include <gnu/libc-version.h> /* Only on gnu */
5703: #endif
5704: struct utsname sysInfo;
5705: int cross = CROSS;
5706: if (cross){
5707: printf("Cross-");
5708: fprintf(ficlog, "Cross-");
5709: }
5710: #endif
5711:
5712: #include <stdint.h>
5713:
5714: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5715: #if defined(__clang__)
5716: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5717: #endif
5718: #if defined(__ICC) || defined(__INTEL_COMPILER)
5719: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5720: #endif
5721: #if defined(__GNUC__) || defined(__GNUG__)
5722: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5723: #endif
5724: #if defined(__HP_cc) || defined(__HP_aCC)
5725: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5726: #endif
5727: #if defined(__IBMC__) || defined(__IBMCPP__)
5728: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5729: #endif
5730: #if defined(_MSC_VER)
5731: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5732: #endif
5733: #if defined(__PGI)
5734: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5735: #endif
5736: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5737: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5738: #endif
5739: printf(" for ");fprintf(ficlog," for ");
5740:
5741: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5742: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5743: // Windows (x64 and x86)
5744: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
5745: #elif __unix__ // all unices, not all compilers
5746: // Unix
5747: printf("Unix ");fprintf(ficlog,"Unix ");
5748: #elif __linux__
5749: // linux
5750: printf("linux ");fprintf(ficlog,"linux ");
5751: #elif __APPLE__
5752: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5753: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
5754: #endif
5755:
5756: /* __MINGW32__ */
5757: /* __CYGWIN__ */
5758: /* __MINGW64__ */
5759: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5760: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5761: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5762: /* _WIN64 // Defined for applications for Win64. */
5763: /* _M_X64 // Defined for compilations that target x64 processors. */
5764: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
5765:
5766: #if UINTPTR_MAX == 0xffffffff
5767: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
5768: #elif UINTPTR_MAX == 0xffffffffffffffff
5769: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
5770: #else
5771: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
5772: #endif
5773:
5774: #if defined(__GNUC__)
5775: # if defined(__GNUC_PATCHLEVEL__)
5776: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5777: + __GNUC_MINOR__ * 100 \
5778: + __GNUC_PATCHLEVEL__)
5779: # else
5780: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5781: + __GNUC_MINOR__ * 100)
5782: # endif
5783: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5784: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
5785:
5786: if (uname(&sysInfo) != -1) {
5787: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5788: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5789: }
5790: else
5791: perror("uname() error");
5792: //#ifndef __INTEL_COMPILER
5793: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
5794: printf("GNU libc version: %s\n", gnu_get_libc_version());
5795: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
5796: #endif
5797: #endif
5798:
5799: // void main()
5800: // {
5801: #if defined(_MSC_VER)
5802: if (IsWow64()){
5803: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5804: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5805: }
5806: else{
5807: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5808: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5809: }
5810: // printf("\nPress Enter to continue...");
5811: // getchar();
5812: // }
5813:
5814: #endif
5815:
5816:
5817: }
5818:
5819: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5820: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5821: int i, j, k, i1 ;
5822: double ftolpl = 1.e-10;
5823: double age, agebase, agelim;
5824:
5825: strcpy(filerespl,"pl");
5826: strcat(filerespl,fileres);
5827: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5828: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5829: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5830: }
5831: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5832: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5833: pstamp(ficrespl);
5834: fprintf(ficrespl,"# Period (stable) prevalence \n");
5835: fprintf(ficrespl,"#Age ");
5836: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5837: fprintf(ficrespl,"\n");
5838:
5839: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5840:
5841: agebase=ageminpar;
5842: agelim=agemaxpar;
5843:
5844: i1=pow(2,cptcoveff);
5845: if (cptcovn < 1){i1=1;}
5846:
5847: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5848: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5849: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5850: k=k+1;
5851: /* to clean */
5852: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5853: fprintf(ficrespl,"\n#******");
5854: printf("\n#******");
5855: fprintf(ficlog,"\n#******");
5856: for(j=1;j<=cptcoveff;j++) {
5857: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5858: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5859: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5860: }
5861: fprintf(ficrespl,"******\n");
5862: printf("******\n");
5863: fprintf(ficlog,"******\n");
5864:
5865: fprintf(ficrespl,"#Age ");
5866: for(j=1;j<=cptcoveff;j++) {
5867: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5868: }
5869: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5870: fprintf(ficrespl,"\n");
5871:
5872: for (age=agebase; age<=agelim; age++){
5873: /* for (age=agebase; age<=agebase; age++){ */
5874: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5875: fprintf(ficrespl,"%.0f ",age );
5876: for(j=1;j<=cptcoveff;j++)
5877: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5878: for(i=1; i<=nlstate;i++)
5879: fprintf(ficrespl," %.5f", prlim[i][i]);
5880: fprintf(ficrespl,"\n");
5881: } /* Age */
5882: /* was end of cptcod */
5883: } /* cptcov */
5884: return 0;
5885: }
5886:
5887: int hPijx(double *p, int bage, int fage){
5888: /*------------- h Pij x at various ages ------------*/
5889:
5890: int stepsize;
5891: int agelim;
5892: int hstepm;
5893: int nhstepm;
5894: int h, i, i1, j, k;
5895:
5896: double agedeb;
5897: double ***p3mat;
5898:
5899: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5900: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5901: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5902: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5903: }
5904: printf("Computing pij: result on file '%s' \n", filerespij);
5905: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5906:
5907: stepsize=(int) (stepm+YEARM-1)/YEARM;
5908: /*if (stepm<=24) stepsize=2;*/
5909:
5910: agelim=AGESUP;
5911: hstepm=stepsize*YEARM; /* Every year of age */
5912: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5913:
5914: /* hstepm=1; aff par mois*/
5915: pstamp(ficrespij);
5916: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5917: i1= pow(2,cptcoveff);
5918: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
5919: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
5920: /* k=k+1; */
5921: for (k=1; k <= (int) pow(2,cptcoveff); k++){
5922: fprintf(ficrespij,"\n#****** ");
5923: for(j=1;j<=cptcoveff;j++)
5924: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5925: fprintf(ficrespij,"******\n");
5926:
5927: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5928: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5929: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5930:
5931: /* nhstepm=nhstepm*YEARM; aff par mois*/
5932:
5933: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5934: oldm=oldms;savm=savms;
5935: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5936: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5937: for(i=1; i<=nlstate;i++)
5938: for(j=1; j<=nlstate+ndeath;j++)
5939: fprintf(ficrespij," %1d-%1d",i,j);
5940: fprintf(ficrespij,"\n");
5941: for (h=0; h<=nhstepm; h++){
5942: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5943: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5944: for(i=1; i<=nlstate;i++)
5945: for(j=1; j<=nlstate+ndeath;j++)
5946: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5947: fprintf(ficrespij,"\n");
5948: }
5949: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5950: fprintf(ficrespij,"\n");
5951: }
5952: /*}*/
5953: }
5954: return 0;
5955: }
5956:
5957:
5958: /***********************************************/
5959: /**************** Main Program *****************/
5960: /***********************************************/
5961:
5962: int main(int argc, char *argv[])
5963: {
5964: #ifdef GSL
5965: const gsl_multimin_fminimizer_type *T;
5966: size_t iteri = 0, it;
5967: int rval = GSL_CONTINUE;
5968: int status = GSL_SUCCESS;
5969: double ssval;
5970: #endif
5971: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5972: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5973:
5974: int jj, ll, li, lj, lk;
5975: int numlinepar=0; /* Current linenumber of parameter file */
5976: int itimes;
5977: int NDIM=2;
5978: int vpopbased=0;
5979:
5980: char ca[32], cb[32];
5981: /* FILE *fichtm; *//* Html File */
5982: /* FILE *ficgp;*/ /*Gnuplot File */
5983: struct stat info;
5984: double agedeb;
5985: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5986:
5987: double fret;
5988: double dum; /* Dummy variable */
5989: double ***p3mat;
5990: double ***mobaverage;
5991:
5992: char line[MAXLINE];
5993: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5994: char pathr[MAXLINE], pathimach[MAXLINE];
5995: char *tok, *val; /* pathtot */
5996: int firstobs=1, lastobs=10;
5997: int c, h , cpt;
5998: int jl;
5999: int i1, j1, jk, stepsize;
6000: int *tab;
6001: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6002: int mobilav=0,popforecast=0;
6003: int hstepm, nhstepm;
6004: int agemortsup;
6005: float sumlpop=0.;
6006: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6007: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6008:
6009: double bage=0, fage=110, age, agelim, agebase;
6010: double ftolpl=FTOL;
6011: double **prlim;
6012: double ***param; /* Matrix of parameters */
6013: double *p;
6014: double **matcov; /* Matrix of covariance */
6015: double ***delti3; /* Scale */
6016: double *delti; /* Scale */
6017: double ***eij, ***vareij;
6018: double **varpl; /* Variances of prevalence limits by age */
6019: double *epj, vepp;
6020:
6021: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6022: double **ximort;
6023: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
6024: int *dcwave;
6025:
6026: char z[1]="c";
6027:
6028: /*char *strt;*/
6029: char strtend[80];
6030:
6031:
6032: /* setlocale (LC_ALL, ""); */
6033: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6034: /* textdomain (PACKAGE); */
6035: /* setlocale (LC_CTYPE, ""); */
6036: /* setlocale (LC_MESSAGES, ""); */
6037:
6038: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
6039: rstart_time = time(NULL);
6040: /* (void) gettimeofday(&start_time,&tzp);*/
6041: start_time = *localtime(&rstart_time);
6042: curr_time=start_time;
6043: /*tml = *localtime(&start_time.tm_sec);*/
6044: /* strcpy(strstart,asctime(&tml)); */
6045: strcpy(strstart,asctime(&start_time));
6046:
6047: /* printf("Localtime (at start)=%s",strstart); */
6048: /* tp.tm_sec = tp.tm_sec +86400; */
6049: /* tm = *localtime(&start_time.tm_sec); */
6050: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6051: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6052: /* tmg.tm_hour=tmg.tm_hour + 1; */
6053: /* tp.tm_sec = mktime(&tmg); */
6054: /* strt=asctime(&tmg); */
6055: /* printf("Time(after) =%s",strstart); */
6056: /* (void) time (&time_value);
6057: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6058: * tm = *localtime(&time_value);
6059: * strstart=asctime(&tm);
6060: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6061: */
6062:
6063: nberr=0; /* Number of errors and warnings */
6064: nbwarn=0;
6065: #ifdef WIN32
6066: _getcwd(pathcd, size);
6067: #else
6068: getcwd(pathcd, size);
6069: #endif
6070:
6071: printf("\n%s\n%s",version,fullversion);
6072: if(argc <=1){
6073: printf("\nEnter the parameter file name: ");
6074: fgets(pathr,FILENAMELENGTH,stdin);
6075: i=strlen(pathr);
6076: if(pathr[i-1]=='\n')
6077: pathr[i-1]='\0';
6078: i=strlen(pathr);
6079: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6080: pathr[i-1]='\0';
6081: for (tok = pathr; tok != NULL; ){
6082: printf("Pathr |%s|\n",pathr);
6083: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6084: printf("val= |%s| pathr=%s\n",val,pathr);
6085: strcpy (pathtot, val);
6086: if(pathr[0] == '\0') break; /* Dirty */
6087: }
6088: }
6089: else{
6090: strcpy(pathtot,argv[1]);
6091: }
6092: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6093: /*cygwin_split_path(pathtot,path,optionfile);
6094: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6095: /* cutv(path,optionfile,pathtot,'\\');*/
6096:
6097: /* Split argv[0], imach program to get pathimach */
6098: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6099: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6100: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6101: /* strcpy(pathimach,argv[0]); */
6102: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6103: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6104: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6105: #ifdef WIN32
6106: _chdir(path); /* Can be a relative path */
6107: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6108: #else
6109: chdir(path); /* Can be a relative path */
6110: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6111: #endif
6112: printf("Current directory %s!\n",pathcd);
6113: strcpy(command,"mkdir ");
6114: strcat(command,optionfilefiname);
6115: if((outcmd=system(command)) != 0){
6116: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6117: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6118: /* fclose(ficlog); */
6119: /* exit(1); */
6120: }
6121: /* if((imk=mkdir(optionfilefiname))<0){ */
6122: /* perror("mkdir"); */
6123: /* } */
6124:
6125: /*-------- arguments in the command line --------*/
6126:
6127: /* Main Log file */
6128: strcat(filelog, optionfilefiname);
6129: strcat(filelog,".log"); /* */
6130: if((ficlog=fopen(filelog,"w"))==NULL) {
6131: printf("Problem with logfile %s\n",filelog);
6132: goto end;
6133: }
6134: fprintf(ficlog,"Log filename:%s\n",filelog);
6135: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6136: fprintf(ficlog,"\nEnter the parameter file name: \n");
6137: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6138: path=%s \n\
6139: optionfile=%s\n\
6140: optionfilext=%s\n\
6141: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6142:
6143: syscompilerinfo();
6144:
6145: printf("Local time (at start):%s",strstart);
6146: fprintf(ficlog,"Local time (at start): %s",strstart);
6147: fflush(ficlog);
6148: /* (void) gettimeofday(&curr_time,&tzp); */
6149: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6150:
6151: /* */
6152: strcpy(fileres,"r");
6153: strcat(fileres, optionfilefiname);
6154: strcat(fileres,".txt"); /* Other files have txt extension */
6155:
6156: /* Main ---------arguments file --------*/
6157:
6158: if((ficpar=fopen(optionfile,"r"))==NULL) {
6159: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6160: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6161: fflush(ficlog);
6162: /* goto end; */
6163: exit(70);
6164: }
6165:
6166:
6167:
6168: strcpy(filereso,"o");
6169: strcat(filereso,fileres);
6170: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6171: printf("Problem with Output resultfile: %s\n", filereso);
6172: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6173: fflush(ficlog);
6174: goto end;
6175: }
6176:
6177: /* Reads comments: lines beginning with '#' */
6178: numlinepar=0;
6179: while((c=getc(ficpar))=='#' && c!= EOF){
6180: ungetc(c,ficpar);
6181: fgets(line, MAXLINE, ficpar);
6182: numlinepar++;
6183: fputs(line,stdout);
6184: fputs(line,ficparo);
6185: fputs(line,ficlog);
6186: }
6187: ungetc(c,ficpar);
6188:
6189: 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=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
6190: numlinepar++;
6191: /* 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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
6192: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n",title, datafile, lastobs, firstpass,lastpass);
6193: /*
6194:
6195:
6196:
6197: */
6198: printf("\nftol=%e \n", ftol);
6199: printf("stepm=%d \n", stepm);
6200: printf("ncovcol=%d nlstate=%d \n", ncovcol, nlstate);
6201: printf("ndeath=%d maxwav=%d mle=%d weight=%d\n", ndeath, maxwav, mle, weightopt);
6202: printf("model=%s\n",model);
6203: 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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6204: 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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6205: fflush(ficlog);
6206: while((c=getc(ficpar))=='#' && c!= EOF){
6207: ungetc(c,ficpar);
6208: fgets(line, MAXLINE, ficpar);
6209: numlinepar++;
6210: fputs(line, stdout);
6211: //puts(line);
6212: fputs(line,ficparo);
6213: fputs(line,ficlog);
6214: }
6215: ungetc(c,ficpar);
6216:
6217:
6218: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6219: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6220: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6221: v1+v2*age+v2*v3 makes cptcovn = 3
6222: */
6223: if (strlen(model)>1)
6224: 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*/
6225: else
6226: ncovmodel=2;
6227: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
6228: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6229: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6230: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6231: 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);
6232: 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);
6233: fflush(stdout);
6234: fclose (ficlog);
6235: goto end;
6236: }
6237: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6238: delti=delti3[1][1];
6239: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6240: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6241: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6242: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6243: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6244: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6245: fclose (ficparo);
6246: fclose (ficlog);
6247: goto end;
6248: exit(0);
6249: }
6250: else if(mle==-3) { /* Main Wizard */
6251: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6252: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6253: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6254: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6255: matcov=matrix(1,npar,1,npar);
6256: }
6257: else{
6258: /* Read guessed parameters */
6259: /* Reads comments: lines beginning with '#' */
6260: while((c=getc(ficpar))=='#' && c!= EOF){
6261: ungetc(c,ficpar);
6262: fgets(line, MAXLINE, ficpar);
6263: numlinepar++;
6264: fputs(line,stdout);
6265: fputs(line,ficparo);
6266: fputs(line,ficlog);
6267: }
6268: ungetc(c,ficpar);
6269:
6270: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6271: for(i=1; i <=nlstate; i++){
6272: j=0;
6273: for(jj=1; jj <=nlstate+ndeath; jj++){
6274: if(jj==i) continue;
6275: j++;
6276: fscanf(ficpar,"%1d%1d",&i1,&j1);
6277: if ((i1 != i) && (j1 != j)){
6278: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6279: It might be a problem of design; if ncovcol and the model are correct\n \
6280: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6281: exit(1);
6282: }
6283: fprintf(ficparo,"%1d%1d",i1,j1);
6284: if(mle==1)
6285: printf("%1d%1d",i,j);
6286: fprintf(ficlog,"%1d%1d",i,j);
6287: for(k=1; k<=ncovmodel;k++){
6288: fscanf(ficpar," %lf",¶m[i][j][k]);
6289: if(mle==1){
6290: printf(" %lf",param[i][j][k]);
6291: fprintf(ficlog," %lf",param[i][j][k]);
6292: }
6293: else
6294: fprintf(ficlog," %lf",param[i][j][k]);
6295: fprintf(ficparo," %lf",param[i][j][k]);
6296: }
6297: fscanf(ficpar,"\n");
6298: numlinepar++;
6299: if(mle==1)
6300: printf("\n");
6301: fprintf(ficlog,"\n");
6302: fprintf(ficparo,"\n");
6303: }
6304: }
6305: fflush(ficlog);
6306:
6307: /* Reads scales values */
6308: p=param[1][1];
6309:
6310: /* Reads comments: lines beginning with '#' */
6311: while((c=getc(ficpar))=='#' && c!= EOF){
6312: ungetc(c,ficpar);
6313: fgets(line, MAXLINE, ficpar);
6314: numlinepar++;
6315: fputs(line,stdout);
6316: fputs(line,ficparo);
6317: fputs(line,ficlog);
6318: }
6319: ungetc(c,ficpar);
6320:
6321: for(i=1; i <=nlstate; i++){
6322: for(j=1; j <=nlstate+ndeath-1; j++){
6323: fscanf(ficpar,"%1d%1d",&i1,&j1);
6324: if ( (i1-i) * (j1-j) != 0){
6325: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6326: exit(1);
6327: }
6328: printf("%1d%1d",i,j);
6329: fprintf(ficparo,"%1d%1d",i1,j1);
6330: fprintf(ficlog,"%1d%1d",i1,j1);
6331: for(k=1; k<=ncovmodel;k++){
6332: fscanf(ficpar,"%le",&delti3[i][j][k]);
6333: printf(" %le",delti3[i][j][k]);
6334: fprintf(ficparo," %le",delti3[i][j][k]);
6335: fprintf(ficlog," %le",delti3[i][j][k]);
6336: }
6337: fscanf(ficpar,"\n");
6338: numlinepar++;
6339: printf("\n");
6340: fprintf(ficparo,"\n");
6341: fprintf(ficlog,"\n");
6342: }
6343: }
6344: fflush(ficlog);
6345:
6346: /* Reads covariance matrix */
6347: delti=delti3[1][1];
6348:
6349:
6350: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6351:
6352: /* Reads comments: lines beginning with '#' */
6353: while((c=getc(ficpar))=='#' && c!= EOF){
6354: ungetc(c,ficpar);
6355: fgets(line, MAXLINE, ficpar);
6356: numlinepar++;
6357: fputs(line,stdout);
6358: fputs(line,ficparo);
6359: fputs(line,ficlog);
6360: }
6361: ungetc(c,ficpar);
6362:
6363: matcov=matrix(1,npar,1,npar);
6364: for(i=1; i <=npar; i++)
6365: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6366:
6367: for(i=1; i <=npar; i++){
6368: fscanf(ficpar,"%s",str);
6369: if(mle==1)
6370: printf("%s",str);
6371: fprintf(ficlog,"%s",str);
6372: fprintf(ficparo,"%s",str);
6373: for(j=1; j <=i; j++){
6374: fscanf(ficpar," %le",&matcov[i][j]);
6375: if(mle==1){
6376: printf(" %.5le",matcov[i][j]);
6377: }
6378: fprintf(ficlog," %.5le",matcov[i][j]);
6379: fprintf(ficparo," %.5le",matcov[i][j]);
6380: }
6381: fscanf(ficpar,"\n");
6382: numlinepar++;
6383: if(mle==1)
6384: printf("\n");
6385: fprintf(ficlog,"\n");
6386: fprintf(ficparo,"\n");
6387: }
6388: for(i=1; i <=npar; i++)
6389: for(j=i+1;j<=npar;j++)
6390: matcov[i][j]=matcov[j][i];
6391:
6392: if(mle==1)
6393: printf("\n");
6394: fprintf(ficlog,"\n");
6395:
6396: fflush(ficlog);
6397:
6398: /*-------- Rewriting parameter file ----------*/
6399: strcpy(rfileres,"r"); /* "Rparameterfile */
6400: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6401: strcat(rfileres,"."); /* */
6402: strcat(rfileres,optionfilext); /* Other files have txt extension */
6403: if((ficres =fopen(rfileres,"w"))==NULL) {
6404: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6405: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6406: }
6407: fprintf(ficres,"#%s\n",version);
6408: } /* End of mle != -3 */
6409:
6410: /* Main data
6411: */
6412: n= lastobs;
6413: num=lvector(1,n);
6414: moisnais=vector(1,n);
6415: annais=vector(1,n);
6416: moisdc=vector(1,n);
6417: andc=vector(1,n);
6418: agedc=vector(1,n);
6419: cod=ivector(1,n);
6420: weight=vector(1,n);
6421: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6422: mint=matrix(1,maxwav,1,n);
6423: anint=matrix(1,maxwav,1,n);
6424: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6425: tab=ivector(1,NCOVMAX);
6426: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6427:
6428: /* Reads data from file datafile */
6429: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6430: goto end;
6431:
6432: /* Calculation of the number of parameters from char model */
6433: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6434: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6435: k=3 V4 Tvar[k=3]= 4 (from V4)
6436: k=2 V1 Tvar[k=2]= 1 (from V1)
6437: k=1 Tvar[1]=2 (from V2)
6438: */
6439: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6440: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6441: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6442: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6443: */
6444: /* For model-covariate k tells which data-covariate to use but
6445: because this model-covariate is a construction we invent a new column
6446: ncovcol + k1
6447: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6448: Tvar[3=V1*V4]=4+1 etc */
6449: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6450: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6451: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6452: */
6453: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6454: 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
6455: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6456: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6457: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6458: 4 covariates (3 plus signs)
6459: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6460: */
6461:
6462: /* Main decodemodel */
6463:
6464: if(decodemodel(model, lastobs) == 1)
6465: goto end;
6466:
6467: if((double)(lastobs-imx)/(double)imx > 1.10){
6468: nbwarn++;
6469: 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);
6470: 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);
6471: }
6472: /* if(mle==1){*/
6473: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6474: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6475: }
6476:
6477: /*-calculation of age at interview from date of interview and age at death -*/
6478: agev=matrix(1,maxwav,1,imx);
6479:
6480: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6481: goto end;
6482:
6483:
6484: agegomp=(int)agemin;
6485: free_vector(moisnais,1,n);
6486: free_vector(annais,1,n);
6487: /* free_matrix(mint,1,maxwav,1,n);
6488: free_matrix(anint,1,maxwav,1,n);*/
6489: free_vector(moisdc,1,n);
6490: free_vector(andc,1,n);
6491: /* */
6492:
6493: wav=ivector(1,imx);
6494: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6495: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6496: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6497:
6498: /* Concatenates waves */
6499: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6500: /* */
6501:
6502: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6503:
6504: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6505: ncodemax[1]=1;
6506: Ndum =ivector(-1,NCOVMAX);
6507: if (ncovmodel > 2)
6508: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6509: /* Nbcode gives the value of the lth modality of jth covariate, in
6510: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6511: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
6512:
6513: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6514: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6515: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
6516: h=0;
6517:
6518:
6519: /*if (cptcovn > 0) */
6520:
6521:
6522: m=pow(2,cptcoveff);
6523:
6524: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6525: 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 */
6526: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6527: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6528: h++;
6529: if (h>m)
6530: h=1;
6531: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6532: * For k=4 covariates, h goes from 1 to 2**k
6533: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6534: * h\k 1 2 3 4
6535: *______________________________
6536: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6537: * 2 2 1 1 1
6538: * 3 i=2 1 2 1 1
6539: * 4 2 2 1 1
6540: * 5 i=3 1 i=2 1 2 1
6541: * 6 2 1 2 1
6542: * 7 i=4 1 2 2 1
6543: * 8 2 2 2 1
6544: * 9 i=5 1 i=3 1 i=2 1 1
6545: * 10 2 1 1 1
6546: * 11 i=6 1 2 1 1
6547: * 12 2 2 1 1
6548: * 13 i=7 1 i=4 1 2 1
6549: * 14 2 1 2 1
6550: * 15 i=8 1 2 2 1
6551: * 16 2 2 2 1
6552: */
6553: codtab[h][k]=j;
6554: /* codtab[12][3]=1; */
6555: /*codtab[h][Tvar[k]]=j;*/
6556: 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]]);
6557: }
6558: }
6559: }
6560: }
6561: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6562: codtab[1][2]=1;codtab[2][2]=2; */
6563: /* for(i=1; i <=m ;i++){
6564: for(k=1; k <=cptcovn; k++){
6565: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6566: }
6567: printf("\n");
6568: }
6569: scanf("%d",i);*/
6570:
6571: free_ivector(Ndum,-1,NCOVMAX);
6572:
6573:
6574:
6575: /* Initialisation of ----------- gnuplot -------------*/
6576: strcpy(optionfilegnuplot,optionfilefiname);
6577: if(mle==-3)
6578: strcat(optionfilegnuplot,"-mort");
6579: strcat(optionfilegnuplot,".gp");
6580:
6581: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6582: printf("Problem with file %s",optionfilegnuplot);
6583: }
6584: else{
6585: fprintf(ficgp,"\n# %s\n", version);
6586: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6587: //fprintf(ficgp,"set missing 'NaNq'\n");
6588: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6589: }
6590: /* fclose(ficgp);*/
6591:
6592:
6593: /* Initialisation of --------- index.htm --------*/
6594:
6595: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6596: if(mle==-3)
6597: strcat(optionfilehtm,"-mort");
6598: strcat(optionfilehtm,".htm");
6599: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6600: printf("Problem with %s \n",optionfilehtm);
6601: exit(0);
6602: }
6603:
6604: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6605: strcat(optionfilehtmcov,"-cov.htm");
6606: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6607: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6608: }
6609: else{
6610: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6611: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6612: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6613: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6614: }
6615:
6616: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6617: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6618: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6619: \n\
6620: <hr size=\"2\" color=\"#EC5E5E\">\
6621: <ul><li><h4>Parameter files</h4>\n\
6622: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6623: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6624: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6625: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6626: - Date and time at start: %s</ul>\n",\
6627: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6628: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6629: fileres,fileres,\
6630: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6631: fflush(fichtm);
6632:
6633: strcpy(pathr,path);
6634: strcat(pathr,optionfilefiname);
6635: #ifdef WIN32
6636: _chdir(optionfilefiname); /* Move to directory named optionfile */
6637: #else
6638: chdir(optionfilefiname); /* Move to directory named optionfile */
6639: #endif
6640:
6641:
6642: /* Calculates basic frequencies. Computes observed prevalence at single age
6643: and prints on file fileres'p'. */
6644: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6645:
6646: fprintf(fichtm,"\n");
6647: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6648: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6649: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6650: imx,agemin,agemax,jmin,jmax,jmean);
6651: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6652: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6653: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6654: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6655: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6656:
6657:
6658: /* For Powell, parameters are in a vector p[] starting at p[1]
6659: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6660: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6661:
6662: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6663: /* For mortality only */
6664: if (mle==-3){
6665: ximort=matrix(1,NDIM,1,NDIM);
6666: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6667: cens=ivector(1,n);
6668: ageexmed=vector(1,n);
6669: agecens=vector(1,n);
6670: dcwave=ivector(1,n);
6671:
6672: for (i=1; i<=imx; i++){
6673: dcwave[i]=-1;
6674: for (m=firstpass; m<=lastpass; m++)
6675: if (s[m][i]>nlstate) {
6676: dcwave[i]=m;
6677: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6678: break;
6679: }
6680: }
6681:
6682: for (i=1; i<=imx; i++) {
6683: if (wav[i]>0){
6684: ageexmed[i]=agev[mw[1][i]][i];
6685: j=wav[i];
6686: agecens[i]=1.;
6687:
6688: if (ageexmed[i]> 1 && wav[i] > 0){
6689: agecens[i]=agev[mw[j][i]][i];
6690: cens[i]= 1;
6691: }else if (ageexmed[i]< 1)
6692: cens[i]= -1;
6693: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6694: cens[i]=0 ;
6695: }
6696: else cens[i]=-1;
6697: }
6698:
6699: for (i=1;i<=NDIM;i++) {
6700: for (j=1;j<=NDIM;j++)
6701: ximort[i][j]=(i == j ? 1.0 : 0.0);
6702: }
6703:
6704: /*p[1]=0.0268; p[NDIM]=0.083;*/
6705: /*printf("%lf %lf", p[1], p[2]);*/
6706:
6707:
6708: #ifdef GSL
6709: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6710: #else
6711: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6712: #endif
6713: strcpy(filerespow,"pow-mort");
6714: strcat(filerespow,fileres);
6715: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6716: printf("Problem with resultfile: %s\n", filerespow);
6717: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6718: }
6719: #ifdef GSL
6720: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6721: #else
6722: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6723: #endif
6724: /* for (i=1;i<=nlstate;i++)
6725: for(j=1;j<=nlstate+ndeath;j++)
6726: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6727: */
6728: fprintf(ficrespow,"\n");
6729: #ifdef GSL
6730: /* gsl starts here */
6731: T = gsl_multimin_fminimizer_nmsimplex;
6732: gsl_multimin_fminimizer *sfm = NULL;
6733: gsl_vector *ss, *x;
6734: gsl_multimin_function minex_func;
6735:
6736: /* Initial vertex size vector */
6737: ss = gsl_vector_alloc (NDIM);
6738:
6739: if (ss == NULL){
6740: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6741: }
6742: /* Set all step sizes to 1 */
6743: gsl_vector_set_all (ss, 0.001);
6744:
6745: /* Starting point */
6746:
6747: x = gsl_vector_alloc (NDIM);
6748:
6749: if (x == NULL){
6750: gsl_vector_free(ss);
6751: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6752: }
6753:
6754: /* Initialize method and iterate */
6755: /* p[1]=0.0268; p[NDIM]=0.083; */
6756: /* gsl_vector_set(x, 0, 0.0268); */
6757: /* gsl_vector_set(x, 1, 0.083); */
6758: gsl_vector_set(x, 0, p[1]);
6759: gsl_vector_set(x, 1, p[2]);
6760:
6761: minex_func.f = &gompertz_f;
6762: minex_func.n = NDIM;
6763: minex_func.params = (void *)&p; /* ??? */
6764:
6765: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6766: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6767:
6768: printf("Iterations beginning .....\n\n");
6769: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6770:
6771: iteri=0;
6772: while (rval == GSL_CONTINUE){
6773: iteri++;
6774: status = gsl_multimin_fminimizer_iterate(sfm);
6775:
6776: if (status) printf("error: %s\n", gsl_strerror (status));
6777: fflush(0);
6778:
6779: if (status)
6780: break;
6781:
6782: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6783: ssval = gsl_multimin_fminimizer_size (sfm);
6784:
6785: if (rval == GSL_SUCCESS)
6786: printf ("converged to a local maximum at\n");
6787:
6788: printf("%5d ", iteri);
6789: for (it = 0; it < NDIM; it++){
6790: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6791: }
6792: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6793: }
6794:
6795: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6796:
6797: gsl_vector_free(x); /* initial values */
6798: gsl_vector_free(ss); /* inital step size */
6799: for (it=0; it<NDIM; it++){
6800: p[it+1]=gsl_vector_get(sfm->x,it);
6801: fprintf(ficrespow," %.12lf", p[it]);
6802: }
6803: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6804: #endif
6805: #ifdef POWELL
6806: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6807: #endif
6808: fclose(ficrespow);
6809:
6810: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6811:
6812: for(i=1; i <=NDIM; i++)
6813: for(j=i+1;j<=NDIM;j++)
6814: matcov[i][j]=matcov[j][i];
6815:
6816: printf("\nCovariance matrix\n ");
6817: for(i=1; i <=NDIM; i++) {
6818: for(j=1;j<=NDIM;j++){
6819: printf("%f ",matcov[i][j]);
6820: }
6821: printf("\n ");
6822: }
6823:
6824: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6825: for (i=1;i<=NDIM;i++)
6826: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6827:
6828: lsurv=vector(1,AGESUP);
6829: lpop=vector(1,AGESUP);
6830: tpop=vector(1,AGESUP);
6831: lsurv[agegomp]=100000;
6832:
6833: for (k=agegomp;k<=AGESUP;k++) {
6834: agemortsup=k;
6835: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6836: }
6837:
6838: for (k=agegomp;k<agemortsup;k++)
6839: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6840:
6841: for (k=agegomp;k<agemortsup;k++){
6842: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6843: sumlpop=sumlpop+lpop[k];
6844: }
6845:
6846: tpop[agegomp]=sumlpop;
6847: for (k=agegomp;k<(agemortsup-3);k++){
6848: /* tpop[k+1]=2;*/
6849: tpop[k+1]=tpop[k]-lpop[k];
6850: }
6851:
6852:
6853: printf("\nAge lx qx dx Lx Tx e(x)\n");
6854: for (k=agegomp;k<(agemortsup-2);k++)
6855: 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]);
6856:
6857:
6858: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6859: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6860:
6861: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6862: stepm, weightopt,\
6863: model,imx,p,matcov,agemortsup);
6864:
6865: free_vector(lsurv,1,AGESUP);
6866: free_vector(lpop,1,AGESUP);
6867: free_vector(tpop,1,AGESUP);
6868: #ifdef GSL
6869: free_ivector(cens,1,n);
6870: free_vector(agecens,1,n);
6871: free_ivector(dcwave,1,n);
6872: free_matrix(ximort,1,NDIM,1,NDIM);
6873: #endif
6874: } /* Endof if mle==-3 mortality only */
6875: /* Standard maximisation */
6876: else{ /* For mle >=1 */
6877: globpr=0;/* debug */
6878: /* Computes likelihood for initial parameters */
6879: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6880: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6881: for (k=1; k<=npar;k++)
6882: printf(" %d %8.5f",k,p[k]);
6883: printf("\n");
6884: globpr=1; /* again, to print the contributions */
6885: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6886: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6887: for (k=1; k<=npar;k++)
6888: printf(" %d %8.5f",k,p[k]);
6889: printf("\n");
6890: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
6891: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6892: }
6893:
6894: /*--------- results files --------------*/
6895: 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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
6896:
6897:
6898: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6899: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6900: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6901: for(i=1,jk=1; i <=nlstate; i++){
6902: for(k=1; k <=(nlstate+ndeath); k++){
6903: if (k != i) {
6904: printf("%d%d ",i,k);
6905: fprintf(ficlog,"%d%d ",i,k);
6906: fprintf(ficres,"%1d%1d ",i,k);
6907: for(j=1; j <=ncovmodel; j++){
6908: printf("%lf ",p[jk]);
6909: fprintf(ficlog,"%lf ",p[jk]);
6910: fprintf(ficres,"%lf ",p[jk]);
6911: jk++;
6912: }
6913: printf("\n");
6914: fprintf(ficlog,"\n");
6915: fprintf(ficres,"\n");
6916: }
6917: }
6918: }
6919: if(mle!=0){
6920: /* Computing hessian and covariance matrix */
6921: ftolhess=ftol; /* Usually correct */
6922: hesscov(matcov, p, npar, delti, ftolhess, func);
6923: }
6924: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6925: printf("# Scales (for hessian or gradient estimation)\n");
6926: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6927: for(i=1,jk=1; i <=nlstate; i++){
6928: for(j=1; j <=nlstate+ndeath; j++){
6929: if (j!=i) {
6930: fprintf(ficres,"%1d%1d",i,j);
6931: printf("%1d%1d",i,j);
6932: fprintf(ficlog,"%1d%1d",i,j);
6933: for(k=1; k<=ncovmodel;k++){
6934: printf(" %.5e",delti[jk]);
6935: fprintf(ficlog," %.5e",delti[jk]);
6936: fprintf(ficres," %.5e",delti[jk]);
6937: jk++;
6938: }
6939: printf("\n");
6940: fprintf(ficlog,"\n");
6941: fprintf(ficres,"\n");
6942: }
6943: }
6944: }
6945:
6946: 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");
6947: if(mle>=1)
6948: 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");
6949: 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");
6950: /* # 121 Var(a12)\n\ */
6951: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6952: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6953: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6954: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6955: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6956: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6957: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6958:
6959:
6960: /* Just to have a covariance matrix which will be more understandable
6961: even is we still don't want to manage dictionary of variables
6962: */
6963: for(itimes=1;itimes<=2;itimes++){
6964: jj=0;
6965: for(i=1; i <=nlstate; i++){
6966: for(j=1; j <=nlstate+ndeath; j++){
6967: if(j==i) continue;
6968: for(k=1; k<=ncovmodel;k++){
6969: jj++;
6970: ca[0]= k+'a'-1;ca[1]='\0';
6971: if(itimes==1){
6972: if(mle>=1)
6973: printf("#%1d%1d%d",i,j,k);
6974: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6975: fprintf(ficres,"#%1d%1d%d",i,j,k);
6976: }else{
6977: if(mle>=1)
6978: printf("%1d%1d%d",i,j,k);
6979: fprintf(ficlog,"%1d%1d%d",i,j,k);
6980: fprintf(ficres,"%1d%1d%d",i,j,k);
6981: }
6982: ll=0;
6983: for(li=1;li <=nlstate; li++){
6984: for(lj=1;lj <=nlstate+ndeath; lj++){
6985: if(lj==li) continue;
6986: for(lk=1;lk<=ncovmodel;lk++){
6987: ll++;
6988: if(ll<=jj){
6989: cb[0]= lk +'a'-1;cb[1]='\0';
6990: if(ll<jj){
6991: if(itimes==1){
6992: if(mle>=1)
6993: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6994: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6995: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6996: }else{
6997: if(mle>=1)
6998: printf(" %.5e",matcov[jj][ll]);
6999: fprintf(ficlog," %.5e",matcov[jj][ll]);
7000: fprintf(ficres," %.5e",matcov[jj][ll]);
7001: }
7002: }else{
7003: if(itimes==1){
7004: if(mle>=1)
7005: printf(" Var(%s%1d%1d)",ca,i,j);
7006: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7007: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7008: }else{
7009: if(mle>=1)
7010: printf(" %.5e",matcov[jj][ll]);
7011: fprintf(ficlog," %.5e",matcov[jj][ll]);
7012: fprintf(ficres," %.5e",matcov[jj][ll]);
7013: }
7014: }
7015: }
7016: } /* end lk */
7017: } /* end lj */
7018: } /* end li */
7019: if(mle>=1)
7020: printf("\n");
7021: fprintf(ficlog,"\n");
7022: fprintf(ficres,"\n");
7023: numlinepar++;
7024: } /* end k*/
7025: } /*end j */
7026: } /* end i */
7027: } /* end itimes */
7028:
7029: fflush(ficlog);
7030: fflush(ficres);
7031:
7032: while((c=getc(ficpar))=='#' && c!= EOF){
7033: ungetc(c,ficpar);
7034: fgets(line, MAXLINE, ficpar);
7035: fputs(line,stdout);
7036: fputs(line,ficparo);
7037: }
7038: ungetc(c,ficpar);
7039:
7040: estepm=0;
7041: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7042: if (estepm==0 || estepm < stepm) estepm=stepm;
7043: if (fage <= 2) {
7044: bage = ageminpar;
7045: fage = agemaxpar;
7046: }
7047:
7048: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7049: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7050: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7051:
7052: /* Other stuffs, more or less useful */
7053: while((c=getc(ficpar))=='#' && c!= EOF){
7054: ungetc(c,ficpar);
7055: fgets(line, MAXLINE, ficpar);
7056: fputs(line,stdout);
7057: fputs(line,ficparo);
7058: }
7059: ungetc(c,ficpar);
7060:
7061: 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);
7062: 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);
7063: 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);
7064: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7065: 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);
7066:
7067: while((c=getc(ficpar))=='#' && c!= EOF){
7068: ungetc(c,ficpar);
7069: fgets(line, MAXLINE, ficpar);
7070: fputs(line,stdout);
7071: fputs(line,ficparo);
7072: }
7073: ungetc(c,ficpar);
7074:
7075:
7076: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7077: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7078:
7079: fscanf(ficpar,"pop_based=%d\n",&popbased);
7080: fprintf(ficparo,"pop_based=%d\n",popbased);
7081: fprintf(ficres,"pop_based=%d\n",popbased);
7082:
7083: while((c=getc(ficpar))=='#' && c!= EOF){
7084: ungetc(c,ficpar);
7085: fgets(line, MAXLINE, ficpar);
7086: fputs(line,stdout);
7087: fputs(line,ficparo);
7088: }
7089: ungetc(c,ficpar);
7090:
7091: 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);
7092: 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);
7093: 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);
7094: 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);
7095: 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);
7096: /* day and month of proj2 are not used but only year anproj2.*/
7097:
7098:
7099:
7100: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7101: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
7102:
7103: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7104: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7105:
7106: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7107: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7108: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7109:
7110: /*------------ free_vector -------------*/
7111: /* chdir(path); */
7112:
7113: free_ivector(wav,1,imx);
7114: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7115: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7116: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7117: free_lvector(num,1,n);
7118: free_vector(agedc,1,n);
7119: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7120: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7121: fclose(ficparo);
7122: fclose(ficres);
7123:
7124:
7125: /* Other results (useful)*/
7126:
7127:
7128: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
7129: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7130: prlim=matrix(1,nlstate,1,nlstate);
7131: prevalence_limit(p, prlim, ageminpar, agemaxpar);
7132: fclose(ficrespl);
7133:
7134: #ifdef FREEEXIT2
7135: #include "freeexit2.h"
7136: #endif
7137:
7138: /*------------- h Pij x at various ages ------------*/
7139: /*#include "hpijx.h"*/
7140: hPijx(p, bage, fage);
7141: fclose(ficrespij);
7142:
7143: /*-------------- Variance of one-step probabilities---*/
7144: k=1;
7145: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7146:
7147:
7148: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7149: for(i=1;i<=AGESUP;i++)
7150: for(j=1;j<=NCOVMAX;j++)
7151: for(k=1;k<=NCOVMAX;k++)
7152: probs[i][j][k]=0.;
7153:
7154: /*---------- Forecasting ------------------*/
7155: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7156: if(prevfcast==1){
7157: /* if(stepm ==1){*/
7158: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7159: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7160: /* } */
7161: /* else{ */
7162: /* erreur=108; */
7163: /* 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); */
7164: /* 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); */
7165: /* } */
7166: }
7167:
7168: /* ------ Other prevalence ratios------------ */
7169:
7170: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7171:
7172: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7173: /* 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",\
7174: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7175: */
7176:
7177: if (mobilav!=0) {
7178: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7179: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7180: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7181: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7182: }
7183: }
7184:
7185:
7186: /*---------- Health expectancies, no variances ------------*/
7187:
7188: strcpy(filerese,"e");
7189: strcat(filerese,fileres);
7190: if((ficreseij=fopen(filerese,"w"))==NULL) {
7191: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7192: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7193: }
7194: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7195: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
7196: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7197: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7198:
7199: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7200: fprintf(ficreseij,"\n#****** ");
7201: for(j=1;j<=cptcoveff;j++) {
7202: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7203: }
7204: fprintf(ficreseij,"******\n");
7205:
7206: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7207: oldm=oldms;savm=savms;
7208: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7209:
7210: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7211: /*}*/
7212: }
7213: fclose(ficreseij);
7214:
7215:
7216: /*---------- Health expectancies and variances ------------*/
7217:
7218:
7219: strcpy(filerest,"t");
7220: strcat(filerest,fileres);
7221: if((ficrest=fopen(filerest,"w"))==NULL) {
7222: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7223: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7224: }
7225: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7226: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7227:
7228:
7229: strcpy(fileresstde,"stde");
7230: strcat(fileresstde,fileres);
7231: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7232: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7233: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7234: }
7235: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7236: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7237:
7238: strcpy(filerescve,"cve");
7239: strcat(filerescve,fileres);
7240: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7241: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7242: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7243: }
7244: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7245: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7246:
7247: strcpy(fileresv,"v");
7248: strcat(fileresv,fileres);
7249: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7250: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7251: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7252: }
7253: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7254: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7255:
7256: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7257: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7258:
7259: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7260: fprintf(ficrest,"\n#****** ");
7261: for(j=1;j<=cptcoveff;j++)
7262: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7263: fprintf(ficrest,"******\n");
7264:
7265: fprintf(ficresstdeij,"\n#****** ");
7266: fprintf(ficrescveij,"\n#****** ");
7267: for(j=1;j<=cptcoveff;j++) {
7268: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7269: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7270: }
7271: fprintf(ficresstdeij,"******\n");
7272: fprintf(ficrescveij,"******\n");
7273:
7274: fprintf(ficresvij,"\n#****** ");
7275: for(j=1;j<=cptcoveff;j++)
7276: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7277: fprintf(ficresvij,"******\n");
7278:
7279: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7280: oldm=oldms;savm=savms;
7281: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7282: /*
7283: */
7284: /* goto endfree; */
7285:
7286: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7287: pstamp(ficrest);
7288:
7289:
7290: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7291: oldm=oldms;savm=savms; /* Segmentation fault */
7292: cptcod= 0; /* To be deleted */
7293: 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 */
7294: 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 ");
7295: if(vpopbased==1)
7296: 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);
7297: else
7298: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7299: fprintf(ficrest,"# Age e.. (std) ");
7300: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7301: fprintf(ficrest,"\n");
7302:
7303: epj=vector(1,nlstate+1);
7304: for(age=bage; age <=fage ;age++){
7305: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7306: if (vpopbased==1) {
7307: if(mobilav ==0){
7308: for(i=1; i<=nlstate;i++)
7309: prlim[i][i]=probs[(int)age][i][k];
7310: }else{ /* mobilav */
7311: for(i=1; i<=nlstate;i++)
7312: prlim[i][i]=mobaverage[(int)age][i][k];
7313: }
7314: }
7315:
7316: fprintf(ficrest," %4.0f",age);
7317: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7318: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7319: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7320: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7321: }
7322: epj[nlstate+1] +=epj[j];
7323: }
7324:
7325: for(i=1, vepp=0.;i <=nlstate;i++)
7326: for(j=1;j <=nlstate;j++)
7327: vepp += vareij[i][j][(int)age];
7328: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7329: for(j=1;j <=nlstate;j++){
7330: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7331: }
7332: fprintf(ficrest,"\n");
7333: }
7334: }
7335: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7336: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7337: free_vector(epj,1,nlstate+1);
7338: /*}*/
7339: }
7340: free_vector(weight,1,n);
7341: free_imatrix(Tvard,1,NCOVMAX,1,2);
7342: free_imatrix(s,1,maxwav+1,1,n);
7343: free_matrix(anint,1,maxwav,1,n);
7344: free_matrix(mint,1,maxwav,1,n);
7345: free_ivector(cod,1,n);
7346: free_ivector(tab,1,NCOVMAX);
7347: fclose(ficresstdeij);
7348: fclose(ficrescveij);
7349: fclose(ficresvij);
7350: fclose(ficrest);
7351: fclose(ficpar);
7352:
7353: /*------- Variance of period (stable) prevalence------*/
7354:
7355: strcpy(fileresvpl,"vpl");
7356: strcat(fileresvpl,fileres);
7357: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7358: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7359: exit(0);
7360: }
7361: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7362:
7363: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7364: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7365:
7366: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7367: fprintf(ficresvpl,"\n#****** ");
7368: for(j=1;j<=cptcoveff;j++)
7369: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7370: fprintf(ficresvpl,"******\n");
7371:
7372: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7373: oldm=oldms;savm=savms;
7374: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7375: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7376: /*}*/
7377: }
7378:
7379: fclose(ficresvpl);
7380:
7381: /*---------- End : free ----------------*/
7382: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7383: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7384: } /* mle==-3 arrives here for freeing */
7385: /* endfree:*/
7386: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7387: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7388: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7389: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7390: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7391: free_matrix(covar,0,NCOVMAX,1,n);
7392: free_matrix(matcov,1,npar,1,npar);
7393: /*free_vector(delti,1,npar);*/
7394: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7395: free_matrix(agev,1,maxwav,1,imx);
7396: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7397:
7398: free_ivector(ncodemax,1,NCOVMAX);
7399: free_ivector(Tvar,1,NCOVMAX);
7400: free_ivector(Tprod,1,NCOVMAX);
7401: free_ivector(Tvaraff,1,NCOVMAX);
7402: free_ivector(Tage,1,NCOVMAX);
7403:
7404: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7405: free_imatrix(codtab,1,100,1,10);
7406: fflush(fichtm);
7407: fflush(ficgp);
7408:
7409:
7410: if((nberr >0) || (nbwarn>0)){
7411: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7412: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7413: }else{
7414: printf("End of Imach\n");
7415: fprintf(ficlog,"End of Imach\n");
7416: }
7417: printf("See log file on %s\n",filelog);
7418: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7419: /*(void) gettimeofday(&end_time,&tzp);*/
7420: rend_time = time(NULL);
7421: end_time = *localtime(&rend_time);
7422: /* tml = *localtime(&end_time.tm_sec); */
7423: strcpy(strtend,asctime(&end_time));
7424: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7425: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7426: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7427:
7428: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7429: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7430: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7431: /* printf("Total time was %d uSec.\n", total_usecs);*/
7432: /* if(fileappend(fichtm,optionfilehtm)){ */
7433: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7434: fclose(fichtm);
7435: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7436: fclose(fichtmcov);
7437: fclose(ficgp);
7438: fclose(ficlog);
7439: /*------ End -----------*/
7440:
7441:
7442: printf("Before Current directory %s!\n",pathcd);
7443: #ifdef WIN32
7444: if (_chdir(pathcd) != 0)
7445: printf("Can't move to directory %s!\n",path);
7446: if(_getcwd(pathcd,MAXLINE) > 0)
7447: #else
7448: if(chdir(pathcd) != 0)
7449: printf("Can't move to directory %s!\n", path);
7450: if (getcwd(pathcd, MAXLINE) > 0)
7451: #endif
7452: printf("Current directory %s!\n",pathcd);
7453: /*strcat(plotcmd,CHARSEPARATOR);*/
7454: sprintf(plotcmd,"gnuplot");
7455: #ifdef _WIN32
7456: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7457: #endif
7458: if(!stat(plotcmd,&info)){
7459: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7460: if(!stat(getenv("GNUPLOTBIN"),&info)){
7461: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7462: }else
7463: strcpy(pplotcmd,plotcmd);
7464: #ifdef __unix
7465: strcpy(plotcmd,GNUPLOTPROGRAM);
7466: if(!stat(plotcmd,&info)){
7467: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7468: }else
7469: strcpy(pplotcmd,plotcmd);
7470: #endif
7471: }else
7472: strcpy(pplotcmd,plotcmd);
7473:
7474: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7475: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7476:
7477: if((outcmd=system(plotcmd)) != 0){
7478: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7479: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7480: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7481: if((outcmd=system(plotcmd)) != 0)
7482: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7483: }
7484: printf(" Successful, please wait...");
7485: while (z[0] != 'q') {
7486: /* chdir(path); */
7487: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7488: scanf("%s",z);
7489: /* if (z[0] == 'c') system("./imach"); */
7490: if (z[0] == 'e') {
7491: #ifdef __APPLE__
7492: sprintf(pplotcmd, "open %s", optionfilehtm);
7493: #elif __linux
7494: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7495: #else
7496: sprintf(pplotcmd, "%s", optionfilehtm);
7497: #endif
7498: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7499: system(pplotcmd);
7500: }
7501: else if (z[0] == 'g') system(plotcmd);
7502: else if (z[0] == 'q') exit(0);
7503: }
7504: end:
7505: while (z[0] != 'q') {
7506: printf("\nType q for exiting: ");
7507: scanf("%s",z);
7508: }
7509: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>