1: /* $Id: imach.c,v 1.205 2015/10/23 15:50:53 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.205 2015/10/23 15:50:53 brouard
5: Summary: 0.98r3 some clarification for graphs on likelihood contributions
6:
7: Revision 1.204 2015/10/01 16:20:26 brouard
8: Summary: Some new graphs of contribution to likelihood
9:
10: Revision 1.203 2015/09/30 17:45:14 brouard
11: Summary: looking at better estimation of the hessian
12:
13: Also a better criteria for convergence to the period prevalence And
14: therefore adding the number of years needed to converge. (The
15: prevalence in any alive state shold sum to one
16:
17: Revision 1.202 2015/09/22 19:45:16 brouard
18: Summary: Adding some overall graph on contribution to likelihood. Might change
19:
20: Revision 1.201 2015/09/15 17:34:58 brouard
21: Summary: 0.98r0
22:
23: - Some new graphs like suvival functions
24: - Some bugs fixed like model=1+age+V2.
25:
26: Revision 1.200 2015/09/09 16:53:55 brouard
27: Summary: Big bug thanks to Flavia
28:
29: Even model=1+age+V2. did not work anymore
30:
31: Revision 1.199 2015/09/07 14:09:23 brouard
32: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
33:
34: Revision 1.198 2015/09/03 07:14:39 brouard
35: Summary: 0.98q5 Flavia
36:
37: Revision 1.197 2015/09/01 18:24:39 brouard
38: *** empty log message ***
39:
40: Revision 1.196 2015/08/18 23:17:52 brouard
41: Summary: 0.98q5
42:
43: Revision 1.195 2015/08/18 16:28:39 brouard
44: Summary: Adding a hack for testing purpose
45:
46: After reading the title, ftol and model lines, if the comment line has
47: a q, starting with #q, the answer at the end of the run is quit. It
48: permits to run test files in batch with ctest. The former workaround was
49: $ echo q | imach foo.imach
50:
51: Revision 1.194 2015/08/18 13:32:00 brouard
52: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
53:
54: Revision 1.193 2015/08/04 07:17:42 brouard
55: Summary: 0.98q4
56:
57: Revision 1.192 2015/07/16 16:49:02 brouard
58: Summary: Fixing some outputs
59:
60: Revision 1.191 2015/07/14 10:00:33 brouard
61: Summary: Some fixes
62:
63: Revision 1.190 2015/05/05 08:51:13 brouard
64: Summary: Adding digits in output parameters (7 digits instead of 6)
65:
66: Fix 1+age+.
67:
68: Revision 1.189 2015/04/30 14:45:16 brouard
69: Summary: 0.98q2
70:
71: Revision 1.188 2015/04/30 08:27:53 brouard
72: *** empty log message ***
73:
74: Revision 1.187 2015/04/29 09:11:15 brouard
75: *** empty log message ***
76:
77: Revision 1.186 2015/04/23 12:01:52 brouard
78: Summary: V1*age is working now, version 0.98q1
79:
80: Some codes had been disabled in order to simplify and Vn*age was
81: working in the optimization phase, ie, giving correct MLE parameters,
82: but, as usual, outputs were not correct and program core dumped.
83:
84: Revision 1.185 2015/03/11 13:26:42 brouard
85: Summary: Inclusion of compile and links command line for Intel Compiler
86:
87: Revision 1.184 2015/03/11 11:52:39 brouard
88: Summary: Back from Windows 8. Intel Compiler
89:
90: Revision 1.183 2015/03/10 20:34:32 brouard
91: Summary: 0.98q0, trying with directest, mnbrak fixed
92:
93: We use directest instead of original Powell test; probably no
94: incidence on the results, but better justifications;
95: We fixed Numerical Recipes mnbrak routine which was wrong and gave
96: wrong results.
97:
98: Revision 1.182 2015/02/12 08:19:57 brouard
99: Summary: Trying to keep directest which seems simpler and more general
100: Author: Nicolas Brouard
101:
102: Revision 1.181 2015/02/11 23:22:24 brouard
103: Summary: Comments on Powell added
104:
105: Author:
106:
107: Revision 1.180 2015/02/11 17:33:45 brouard
108: Summary: Finishing move from main to function (hpijx and prevalence_limit)
109:
110: Revision 1.179 2015/01/04 09:57:06 brouard
111: Summary: back to OS/X
112:
113: Revision 1.178 2015/01/04 09:35:48 brouard
114: *** empty log message ***
115:
116: Revision 1.177 2015/01/03 18:40:56 brouard
117: Summary: Still testing ilc32 on OSX
118:
119: Revision 1.176 2015/01/03 16:45:04 brouard
120: *** empty log message ***
121:
122: Revision 1.175 2015/01/03 16:33:42 brouard
123: *** empty log message ***
124:
125: Revision 1.174 2015/01/03 16:15:49 brouard
126: Summary: Still in cross-compilation
127:
128: Revision 1.173 2015/01/03 12:06:26 brouard
129: Summary: trying to detect cross-compilation
130:
131: Revision 1.172 2014/12/27 12:07:47 brouard
132: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
133:
134: Revision 1.171 2014/12/23 13:26:59 brouard
135: Summary: Back from Visual C
136:
137: Still problem with utsname.h on Windows
138:
139: Revision 1.170 2014/12/23 11:17:12 brouard
140: Summary: Cleaning some \%% back to %%
141:
142: The escape was mandatory for a specific compiler (which one?), but too many warnings.
143:
144: Revision 1.169 2014/12/22 23:08:31 brouard
145: Summary: 0.98p
146:
147: Outputs some informations on compiler used, OS etc. Testing on different platforms.
148:
149: Revision 1.168 2014/12/22 15:17:42 brouard
150: Summary: update
151:
152: Revision 1.167 2014/12/22 13:50:56 brouard
153: Summary: Testing uname and compiler version and if compiled 32 or 64
154:
155: Testing on Linux 64
156:
157: Revision 1.166 2014/12/22 11:40:47 brouard
158: *** empty log message ***
159:
160: Revision 1.165 2014/12/16 11:20:36 brouard
161: Summary: After compiling on Visual C
162:
163: * imach.c (Module): Merging 1.61 to 1.162
164:
165: Revision 1.164 2014/12/16 10:52:11 brouard
166: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
167:
168: * imach.c (Module): Merging 1.61 to 1.162
169:
170: Revision 1.163 2014/12/16 10:30:11 brouard
171: * imach.c (Module): Merging 1.61 to 1.162
172:
173: Revision 1.162 2014/09/25 11:43:39 brouard
174: Summary: temporary backup 0.99!
175:
176: Revision 1.1 2014/09/16 11:06:58 brouard
177: Summary: With some code (wrong) for nlopt
178:
179: Author:
180:
181: Revision 1.161 2014/09/15 20:41:41 brouard
182: Summary: Problem with macro SQR on Intel compiler
183:
184: Revision 1.160 2014/09/02 09:24:05 brouard
185: *** empty log message ***
186:
187: Revision 1.159 2014/09/01 10:34:10 brouard
188: Summary: WIN32
189: Author: Brouard
190:
191: Revision 1.158 2014/08/27 17:11:51 brouard
192: *** empty log message ***
193:
194: Revision 1.157 2014/08/27 16:26:55 brouard
195: Summary: Preparing windows Visual studio version
196: Author: Brouard
197:
198: In order to compile on Visual studio, time.h is now correct and time_t
199: and tm struct should be used. difftime should be used but sometimes I
200: just make the differences in raw time format (time(&now).
201: Trying to suppress #ifdef LINUX
202: Add xdg-open for __linux in order to open default browser.
203:
204: Revision 1.156 2014/08/25 20:10:10 brouard
205: *** empty log message ***
206:
207: Revision 1.155 2014/08/25 18:32:34 brouard
208: Summary: New compile, minor changes
209: Author: Brouard
210:
211: Revision 1.154 2014/06/20 17:32:08 brouard
212: Summary: Outputs now all graphs of convergence to period prevalence
213:
214: Revision 1.153 2014/06/20 16:45:46 brouard
215: Summary: If 3 live state, convergence to period prevalence on same graph
216: Author: Brouard
217:
218: Revision 1.152 2014/06/18 17:54:09 brouard
219: Summary: open browser, use gnuplot on same dir than imach if not found in the path
220:
221: Revision 1.151 2014/06/18 16:43:30 brouard
222: *** empty log message ***
223:
224: Revision 1.150 2014/06/18 16:42:35 brouard
225: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
226: Author: brouard
227:
228: Revision 1.149 2014/06/18 15:51:14 brouard
229: Summary: Some fixes in parameter files errors
230: Author: Nicolas Brouard
231:
232: Revision 1.148 2014/06/17 17:38:48 brouard
233: Summary: Nothing new
234: Author: Brouard
235:
236: Just a new packaging for OS/X version 0.98nS
237:
238: Revision 1.147 2014/06/16 10:33:11 brouard
239: *** empty log message ***
240:
241: Revision 1.146 2014/06/16 10:20:28 brouard
242: Summary: Merge
243: Author: Brouard
244:
245: Merge, before building revised version.
246:
247: Revision 1.145 2014/06/10 21:23:15 brouard
248: Summary: Debugging with valgrind
249: Author: Nicolas Brouard
250:
251: Lot of changes in order to output the results with some covariates
252: After the Edimburgh REVES conference 2014, it seems mandatory to
253: improve the code.
254: No more memory valgrind error but a lot has to be done in order to
255: continue the work of splitting the code into subroutines.
256: Also, decodemodel has been improved. Tricode is still not
257: optimal. nbcode should be improved. Documentation has been added in
258: the source code.
259:
260: Revision 1.143 2014/01/26 09:45:38 brouard
261: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
262:
263: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
264: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
265:
266: Revision 1.142 2014/01/26 03:57:36 brouard
267: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
268:
269: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
270:
271: Revision 1.141 2014/01/26 02:42:01 brouard
272: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
273:
274: Revision 1.140 2011/09/02 10:37:54 brouard
275: Summary: times.h is ok with mingw32 now.
276:
277: Revision 1.139 2010/06/14 07:50:17 brouard
278: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
279: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
280:
281: Revision 1.138 2010/04/30 18:19:40 brouard
282: *** empty log message ***
283:
284: Revision 1.137 2010/04/29 18:11:38 brouard
285: (Module): Checking covariates for more complex models
286: than V1+V2. A lot of change to be done. Unstable.
287:
288: Revision 1.136 2010/04/26 20:30:53 brouard
289: (Module): merging some libgsl code. Fixing computation
290: of likelione (using inter/intrapolation if mle = 0) in order to
291: get same likelihood as if mle=1.
292: Some cleaning of code and comments added.
293:
294: Revision 1.135 2009/10/29 15:33:14 brouard
295: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
296:
297: Revision 1.134 2009/10/29 13:18:53 brouard
298: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
299:
300: Revision 1.133 2009/07/06 10:21:25 brouard
301: just nforces
302:
303: Revision 1.132 2009/07/06 08:22:05 brouard
304: Many tings
305:
306: Revision 1.131 2009/06/20 16:22:47 brouard
307: Some dimensions resccaled
308:
309: Revision 1.130 2009/05/26 06:44:34 brouard
310: (Module): Max Covariate is now set to 20 instead of 8. A
311: lot of cleaning with variables initialized to 0. Trying to make
312: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
313:
314: Revision 1.129 2007/08/31 13:49:27 lievre
315: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
316:
317: Revision 1.128 2006/06/30 13:02:05 brouard
318: (Module): Clarifications on computing e.j
319:
320: Revision 1.127 2006/04/28 18:11:50 brouard
321: (Module): Yes the sum of survivors was wrong since
322: imach-114 because nhstepm was no more computed in the age
323: loop. Now we define nhstepma in the age loop.
324: (Module): In order to speed up (in case of numerous covariates) we
325: compute health expectancies (without variances) in a first step
326: and then all the health expectancies with variances or standard
327: deviation (needs data from the Hessian matrices) which slows the
328: computation.
329: In the future we should be able to stop the program is only health
330: expectancies and graph are needed without standard deviations.
331:
332: Revision 1.126 2006/04/28 17:23:28 brouard
333: (Module): Yes the sum of survivors was wrong since
334: imach-114 because nhstepm was no more computed in the age
335: loop. Now we define nhstepma in the age loop.
336: Version 0.98h
337:
338: Revision 1.125 2006/04/04 15:20:31 lievre
339: Errors in calculation of health expectancies. Age was not initialized.
340: Forecasting file added.
341:
342: Revision 1.124 2006/03/22 17:13:53 lievre
343: Parameters are printed with %lf instead of %f (more numbers after the comma).
344: The log-likelihood is printed in the log file
345:
346: Revision 1.123 2006/03/20 10:52:43 brouard
347: * imach.c (Module): <title> changed, corresponds to .htm file
348: name. <head> headers where missing.
349:
350: * imach.c (Module): Weights can have a decimal point as for
351: English (a comma might work with a correct LC_NUMERIC environment,
352: otherwise the weight is truncated).
353: Modification of warning when the covariates values are not 0 or
354: 1.
355: Version 0.98g
356:
357: Revision 1.122 2006/03/20 09:45:41 brouard
358: (Module): Weights can have a decimal point as for
359: English (a comma might work with a correct LC_NUMERIC environment,
360: otherwise the weight is truncated).
361: Modification of warning when the covariates values are not 0 or
362: 1.
363: Version 0.98g
364:
365: Revision 1.121 2006/03/16 17:45:01 lievre
366: * imach.c (Module): Comments concerning covariates added
367:
368: * imach.c (Module): refinements in the computation of lli if
369: status=-2 in order to have more reliable computation if stepm is
370: not 1 month. Version 0.98f
371:
372: Revision 1.120 2006/03/16 15:10:38 lievre
373: (Module): refinements in the computation of lli if
374: status=-2 in order to have more reliable computation if stepm is
375: not 1 month. Version 0.98f
376:
377: Revision 1.119 2006/03/15 17:42:26 brouard
378: (Module): Bug if status = -2, the loglikelihood was
379: computed as likelihood omitting the logarithm. Version O.98e
380:
381: Revision 1.118 2006/03/14 18:20:07 brouard
382: (Module): varevsij Comments added explaining the second
383: table of variances if popbased=1 .
384: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
385: (Module): Function pstamp added
386: (Module): Version 0.98d
387:
388: Revision 1.117 2006/03/14 17:16:22 brouard
389: (Module): varevsij Comments added explaining the second
390: table of variances if popbased=1 .
391: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
392: (Module): Function pstamp added
393: (Module): Version 0.98d
394:
395: Revision 1.116 2006/03/06 10:29:27 brouard
396: (Module): Variance-covariance wrong links and
397: varian-covariance of ej. is needed (Saito).
398:
399: Revision 1.115 2006/02/27 12:17:45 brouard
400: (Module): One freematrix added in mlikeli! 0.98c
401:
402: Revision 1.114 2006/02/26 12:57:58 brouard
403: (Module): Some improvements in processing parameter
404: filename with strsep.
405:
406: Revision 1.113 2006/02/24 14:20:24 brouard
407: (Module): Memory leaks checks with valgrind and:
408: datafile was not closed, some imatrix were not freed and on matrix
409: allocation too.
410:
411: Revision 1.112 2006/01/30 09:55:26 brouard
412: (Module): Back to gnuplot.exe instead of wgnuplot.exe
413:
414: Revision 1.111 2006/01/25 20:38:18 brouard
415: (Module): Lots of cleaning and bugs added (Gompertz)
416: (Module): Comments can be added in data file. Missing date values
417: can be a simple dot '.'.
418:
419: Revision 1.110 2006/01/25 00:51:50 brouard
420: (Module): Lots of cleaning and bugs added (Gompertz)
421:
422: Revision 1.109 2006/01/24 19:37:15 brouard
423: (Module): Comments (lines starting with a #) are allowed in data.
424:
425: Revision 1.108 2006/01/19 18:05:42 lievre
426: Gnuplot problem appeared...
427: To be fixed
428:
429: Revision 1.107 2006/01/19 16:20:37 brouard
430: Test existence of gnuplot in imach path
431:
432: Revision 1.106 2006/01/19 13:24:36 brouard
433: Some cleaning and links added in html output
434:
435: Revision 1.105 2006/01/05 20:23:19 lievre
436: *** empty log message ***
437:
438: Revision 1.104 2005/09/30 16:11:43 lievre
439: (Module): sump fixed, loop imx fixed, and simplifications.
440: (Module): If the status is missing at the last wave but we know
441: that the person is alive, then we can code his/her status as -2
442: (instead of missing=-1 in earlier versions) and his/her
443: contributions to the likelihood is 1 - Prob of dying from last
444: health status (= 1-p13= p11+p12 in the easiest case of somebody in
445: the healthy state at last known wave). Version is 0.98
446:
447: Revision 1.103 2005/09/30 15:54:49 lievre
448: (Module): sump fixed, loop imx fixed, and simplifications.
449:
450: Revision 1.102 2004/09/15 17:31:30 brouard
451: Add the possibility to read data file including tab characters.
452:
453: Revision 1.101 2004/09/15 10:38:38 brouard
454: Fix on curr_time
455:
456: Revision 1.100 2004/07/12 18:29:06 brouard
457: Add version for Mac OS X. Just define UNIX in Makefile
458:
459: Revision 1.99 2004/06/05 08:57:40 brouard
460: *** empty log message ***
461:
462: Revision 1.98 2004/05/16 15:05:56 brouard
463: New version 0.97 . First attempt to estimate force of mortality
464: directly from the data i.e. without the need of knowing the health
465: state at each age, but using a Gompertz model: log u =a + b*age .
466: This is the basic analysis of mortality and should be done before any
467: other analysis, in order to test if the mortality estimated from the
468: cross-longitudinal survey is different from the mortality estimated
469: from other sources like vital statistic data.
470:
471: The same imach parameter file can be used but the option for mle should be -3.
472:
473: Agnès, who wrote this part of the code, tried to keep most of the
474: former routines in order to include the new code within the former code.
475:
476: The output is very simple: only an estimate of the intercept and of
477: the slope with 95% confident intervals.
478:
479: Current limitations:
480: A) Even if you enter covariates, i.e. with the
481: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
482: B) There is no computation of Life Expectancy nor Life Table.
483:
484: Revision 1.97 2004/02/20 13:25:42 lievre
485: Version 0.96d. Population forecasting command line is (temporarily)
486: suppressed.
487:
488: Revision 1.96 2003/07/15 15:38:55 brouard
489: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
490: rewritten within the same printf. Workaround: many printfs.
491:
492: Revision 1.95 2003/07/08 07:54:34 brouard
493: * imach.c (Repository):
494: (Repository): Using imachwizard code to output a more meaningful covariance
495: matrix (cov(a12,c31) instead of numbers.
496:
497: Revision 1.94 2003/06/27 13:00:02 brouard
498: Just cleaning
499:
500: Revision 1.93 2003/06/25 16:33:55 brouard
501: (Module): On windows (cygwin) function asctime_r doesn't
502: exist so I changed back to asctime which exists.
503: (Module): Version 0.96b
504:
505: Revision 1.92 2003/06/25 16:30:45 brouard
506: (Module): On windows (cygwin) function asctime_r doesn't
507: exist so I changed back to asctime which exists.
508:
509: Revision 1.91 2003/06/25 15:30:29 brouard
510: * imach.c (Repository): Duplicated warning errors corrected.
511: (Repository): Elapsed time after each iteration is now output. It
512: helps to forecast when convergence will be reached. Elapsed time
513: is stamped in powell. We created a new html file for the graphs
514: concerning matrix of covariance. It has extension -cov.htm.
515:
516: Revision 1.90 2003/06/24 12:34:15 brouard
517: (Module): Some bugs corrected for windows. Also, when
518: mle=-1 a template is output in file "or"mypar.txt with the design
519: of the covariance matrix to be input.
520:
521: Revision 1.89 2003/06/24 12:30:52 brouard
522: (Module): Some bugs corrected for windows. Also, when
523: mle=-1 a template is output in file "or"mypar.txt with the design
524: of the covariance matrix to be input.
525:
526: Revision 1.88 2003/06/23 17:54:56 brouard
527: * 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.
528:
529: Revision 1.87 2003/06/18 12:26:01 brouard
530: Version 0.96
531:
532: Revision 1.86 2003/06/17 20:04:08 brouard
533: (Module): Change position of html and gnuplot routines and added
534: routine fileappend.
535:
536: Revision 1.85 2003/06/17 13:12:43 brouard
537: * imach.c (Repository): Check when date of death was earlier that
538: current date of interview. It may happen when the death was just
539: prior to the death. In this case, dh was negative and likelihood
540: was wrong (infinity). We still send an "Error" but patch by
541: assuming that the date of death was just one stepm after the
542: interview.
543: (Repository): Because some people have very long ID (first column)
544: we changed int to long in num[] and we added a new lvector for
545: memory allocation. But we also truncated to 8 characters (left
546: truncation)
547: (Repository): No more line truncation errors.
548:
549: Revision 1.84 2003/06/13 21:44:43 brouard
550: * imach.c (Repository): Replace "freqsummary" at a correct
551: place. It differs from routine "prevalence" which may be called
552: many times. Probs is memory consuming and must be used with
553: parcimony.
554: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
555:
556: Revision 1.83 2003/06/10 13:39:11 lievre
557: *** empty log message ***
558:
559: Revision 1.82 2003/06/05 15:57:20 brouard
560: Add log in imach.c and fullversion number is now printed.
561:
562: */
563: /*
564: Interpolated Markov Chain
565:
566: Short summary of the programme:
567:
568: This program computes Healthy Life Expectancies from
569: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
570: first survey ("cross") where individuals from different ages are
571: interviewed on their health status or degree of disability (in the
572: case of a health survey which is our main interest) -2- at least a
573: second wave of interviews ("longitudinal") which measure each change
574: (if any) in individual health status. Health expectancies are
575: computed from the time spent in each health state according to a
576: model. More health states you consider, more time is necessary to reach the
577: Maximum Likelihood of the parameters involved in the model. The
578: simplest model is the multinomial logistic model where pij is the
579: probability to be observed in state j at the second wave
580: conditional to be observed in state i at the first wave. Therefore
581: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
582: 'age' is age and 'sex' is a covariate. If you want to have a more
583: complex model than "constant and age", you should modify the program
584: where the markup *Covariates have to be included here again* invites
585: you to do it. More covariates you add, slower the
586: convergence.
587:
588: The advantage of this computer programme, compared to a simple
589: multinomial logistic model, is clear when the delay between waves is not
590: identical for each individual. Also, if a individual missed an
591: intermediate interview, the information is lost, but taken into
592: account using an interpolation or extrapolation.
593:
594: hPijx is the probability to be observed in state i at age x+h
595: conditional to the observed state i at age x. The delay 'h' can be
596: split into an exact number (nh*stepm) of unobserved intermediate
597: states. This elementary transition (by month, quarter,
598: semester or year) is modelled as a multinomial logistic. The hPx
599: matrix is simply the matrix product of nh*stepm elementary matrices
600: and the contribution of each individual to the likelihood is simply
601: hPijx.
602:
603: Also this programme outputs the covariance matrix of the parameters but also
604: of the life expectancies. It also computes the period (stable) prevalence.
605:
606: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
607: Institut national d'études démographiques, Paris.
608: This software have been partly granted by Euro-REVES, a concerted action
609: from the European Union.
610: It is copyrighted identically to a GNU software product, ie programme and
611: software can be distributed freely for non commercial use. Latest version
612: can be accessed at http://euroreves.ined.fr/imach .
613:
614: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
615: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
616:
617: **********************************************************************/
618: /*
619: main
620: read parameterfile
621: read datafile
622: concatwav
623: freqsummary
624: if (mle >= 1)
625: mlikeli
626: print results files
627: if mle==1
628: computes hessian
629: read end of parameter file: agemin, agemax, bage, fage, estepm
630: begin-prev-date,...
631: open gnuplot file
632: open html file
633: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
634: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
635: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
636: freexexit2 possible for memory heap.
637:
638: h Pij x | pij_nom ficrestpij
639: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
640: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
641: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
642:
643: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
644: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
645: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
646: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
647: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
648:
649: forecasting if prevfcast==1 prevforecast call prevalence()
650: health expectancies
651: Variance-covariance of DFLE
652: prevalence()
653: movingaverage()
654: varevsij()
655: if popbased==1 varevsij(,popbased)
656: total life expectancies
657: Variance of period (stable) prevalence
658: end
659: */
660:
661: /* #define DEBUG */
662: /* #define DEBUGBRENT */
663: /* #define DEBUGLINMIN */
664: /* #define DEBUGHESS */
665: #define DEBUGHESSIJ
666: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
667: #define POWELL /* Instead of NLOPT */
668: #define POWELLF1F3 /* Skip test */
669: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
670: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
671:
672: #include <math.h>
673: #include <stdio.h>
674: #include <stdlib.h>
675: #include <string.h>
676:
677: #ifdef _WIN32
678: #include <io.h>
679: #include <windows.h>
680: #include <tchar.h>
681: #else
682: #include <unistd.h>
683: #endif
684:
685: #include <limits.h>
686: #include <sys/types.h>
687:
688: #if defined(__GNUC__)
689: #include <sys/utsname.h> /* Doesn't work on Windows */
690: #endif
691:
692: #include <sys/stat.h>
693: #include <errno.h>
694: /* extern int errno; */
695:
696: /* #ifdef LINUX */
697: /* #include <time.h> */
698: /* #include "timeval.h" */
699: /* #else */
700: /* #include <sys/time.h> */
701: /* #endif */
702:
703: #include <time.h>
704:
705: #ifdef GSL
706: #include <gsl/gsl_errno.h>
707: #include <gsl/gsl_multimin.h>
708: #endif
709:
710:
711: #ifdef NLOPT
712: #include <nlopt.h>
713: typedef struct {
714: double (* function)(double [] );
715: } myfunc_data ;
716: #endif
717:
718: /* #include <libintl.h> */
719: /* #define _(String) gettext (String) */
720:
721: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
722:
723: #define GNUPLOTPROGRAM "gnuplot"
724: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
725: #define FILENAMELENGTH 132
726:
727: #define GLOCK_ERROR_NOPATH -1 /* empty path */
728: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
729:
730: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
731: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
732:
733: #define NINTERVMAX 8
734: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
735: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
736: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
737: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
738: #define MAXN 20000
739: #define YEARM 12. /**< Number of months per year */
740: #define AGESUP 130
741: #define AGEBASE 40
742: #define AGEOVERFLOW 1.e20
743: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
744: #ifdef _WIN32
745: #define DIRSEPARATOR '\\'
746: #define CHARSEPARATOR "\\"
747: #define ODIRSEPARATOR '/'
748: #else
749: #define DIRSEPARATOR '/'
750: #define CHARSEPARATOR "/"
751: #define ODIRSEPARATOR '\\'
752: #endif
753:
754: /* $Id: imach.c,v 1.205 2015/10/23 15:50:53 brouard Exp $ */
755: /* $State: Exp $ */
756: #include "version.h"
757: char version[]=__IMACH_VERSION__;
758: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
759: char fullversion[]="$Revision: 1.205 $ $Date: 2015/10/23 15:50:53 $";
760: char strstart[80];
761: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
762: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
763: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
764: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
765: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
766: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
767: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
768: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
769: int cptcovprodnoage=0; /**< Number of covariate products without age */
770: int cptcoveff=0; /* Total number of covariates to vary for printing results */
771: int cptcov=0; /* Working variable */
772: int npar=NPARMAX;
773: int nlstate=2; /* Number of live states */
774: int ndeath=1; /* Number of dead states */
775: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
776: int popbased=0;
777:
778: int *wav; /* Number of waves for this individuual 0 is possible */
779: int maxwav=0; /* Maxim number of waves */
780: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
781: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
782: int gipmx=0, gsw=0; /* Global variables on the number of contributions
783: to the likelihood and the sum of weights (done by funcone)*/
784: int mle=1, weightopt=0;
785: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
786: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
787: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
788: * wave mi and wave mi+1 is not an exact multiple of stepm. */
789: int countcallfunc=0; /* Count the number of calls to func */
790: double jmean=1; /* Mean space between 2 waves */
791: double **matprod2(); /* test */
792: double **oldm, **newm, **savm; /* Working pointers to matrices */
793: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
794: /*FILE *fic ; */ /* Used in readdata only */
795: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
796: FILE *ficlog, *ficrespow;
797: int globpr=0; /* Global variable for printing or not */
798: double fretone; /* Only one call to likelihood */
799: long ipmx=0; /* Number of contributions */
800: double sw; /* Sum of weights */
801: char filerespow[FILENAMELENGTH];
802: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
803: FILE *ficresilk;
804: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
805: FILE *ficresprobmorprev;
806: FILE *fichtm, *fichtmcov; /* Html File */
807: FILE *ficreseij;
808: char filerese[FILENAMELENGTH];
809: FILE *ficresstdeij;
810: char fileresstde[FILENAMELENGTH];
811: FILE *ficrescveij;
812: char filerescve[FILENAMELENGTH];
813: FILE *ficresvij;
814: char fileresv[FILENAMELENGTH];
815: FILE *ficresvpl;
816: char fileresvpl[FILENAMELENGTH];
817: char title[MAXLINE];
818: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
819: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
820: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
821: char command[FILENAMELENGTH];
822: int outcmd=0;
823:
824: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
825: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
826: char filelog[FILENAMELENGTH]; /* Log file */
827: char filerest[FILENAMELENGTH];
828: char fileregp[FILENAMELENGTH];
829: char popfile[FILENAMELENGTH];
830:
831: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
832:
833: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
834: /* struct timezone tzp; */
835: /* extern int gettimeofday(); */
836: struct tm tml, *gmtime(), *localtime();
837:
838: extern time_t time();
839:
840: struct tm start_time, end_time, curr_time, last_time, forecast_time;
841: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
842: struct tm tm;
843:
844: char strcurr[80], strfor[80];
845:
846: char *endptr;
847: long lval;
848: double dval;
849:
850: #define NR_END 1
851: #define FREE_ARG char*
852: #define FTOL 1.0e-10
853:
854: #define NRANSI
855: #define ITMAX 200
856:
857: #define TOL 2.0e-4
858:
859: #define CGOLD 0.3819660
860: #define ZEPS 1.0e-10
861: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
862:
863: #define GOLD 1.618034
864: #define GLIMIT 100.0
865: #define TINY 1.0e-20
866:
867: static double maxarg1,maxarg2;
868: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
869: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
870:
871: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
872: #define rint(a) floor(a+0.5)
873: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
874: #define mytinydouble 1.0e-16
875: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
876: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
877: /* static double dsqrarg; */
878: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
879: static double sqrarg;
880: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
881: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
882: int agegomp= AGEGOMP;
883:
884: int imx;
885: int stepm=1;
886: /* Stepm, step in month: minimum step interpolation*/
887:
888: int estepm;
889: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
890:
891: int m,nb;
892: long *num;
893: int firstpass=0, lastpass=4,*cod, *cens;
894: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
895: covariate for which somebody answered excluding
896: undefined. Usually 2: 0 and 1. */
897: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
898: covariate for which somebody answered including
899: undefined. Usually 3: -1, 0 and 1. */
900: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
901: double **pmmij, ***probs;
902: double *ageexmed,*agecens;
903: double dateintmean=0;
904:
905: double *weight;
906: int **s; /* Status */
907: double *agedc;
908: double **covar; /**< covar[j,i], value of jth covariate for individual i,
909: * covar=matrix(0,NCOVMAX,1,n);
910: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
911: double idx;
912: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
913: int *Tage;
914: int *Ndum; /** Freq of modality (tricode */
915: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
916: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
917: double *lsurv, *lpop, *tpop;
918:
919: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
920: double ftolhess; /**< Tolerance for computing hessian */
921:
922: /**************** split *************************/
923: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
924: {
925: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
926: the name of the file (name), its extension only (ext) and its first part of the name (finame)
927: */
928: char *ss; /* pointer */
929: int l1=0, l2=0; /* length counters */
930:
931: l1 = strlen(path ); /* length of path */
932: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
933: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
934: if ( ss == NULL ) { /* no directory, so determine current directory */
935: strcpy( name, path ); /* we got the fullname name because no directory */
936: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
937: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
938: /* get current working directory */
939: /* extern char* getcwd ( char *buf , int len);*/
940: #ifdef WIN32
941: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
942: #else
943: if (getcwd(dirc, FILENAME_MAX) == NULL) {
944: #endif
945: return( GLOCK_ERROR_GETCWD );
946: }
947: /* got dirc from getcwd*/
948: printf(" DIRC = %s \n",dirc);
949: } else { /* strip directory from path */
950: ss++; /* after this, the filename */
951: l2 = strlen( ss ); /* length of filename */
952: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
953: strcpy( name, ss ); /* save file name */
954: strncpy( dirc, path, l1 - l2 ); /* now the directory */
955: dirc[l1-l2] = '\0'; /* add zero */
956: printf(" DIRC2 = %s \n",dirc);
957: }
958: /* We add a separator at the end of dirc if not exists */
959: l1 = strlen( dirc ); /* length of directory */
960: if( dirc[l1-1] != DIRSEPARATOR ){
961: dirc[l1] = DIRSEPARATOR;
962: dirc[l1+1] = 0;
963: printf(" DIRC3 = %s \n",dirc);
964: }
965: ss = strrchr( name, '.' ); /* find last / */
966: if (ss >0){
967: ss++;
968: strcpy(ext,ss); /* save extension */
969: l1= strlen( name);
970: l2= strlen(ss)+1;
971: strncpy( finame, name, l1-l2);
972: finame[l1-l2]= 0;
973: }
974:
975: return( 0 ); /* we're done */
976: }
977:
978:
979: /******************************************/
980:
981: void replace_back_to_slash(char *s, char*t)
982: {
983: int i;
984: int lg=0;
985: i=0;
986: lg=strlen(t);
987: for(i=0; i<= lg; i++) {
988: (s[i] = t[i]);
989: if (t[i]== '\\') s[i]='/';
990: }
991: }
992:
993: char *trimbb(char *out, char *in)
994: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
995: char *s;
996: s=out;
997: while (*in != '\0'){
998: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
999: in++;
1000: }
1001: *out++ = *in++;
1002: }
1003: *out='\0';
1004: return s;
1005: }
1006:
1007: /* char *substrchaine(char *out, char *in, char *chain) */
1008: /* { */
1009: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1010: /* char *s, *t; */
1011: /* t=in;s=out; */
1012: /* while ((*in != *chain) && (*in != '\0')){ */
1013: /* *out++ = *in++; */
1014: /* } */
1015:
1016: /* /\* *in matches *chain *\/ */
1017: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1018: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1019: /* } */
1020: /* in--; chain--; */
1021: /* while ( (*in != '\0')){ */
1022: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1023: /* *out++ = *in++; */
1024: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1025: /* } */
1026: /* *out='\0'; */
1027: /* out=s; */
1028: /* return out; */
1029: /* } */
1030: char *substrchaine(char *out, char *in, char *chain)
1031: {
1032: /* Substract chain 'chain' from 'in', return and output 'out' */
1033: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1034:
1035: char *strloc;
1036:
1037: strcpy (out, in);
1038: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1039: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1040: if(strloc != NULL){
1041: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1042: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1043: /* strcpy (strloc, strloc +strlen(chain));*/
1044: }
1045: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1046: return out;
1047: }
1048:
1049:
1050: char *cutl(char *blocc, char *alocc, char *in, char occ)
1051: {
1052: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1053: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1054: gives blocc="abcdef" and alocc="ghi2j".
1055: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1056: */
1057: char *s, *t;
1058: t=in;s=in;
1059: while ((*in != occ) && (*in != '\0')){
1060: *alocc++ = *in++;
1061: }
1062: if( *in == occ){
1063: *(alocc)='\0';
1064: s=++in;
1065: }
1066:
1067: if (s == t) {/* occ not found */
1068: *(alocc-(in-s))='\0';
1069: in=s;
1070: }
1071: while ( *in != '\0'){
1072: *blocc++ = *in++;
1073: }
1074:
1075: *blocc='\0';
1076: return t;
1077: }
1078: char *cutv(char *blocc, char *alocc, char *in, char occ)
1079: {
1080: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1081: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1082: gives blocc="abcdef2ghi" and alocc="j".
1083: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1084: */
1085: char *s, *t;
1086: t=in;s=in;
1087: while (*in != '\0'){
1088: while( *in == occ){
1089: *blocc++ = *in++;
1090: s=in;
1091: }
1092: *blocc++ = *in++;
1093: }
1094: if (s == t) /* occ not found */
1095: *(blocc-(in-s))='\0';
1096: else
1097: *(blocc-(in-s)-1)='\0';
1098: in=s;
1099: while ( *in != '\0'){
1100: *alocc++ = *in++;
1101: }
1102:
1103: *alocc='\0';
1104: return s;
1105: }
1106:
1107: int nbocc(char *s, char occ)
1108: {
1109: int i,j=0;
1110: int lg=20;
1111: i=0;
1112: lg=strlen(s);
1113: for(i=0; i<= lg; i++) {
1114: if (s[i] == occ ) j++;
1115: }
1116: return j;
1117: }
1118:
1119: /* void cutv(char *u,char *v, char*t, char occ) */
1120: /* { */
1121: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1122: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1123: /* gives u="abcdef2ghi" and v="j" *\/ */
1124: /* int i,lg,j,p=0; */
1125: /* i=0; */
1126: /* lg=strlen(t); */
1127: /* for(j=0; j<=lg-1; j++) { */
1128: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1129: /* } */
1130:
1131: /* for(j=0; j<p; j++) { */
1132: /* (u[j] = t[j]); */
1133: /* } */
1134: /* u[p]='\0'; */
1135:
1136: /* for(j=0; j<= lg; j++) { */
1137: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1138: /* } */
1139: /* } */
1140:
1141: #ifdef _WIN32
1142: char * strsep(char **pp, const char *delim)
1143: {
1144: char *p, *q;
1145:
1146: if ((p = *pp) == NULL)
1147: return 0;
1148: if ((q = strpbrk (p, delim)) != NULL)
1149: {
1150: *pp = q + 1;
1151: *q = '\0';
1152: }
1153: else
1154: *pp = 0;
1155: return p;
1156: }
1157: #endif
1158:
1159: /********************** nrerror ********************/
1160:
1161: void nrerror(char error_text[])
1162: {
1163: fprintf(stderr,"ERREUR ...\n");
1164: fprintf(stderr,"%s\n",error_text);
1165: exit(EXIT_FAILURE);
1166: }
1167: /*********************** vector *******************/
1168: double *vector(int nl, int nh)
1169: {
1170: double *v;
1171: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1172: if (!v) nrerror("allocation failure in vector");
1173: return v-nl+NR_END;
1174: }
1175:
1176: /************************ free vector ******************/
1177: void free_vector(double*v, int nl, int nh)
1178: {
1179: free((FREE_ARG)(v+nl-NR_END));
1180: }
1181:
1182: /************************ivector *******************************/
1183: int *ivector(long nl,long nh)
1184: {
1185: int *v;
1186: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1187: if (!v) nrerror("allocation failure in ivector");
1188: return v-nl+NR_END;
1189: }
1190:
1191: /******************free ivector **************************/
1192: void free_ivector(int *v, long nl, long nh)
1193: {
1194: free((FREE_ARG)(v+nl-NR_END));
1195: }
1196:
1197: /************************lvector *******************************/
1198: long *lvector(long nl,long nh)
1199: {
1200: long *v;
1201: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1202: if (!v) nrerror("allocation failure in ivector");
1203: return v-nl+NR_END;
1204: }
1205:
1206: /******************free lvector **************************/
1207: void free_lvector(long *v, long nl, long nh)
1208: {
1209: free((FREE_ARG)(v+nl-NR_END));
1210: }
1211:
1212: /******************* imatrix *******************************/
1213: int **imatrix(long nrl, long nrh, long ncl, long nch)
1214: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1215: {
1216: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1217: int **m;
1218:
1219: /* allocate pointers to rows */
1220: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1221: if (!m) nrerror("allocation failure 1 in matrix()");
1222: m += NR_END;
1223: m -= nrl;
1224:
1225:
1226: /* allocate rows and set pointers to them */
1227: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1228: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1229: m[nrl] += NR_END;
1230: m[nrl] -= ncl;
1231:
1232: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1233:
1234: /* return pointer to array of pointers to rows */
1235: return m;
1236: }
1237:
1238: /****************** free_imatrix *************************/
1239: void free_imatrix(m,nrl,nrh,ncl,nch)
1240: int **m;
1241: long nch,ncl,nrh,nrl;
1242: /* free an int matrix allocated by imatrix() */
1243: {
1244: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1245: free((FREE_ARG) (m+nrl-NR_END));
1246: }
1247:
1248: /******************* matrix *******************************/
1249: double **matrix(long nrl, long nrh, long ncl, long nch)
1250: {
1251: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1252: double **m;
1253:
1254: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1255: if (!m) nrerror("allocation failure 1 in matrix()");
1256: m += NR_END;
1257: m -= nrl;
1258:
1259: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1260: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1261: m[nrl] += NR_END;
1262: m[nrl] -= ncl;
1263:
1264: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1265: return m;
1266: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1267: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1268: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1269: */
1270: }
1271:
1272: /*************************free matrix ************************/
1273: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1274: {
1275: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1276: free((FREE_ARG)(m+nrl-NR_END));
1277: }
1278:
1279: /******************* ma3x *******************************/
1280: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1281: {
1282: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1283: double ***m;
1284:
1285: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1286: if (!m) nrerror("allocation failure 1 in matrix()");
1287: m += NR_END;
1288: m -= nrl;
1289:
1290: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1291: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1292: m[nrl] += NR_END;
1293: m[nrl] -= ncl;
1294:
1295: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1296:
1297: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1298: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1299: m[nrl][ncl] += NR_END;
1300: m[nrl][ncl] -= nll;
1301: for (j=ncl+1; j<=nch; j++)
1302: m[nrl][j]=m[nrl][j-1]+nlay;
1303:
1304: for (i=nrl+1; i<=nrh; i++) {
1305: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1306: for (j=ncl+1; j<=nch; j++)
1307: m[i][j]=m[i][j-1]+nlay;
1308: }
1309: return m;
1310: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1311: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1312: */
1313: }
1314:
1315: /*************************free ma3x ************************/
1316: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1317: {
1318: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1319: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1320: free((FREE_ARG)(m+nrl-NR_END));
1321: }
1322:
1323: /*************** function subdirf ***********/
1324: char *subdirf(char fileres[])
1325: {
1326: /* Caution optionfilefiname is hidden */
1327: strcpy(tmpout,optionfilefiname);
1328: strcat(tmpout,"/"); /* Add to the right */
1329: strcat(tmpout,fileres);
1330: return tmpout;
1331: }
1332:
1333: /*************** function subdirf2 ***********/
1334: char *subdirf2(char fileres[], char *preop)
1335: {
1336:
1337: /* Caution optionfilefiname is hidden */
1338: strcpy(tmpout,optionfilefiname);
1339: strcat(tmpout,"/");
1340: strcat(tmpout,preop);
1341: strcat(tmpout,fileres);
1342: return tmpout;
1343: }
1344:
1345: /*************** function subdirf3 ***********/
1346: char *subdirf3(char fileres[], char *preop, char *preop2)
1347: {
1348:
1349: /* Caution optionfilefiname is hidden */
1350: strcpy(tmpout,optionfilefiname);
1351: strcat(tmpout,"/");
1352: strcat(tmpout,preop);
1353: strcat(tmpout,preop2);
1354: strcat(tmpout,fileres);
1355: return tmpout;
1356: }
1357:
1358: char *asc_diff_time(long time_sec, char ascdiff[])
1359: {
1360: long sec_left, days, hours, minutes;
1361: days = (time_sec) / (60*60*24);
1362: sec_left = (time_sec) % (60*60*24);
1363: hours = (sec_left) / (60*60) ;
1364: sec_left = (sec_left) %(60*60);
1365: minutes = (sec_left) /60;
1366: sec_left = (sec_left) % (60);
1367: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1368: return ascdiff;
1369: }
1370:
1371: /***************** f1dim *************************/
1372: extern int ncom;
1373: extern double *pcom,*xicom;
1374: extern double (*nrfunc)(double []);
1375:
1376: double f1dim(double x)
1377: {
1378: int j;
1379: double f;
1380: double *xt;
1381:
1382: xt=vector(1,ncom);
1383: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1384: f=(*nrfunc)(xt);
1385: free_vector(xt,1,ncom);
1386: return f;
1387: }
1388:
1389: /*****************brent *************************/
1390: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1391: {
1392: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1393: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1394: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1395: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1396: * returned function value.
1397: */
1398: int iter;
1399: double a,b,d,etemp;
1400: double fu=0,fv,fw,fx;
1401: double ftemp=0.;
1402: double p,q,r,tol1,tol2,u,v,w,x,xm;
1403: double e=0.0;
1404:
1405: a=(ax < cx ? ax : cx);
1406: b=(ax > cx ? ax : cx);
1407: x=w=v=bx;
1408: fw=fv=fx=(*f)(x);
1409: for (iter=1;iter<=ITMAX;iter++) {
1410: xm=0.5*(a+b);
1411: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1412: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1413: printf(".");fflush(stdout);
1414: fprintf(ficlog,".");fflush(ficlog);
1415: #ifdef DEBUGBRENT
1416: 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);
1417: 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);
1418: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1419: #endif
1420: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1421: *xmin=x;
1422: return fx;
1423: }
1424: ftemp=fu;
1425: if (fabs(e) > tol1) {
1426: r=(x-w)*(fx-fv);
1427: q=(x-v)*(fx-fw);
1428: p=(x-v)*q-(x-w)*r;
1429: q=2.0*(q-r);
1430: if (q > 0.0) p = -p;
1431: q=fabs(q);
1432: etemp=e;
1433: e=d;
1434: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1435: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1436: else {
1437: d=p/q;
1438: u=x+d;
1439: if (u-a < tol2 || b-u < tol2)
1440: d=SIGN(tol1,xm-x);
1441: }
1442: } else {
1443: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1444: }
1445: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1446: fu=(*f)(u);
1447: if (fu <= fx) {
1448: if (u >= x) a=x; else b=x;
1449: SHFT(v,w,x,u)
1450: SHFT(fv,fw,fx,fu)
1451: } else {
1452: if (u < x) a=u; else b=u;
1453: if (fu <= fw || w == x) {
1454: v=w;
1455: w=u;
1456: fv=fw;
1457: fw=fu;
1458: } else if (fu <= fv || v == x || v == w) {
1459: v=u;
1460: fv=fu;
1461: }
1462: }
1463: }
1464: nrerror("Too many iterations in brent");
1465: *xmin=x;
1466: return fx;
1467: }
1468:
1469: /****************** mnbrak ***********************/
1470:
1471: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1472: double (*func)(double))
1473: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1474: the downhill direction (defined by the function as evaluated at the initial points) and returns
1475: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1476: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1477: */
1478: double ulim,u,r,q, dum;
1479: double fu;
1480:
1481: double scale=10.;
1482: int iterscale=0;
1483:
1484: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1485: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1486:
1487:
1488: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1489: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1490: /* *bx = *ax - (*ax - *bx)/scale; */
1491: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1492: /* } */
1493:
1494: if (*fb > *fa) {
1495: SHFT(dum,*ax,*bx,dum)
1496: SHFT(dum,*fb,*fa,dum)
1497: }
1498: *cx=(*bx)+GOLD*(*bx-*ax);
1499: *fc=(*func)(*cx);
1500: #ifdef DEBUG
1501: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1502: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1503: #endif
1504: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1505: r=(*bx-*ax)*(*fb-*fc);
1506: q=(*bx-*cx)*(*fb-*fa);
1507: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1508: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1509: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1510: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1511: fu=(*func)(u);
1512: #ifdef DEBUG
1513: /* f(x)=A(x-u)**2+f(u) */
1514: double A, fparabu;
1515: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1516: fparabu= *fa - A*(*ax-u)*(*ax-u);
1517: 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);
1518: 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);
1519: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1520: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1521: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1522: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1523: #endif
1524: #ifdef MNBRAKORIGINAL
1525: #else
1526: /* if (fu > *fc) { */
1527: /* #ifdef DEBUG */
1528: /* printf("mnbrak4 fu > fc \n"); */
1529: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1530: /* #endif */
1531: /* /\* 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 *\\/ *\/ */
1532: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1533: /* dum=u; /\* Shifting c and u *\/ */
1534: /* u = *cx; */
1535: /* *cx = dum; */
1536: /* dum = fu; */
1537: /* fu = *fc; */
1538: /* *fc =dum; */
1539: /* } else { /\* end *\/ */
1540: /* #ifdef DEBUG */
1541: /* printf("mnbrak3 fu < fc \n"); */
1542: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1543: /* #endif */
1544: /* dum=u; /\* Shifting c and u *\/ */
1545: /* u = *cx; */
1546: /* *cx = dum; */
1547: /* dum = fu; */
1548: /* fu = *fc; */
1549: /* *fc =dum; */
1550: /* } */
1551: #ifdef DEBUG
1552: printf("mnbrak34 fu < or >= fc \n");
1553: fprintf(ficlog, "mnbrak34 fu < fc\n");
1554: #endif
1555: dum=u; /* Shifting c and u */
1556: u = *cx;
1557: *cx = dum;
1558: dum = fu;
1559: fu = *fc;
1560: *fc =dum;
1561: #endif
1562: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1563: #ifdef DEBUG
1564: printf("mnbrak2 u after c but before ulim\n");
1565: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1566: #endif
1567: fu=(*func)(u);
1568: if (fu < *fc) {
1569: #ifdef DEBUG
1570: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1571: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1572: #endif
1573: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1574: SHFT(*fb,*fc,fu,(*func)(u))
1575: }
1576: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1577: #ifdef DEBUG
1578: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1579: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1580: #endif
1581: u=ulim;
1582: fu=(*func)(u);
1583: } else { /* u could be left to b (if r > q parabola has a maximum) */
1584: #ifdef DEBUG
1585: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1586: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1587: #endif
1588: u=(*cx)+GOLD*(*cx-*bx);
1589: fu=(*func)(u);
1590: } /* end tests */
1591: SHFT(*ax,*bx,*cx,u)
1592: SHFT(*fa,*fb,*fc,fu)
1593: #ifdef DEBUG
1594: 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);
1595: 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);
1596: #endif
1597: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1598: }
1599:
1600: /*************** linmin ************************/
1601: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1602: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1603: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1604: the value of func at the returned location p . This is actually all accomplished by calling the
1605: routines mnbrak and brent .*/
1606: int ncom;
1607: double *pcom,*xicom;
1608: double (*nrfunc)(double []);
1609:
1610: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1611: {
1612: double brent(double ax, double bx, double cx,
1613: double (*f)(double), double tol, double *xmin);
1614: double f1dim(double x);
1615: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1616: double *fc, double (*func)(double));
1617: int j;
1618: double xx,xmin,bx,ax;
1619: double fx,fb,fa;
1620:
1621: #ifdef LINMINORIGINAL
1622: #else
1623: double scale=10., axs, xxs; /* Scale added for infinity */
1624: #endif
1625:
1626: ncom=n;
1627: pcom=vector(1,n);
1628: xicom=vector(1,n);
1629: nrfunc=func;
1630: for (j=1;j<=n;j++) {
1631: pcom[j]=p[j];
1632: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1633: }
1634:
1635: #ifdef LINMINORIGINAL
1636: xx=1.;
1637: #else
1638: axs=0.0;
1639: xxs=1.;
1640: do{
1641: xx= xxs;
1642: #endif
1643: ax=0.;
1644: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1645: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1646: /* xt[x,j]=pcom[j]+x*xicom[j] f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j)) */
1647: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1648: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1649: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1650: /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus [0:xi[j]]*/
1651: #ifdef LINMINORIGINAL
1652: #else
1653: if (fx != fx){
1654: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1655: printf("|");
1656: fprintf(ficlog,"|");
1657: #ifdef DEBUGLINMIN
1658: printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n", axs, xxs, fx,fb, fa, xx, ax, bx);
1659: #endif
1660: }
1661: }while(fx != fx);
1662: #endif
1663:
1664: #ifdef DEBUGLINMIN
1665: printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n", ax,xx,bx,fa,fx,fb);
1666: fprintf(ficlog,"\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n", ax,xx,bx,fa,fx,fb);
1667: #endif
1668: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1669: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1670: /* fmin = f(p[j] + xmin * xi[j]) */
1671: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1672: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1673: #ifdef DEBUG
1674: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1675: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1676: #endif
1677: #ifdef DEBUGLINMIN
1678: printf("linmin end ");
1679: fprintf(ficlog,"linmin end ");
1680: #endif
1681: for (j=1;j<=n;j++) {
1682: #ifdef LINMINORIGINAL
1683: xi[j] *= xmin;
1684: #else
1685: #ifdef DEBUGLINMIN
1686: if(xxs <1.0)
1687: printf(" before xi[%d]=%12.8f", j,xi[j]);
1688: #endif
1689: xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1690: #ifdef DEBUGLINMIN
1691: if(xxs <1.0)
1692: printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs );
1693: #endif
1694: #endif
1695: p[j] += xi[j]; /* Parameters values are updated accordingly */
1696: }
1697: #ifdef DEBUGLINMIN
1698: printf("\n");
1699: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1700: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1701: for (j=1;j<=n;j++) {
1702: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1703: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1704: if(j % ncovmodel == 0){
1705: printf("\n");
1706: fprintf(ficlog,"\n");
1707: }
1708: }
1709: #else
1710: #endif
1711: free_vector(xicom,1,n);
1712: free_vector(pcom,1,n);
1713: }
1714:
1715:
1716: /*************** powell ************************/
1717: /*
1718: Minimization of a function func of n variables. Input consists of an initial starting point
1719: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1720: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1721: such that failure to decrease by more than this amount on one iteration signals doneness. On
1722: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1723: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1724: */
1725: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1726: double (*func)(double []))
1727: {
1728: void linmin(double p[], double xi[], int n, double *fret,
1729: double (*func)(double []));
1730: int i,ibig,j;
1731: double del,t,*pt,*ptt,*xit;
1732: double directest;
1733: double fp,fptt;
1734: double *xits;
1735: int niterf, itmp;
1736:
1737: pt=vector(1,n);
1738: ptt=vector(1,n);
1739: xit=vector(1,n);
1740: xits=vector(1,n);
1741: *fret=(*func)(p);
1742: for (j=1;j<=n;j++) pt[j]=p[j];
1743: rcurr_time = time(NULL);
1744: for (*iter=1;;++(*iter)) {
1745: fp=(*fret); /* From former iteration or initial value */
1746: ibig=0;
1747: del=0.0;
1748: rlast_time=rcurr_time;
1749: /* (void) gettimeofday(&curr_time,&tzp); */
1750: rcurr_time = time(NULL);
1751: curr_time = *localtime(&rcurr_time);
1752: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1753: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1754: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1755: for (i=1;i<=n;i++) {
1756: printf(" %d %.12f",i, p[i]);
1757: fprintf(ficlog," %d %.12lf",i, p[i]);
1758: fprintf(ficrespow," %.12lf", p[i]);
1759: }
1760: printf("\n");
1761: fprintf(ficlog,"\n");
1762: fprintf(ficrespow,"\n");fflush(ficrespow);
1763: if(*iter <=3){
1764: tml = *localtime(&rcurr_time);
1765: strcpy(strcurr,asctime(&tml));
1766: rforecast_time=rcurr_time;
1767: itmp = strlen(strcurr);
1768: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1769: strcurr[itmp-1]='\0';
1770: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1771: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1772: for(niterf=10;niterf<=30;niterf+=10){
1773: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1774: forecast_time = *localtime(&rforecast_time);
1775: strcpy(strfor,asctime(&forecast_time));
1776: itmp = strlen(strfor);
1777: if(strfor[itmp-1]=='\n')
1778: strfor[itmp-1]='\0';
1779: 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);
1780: 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);
1781: }
1782: }
1783: for (i=1;i<=n;i++) { /* For each direction i */
1784: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1785: fptt=(*fret);
1786: #ifdef DEBUG
1787: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1788: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1789: #endif
1790: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1791: fprintf(ficlog,"%d",i);fflush(ficlog);
1792: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1793: /* Outputs are fret(new point p) p is updated and xit rescaled */
1794: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1795: /* because that direction will be replaced unless the gain del is small */
1796: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1797: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1798: /* with the new direction. */
1799: del=fabs(fptt-(*fret));
1800: ibig=i;
1801: }
1802: #ifdef DEBUG
1803: printf("%d %.12e",i,(*fret));
1804: fprintf(ficlog,"%d %.12e",i,(*fret));
1805: for (j=1;j<=n;j++) {
1806: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1807: printf(" x(%d)=%.12e",j,xit[j]);
1808: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1809: }
1810: for(j=1;j<=n;j++) {
1811: printf(" p(%d)=%.12e",j,p[j]);
1812: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1813: }
1814: printf("\n");
1815: fprintf(ficlog,"\n");
1816: #endif
1817: } /* end loop on each direction i */
1818: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1819: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1820: /* New value of last point Pn is not computed, P(n-1) */
1821: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1822: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1823: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1824: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1825: /* decreased of more than 3.84 */
1826: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1827: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1828: /* By adding 10 parameters more the gain should be 18.31 */
1829:
1830: /* Starting the program with initial values given by a former maximization will simply change */
1831: /* the scales of the directions and the directions, because the are reset to canonical directions */
1832: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1833: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1834: #ifdef DEBUG
1835: int k[2],l;
1836: k[0]=1;
1837: k[1]=-1;
1838: printf("Max: %.12e",(*func)(p));
1839: fprintf(ficlog,"Max: %.12e",(*func)(p));
1840: for (j=1;j<=n;j++) {
1841: printf(" %.12e",p[j]);
1842: fprintf(ficlog," %.12e",p[j]);
1843: }
1844: printf("\n");
1845: fprintf(ficlog,"\n");
1846: for(l=0;l<=1;l++) {
1847: for (j=1;j<=n;j++) {
1848: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1849: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1850: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1851: }
1852: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1853: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1854: }
1855: #endif
1856:
1857:
1858: free_vector(xit,1,n);
1859: free_vector(xits,1,n);
1860: free_vector(ptt,1,n);
1861: free_vector(pt,1,n);
1862: return;
1863: } /* enough precision */
1864: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1865: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1866: ptt[j]=2.0*p[j]-pt[j];
1867: xit[j]=p[j]-pt[j];
1868: pt[j]=p[j];
1869: }
1870: fptt=(*func)(ptt); /* f_3 */
1871: #ifdef POWELLF1F3
1872: #else
1873: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1874: #endif
1875: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1876: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1877: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1878: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1879: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1880: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1881: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1882: #ifdef NRCORIGINAL
1883: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1884: #else
1885: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1886: t= t- del*SQR(fp-fptt);
1887: #endif
1888: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1889: #ifdef DEBUG
1890: 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);
1891: 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);
1892: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1893: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1894: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1895: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1896: 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);
1897: 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);
1898: #endif
1899: #ifdef POWELLORIGINAL
1900: if (t < 0.0) { /* Then we use it for new direction */
1901: #else
1902: if (directest*t < 0.0) { /* Contradiction between both tests */
1903: printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1904: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1905: fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1906: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1907: }
1908: if (directest < 0.0) { /* Then we use it for new direction */
1909: #endif
1910: #ifdef DEBUGLINMIN
1911: printf("Before linmin in direction P%d-P0\n",n);
1912: for (j=1;j<=n;j++) {
1913: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1914: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1915: if(j % ncovmodel == 0){
1916: printf("\n");
1917: fprintf(ficlog,"\n");
1918: }
1919: }
1920: #endif
1921: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1922: #ifdef DEBUGLINMIN
1923: for (j=1;j<=n;j++) {
1924: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1925: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1926: if(j % ncovmodel == 0){
1927: printf("\n");
1928: fprintf(ficlog,"\n");
1929: }
1930: }
1931: #endif
1932: for (j=1;j<=n;j++) {
1933: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1934: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1935: }
1936: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1937: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1938:
1939: #ifdef DEBUG
1940: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1941: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1942: for(j=1;j<=n;j++){
1943: printf(" %.12e",xit[j]);
1944: fprintf(ficlog," %.12e",xit[j]);
1945: }
1946: printf("\n");
1947: fprintf(ficlog,"\n");
1948: #endif
1949: } /* end of t or directest negative */
1950: #ifdef POWELLF1F3
1951: #else
1952: } /* end if (fptt < fp) */
1953: #endif
1954: } /* loop iteration */
1955: }
1956:
1957: /**** Prevalence limit (stable or period prevalence) ****************/
1958:
1959: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1960: {
1961: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1962: matrix by transitions matrix until convergence is reached with precision ftolpl */
1963:
1964: int i, ii,j,k;
1965: double min, max, maxmin, maxmax,sumnew=0.;
1966: /* double **matprod2(); */ /* test */
1967: double **out, cov[NCOVMAX+1], **pmij();
1968: double **newm;
1969: double agefin, delaymax=100 ; /* Max number of years to converge */
1970: int ncvloop=0;
1971:
1972: for (ii=1;ii<=nlstate+ndeath;ii++)
1973: for (j=1;j<=nlstate+ndeath;j++){
1974: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1975: }
1976:
1977: cov[1]=1.;
1978:
1979: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1980: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1981: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1982: ncvloop++;
1983: newm=savm;
1984: /* Covariates have to be included here again */
1985: cov[2]=agefin;
1986: if(nagesqr==1)
1987: cov[3]= agefin*agefin;;
1988: for (k=1; k<=cptcovn;k++) {
1989: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1990: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1991: /* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); */
1992: }
1993: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1994: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
1995: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1996: for (k=1; k<=cptcovprod;k++) /* Useless */
1997: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1998: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1999:
2000: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2001: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2002: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2003: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2004: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2005: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2006:
2007: savm=oldm;
2008: oldm=newm;
2009: maxmax=0.;
2010: for(j=1;j<=nlstate;j++){
2011: min=1.;
2012: max=0.;
2013: for(i=1; i<=nlstate; i++) {
2014: sumnew=0;
2015: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2016: prlim[i][j]= newm[i][j]/(1-sumnew);
2017: max=FMAX(max,prlim[i][j]);
2018: min=FMIN(min,prlim[i][j]);
2019: /* printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min); */
2020: }
2021: maxmin=(max-min)/(max+min)*2;
2022: maxmax=FMAX(maxmax,maxmin);
2023: } /* j loop */
2024: *ncvyear= (int)age- (int)agefin;
2025: /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2026: if(maxmax < ftolpl){
2027: /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2028: return prlim;
2029: }
2030: } /* age loop */
2031: printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g. \n\
2032: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
2033: /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
2034: return prlim; /* should not reach here */
2035: }
2036:
2037: /*************** transition probabilities ***************/
2038:
2039: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2040: {
2041: /* According to parameters values stored in x and the covariate's values stored in cov,
2042: computes the probability to be observed in state j being in state i by appying the
2043: model to the ncovmodel covariates (including constant and age).
2044: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2045: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2046: ncth covariate in the global vector x is given by the formula:
2047: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2048: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2049: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2050: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2051: Outputs ps[i][j] the probability to be observed in j being in j according to
2052: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2053: */
2054: double s1, lnpijopii;
2055: /*double t34;*/
2056: int i,j, nc, ii, jj;
2057:
2058: for(i=1; i<= nlstate; i++){
2059: for(j=1; j<i;j++){
2060: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2061: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2062: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2063: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2064: }
2065: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2066: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2067: }
2068: for(j=i+1; j<=nlstate+ndeath;j++){
2069: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2070: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2071: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2072: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2073: }
2074: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2075: }
2076: }
2077:
2078: for(i=1; i<= nlstate; i++){
2079: s1=0;
2080: for(j=1; j<i; j++){
2081: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2082: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2083: }
2084: for(j=i+1; j<=nlstate+ndeath; j++){
2085: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2086: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2087: }
2088: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2089: ps[i][i]=1./(s1+1.);
2090: /* Computing other pijs */
2091: for(j=1; j<i; j++)
2092: ps[i][j]= exp(ps[i][j])*ps[i][i];
2093: for(j=i+1; j<=nlstate+ndeath; j++)
2094: ps[i][j]= exp(ps[i][j])*ps[i][i];
2095: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2096: } /* end i */
2097:
2098: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2099: for(jj=1; jj<= nlstate+ndeath; jj++){
2100: ps[ii][jj]=0;
2101: ps[ii][ii]=1;
2102: }
2103: }
2104:
2105:
2106: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2107: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2108: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2109: /* } */
2110: /* printf("\n "); */
2111: /* } */
2112: /* printf("\n ");printf("%lf ",cov[2]);*/
2113: /*
2114: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2115: goto end;*/
2116: return ps;
2117: }
2118:
2119: /**************** Product of 2 matrices ******************/
2120:
2121: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2122: {
2123: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2124: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2125: /* in, b, out are matrice of pointers which should have been initialized
2126: before: only the contents of out is modified. The function returns
2127: a pointer to pointers identical to out */
2128: int i, j, k;
2129: for(i=nrl; i<= nrh; i++)
2130: for(k=ncolol; k<=ncoloh; k++){
2131: out[i][k]=0.;
2132: for(j=ncl; j<=nch; j++)
2133: out[i][k] +=in[i][j]*b[j][k];
2134: }
2135: return out;
2136: }
2137:
2138:
2139: /************* Higher Matrix Product ***************/
2140:
2141: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2142: {
2143: /* Computes the transition matrix starting at age 'age' over
2144: 'nhstepm*hstepm*stepm' months (i.e. until
2145: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2146: nhstepm*hstepm matrices.
2147: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2148: (typically every 2 years instead of every month which is too big
2149: for the memory).
2150: Model is determined by parameters x and covariates have to be
2151: included manually here.
2152:
2153: */
2154:
2155: int i, j, d, h, k;
2156: double **out, cov[NCOVMAX+1];
2157: double **newm;
2158: double agexact;
2159:
2160: /* Hstepm could be zero and should return the unit matrix */
2161: for (i=1;i<=nlstate+ndeath;i++)
2162: for (j=1;j<=nlstate+ndeath;j++){
2163: oldm[i][j]=(i==j ? 1.0 : 0.0);
2164: po[i][j][0]=(i==j ? 1.0 : 0.0);
2165: }
2166: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2167: for(h=1; h <=nhstepm; h++){
2168: for(d=1; d <=hstepm; d++){
2169: newm=savm;
2170: /* Covariates have to be included here again */
2171: cov[1]=1.;
2172: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2173: cov[2]=agexact;
2174: if(nagesqr==1)
2175: cov[3]= agexact*agexact;
2176: for (k=1; k<=cptcovn;k++)
2177: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2178: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2179: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2180: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2181: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2182: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2183: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2184: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2185: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2186:
2187:
2188: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2189: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2190: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2191: pmij(pmmij,cov,ncovmodel,x,nlstate));
2192: savm=oldm;
2193: oldm=newm;
2194: }
2195: for(i=1; i<=nlstate+ndeath; i++)
2196: for(j=1;j<=nlstate+ndeath;j++) {
2197: po[i][j][h]=newm[i][j];
2198: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2199: }
2200: /*printf("h=%d ",h);*/
2201: } /* end h */
2202: /* printf("\n H=%d \n",h); */
2203: return po;
2204: }
2205:
2206: #ifdef NLOPT
2207: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2208: double fret;
2209: double *xt;
2210: int j;
2211: myfunc_data *d2 = (myfunc_data *) pd;
2212: /* xt = (p1-1); */
2213: xt=vector(1,n);
2214: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2215:
2216: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2217: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2218: printf("Function = %.12lf ",fret);
2219: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2220: printf("\n");
2221: free_vector(xt,1,n);
2222: return fret;
2223: }
2224: #endif
2225:
2226: /*************** log-likelihood *************/
2227: double func( double *x)
2228: {
2229: int i, ii, j, k, mi, d, kk;
2230: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2231: double **out;
2232: double sw; /* Sum of weights */
2233: double lli; /* Individual log likelihood */
2234: int s1, s2;
2235: double bbh, survp;
2236: long ipmx;
2237: double agexact;
2238: /*extern weight */
2239: /* We are differentiating ll according to initial status */
2240: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2241: /*for(i=1;i<imx;i++)
2242: printf(" %d\n",s[4][i]);
2243: */
2244:
2245: ++countcallfunc;
2246:
2247: cov[1]=1.;
2248:
2249: for(k=1; k<=nlstate; k++) ll[k]=0.;
2250:
2251: if(mle==1){
2252: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2253: /* Computes the values of the ncovmodel covariates of the model
2254: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2255: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2256: to be observed in j being in i according to the model.
2257: */
2258: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2259: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2260: }
2261: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2262: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2263: has been calculated etc */
2264: for(mi=1; mi<= wav[i]-1; mi++){
2265: for (ii=1;ii<=nlstate+ndeath;ii++)
2266: for (j=1;j<=nlstate+ndeath;j++){
2267: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2268: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2269: }
2270: for(d=0; d<dh[mi][i]; d++){
2271: newm=savm;
2272: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2273: cov[2]=agexact;
2274: if(nagesqr==1)
2275: cov[3]= agexact*agexact;
2276: for (kk=1; kk<=cptcovage;kk++) {
2277: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2278: }
2279: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2280: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2281: savm=oldm;
2282: oldm=newm;
2283: } /* end mult */
2284:
2285: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2286: /* But now since version 0.9 we anticipate for bias at large stepm.
2287: * If stepm is larger than one month (smallest stepm) and if the exact delay
2288: * (in months) between two waves is not a multiple of stepm, we rounded to
2289: * the nearest (and in case of equal distance, to the lowest) interval but now
2290: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2291: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2292: * probability in order to take into account the bias as a fraction of the way
2293: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2294: * -stepm/2 to stepm/2 .
2295: * For stepm=1 the results are the same as for previous versions of Imach.
2296: * For stepm > 1 the results are less biased than in previous versions.
2297: */
2298: s1=s[mw[mi][i]][i];
2299: s2=s[mw[mi+1][i]][i];
2300: bbh=(double)bh[mi][i]/(double)stepm;
2301: /* bias bh is positive if real duration
2302: * is higher than the multiple of stepm and negative otherwise.
2303: */
2304: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2305: if( s2 > nlstate){
2306: /* i.e. if s2 is a death state and if the date of death is known
2307: then the contribution to the likelihood is the probability to
2308: die between last step unit time and current step unit time,
2309: which is also equal to probability to die before dh
2310: minus probability to die before dh-stepm .
2311: In version up to 0.92 likelihood was computed
2312: as if date of death was unknown. Death was treated as any other
2313: health state: the date of the interview describes the actual state
2314: and not the date of a change in health state. The former idea was
2315: to consider that at each interview the state was recorded
2316: (healthy, disable or death) and IMaCh was corrected; but when we
2317: introduced the exact date of death then we should have modified
2318: the contribution of an exact death to the likelihood. This new
2319: contribution is smaller and very dependent of the step unit
2320: stepm. It is no more the probability to die between last interview
2321: and month of death but the probability to survive from last
2322: interview up to one month before death multiplied by the
2323: probability to die within a month. Thanks to Chris
2324: Jackson for correcting this bug. Former versions increased
2325: mortality artificially. The bad side is that we add another loop
2326: which slows down the processing. The difference can be up to 10%
2327: lower mortality.
2328: */
2329: /* If, at the beginning of the maximization mostly, the
2330: cumulative probability or probability to be dead is
2331: constant (ie = 1) over time d, the difference is equal to
2332: 0. out[s1][3] = savm[s1][3]: probability, being at state
2333: s1 at precedent wave, to be dead a month before current
2334: wave is equal to probability, being at state s1 at
2335: precedent wave, to be dead at mont of the current
2336: wave. Then the observed probability (that this person died)
2337: is null according to current estimated parameter. In fact,
2338: it should be very low but not zero otherwise the log go to
2339: infinity.
2340: */
2341: /* #ifdef INFINITYORIGINAL */
2342: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2343: /* #else */
2344: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2345: /* lli=log(mytinydouble); */
2346: /* else */
2347: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2348: /* #endif */
2349: lli=log(out[s1][s2] - savm[s1][s2]);
2350:
2351: } else if (s2==-2) {
2352: for (j=1,survp=0. ; j<=nlstate; j++)
2353: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2354: /*survp += out[s1][j]; */
2355: lli= log(survp);
2356: }
2357:
2358: else if (s2==-4) {
2359: for (j=3,survp=0. ; j<=nlstate; j++)
2360: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2361: lli= log(survp);
2362: }
2363:
2364: else if (s2==-5) {
2365: for (j=1,survp=0. ; j<=2; j++)
2366: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2367: lli= log(survp);
2368: }
2369:
2370: else{
2371: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2372: /* 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 */
2373: }
2374: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2375: /*if(lli ==000.0)*/
2376: /*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); */
2377: ipmx +=1;
2378: sw += weight[i];
2379: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2380: /* if (lli < log(mytinydouble)){ */
2381: /* 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); */
2382: /* 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]); */
2383: /* } */
2384: } /* end of wave */
2385: } /* end of individual */
2386: } else if(mle==2){
2387: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2388: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2389: for(mi=1; mi<= wav[i]-1; mi++){
2390: for (ii=1;ii<=nlstate+ndeath;ii++)
2391: for (j=1;j<=nlstate+ndeath;j++){
2392: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2393: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2394: }
2395: for(d=0; d<=dh[mi][i]; d++){
2396: newm=savm;
2397: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2398: cov[2]=agexact;
2399: if(nagesqr==1)
2400: cov[3]= agexact*agexact;
2401: for (kk=1; kk<=cptcovage;kk++) {
2402: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2403: }
2404: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2405: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2406: savm=oldm;
2407: oldm=newm;
2408: } /* end mult */
2409:
2410: s1=s[mw[mi][i]][i];
2411: s2=s[mw[mi+1][i]][i];
2412: bbh=(double)bh[mi][i]/(double)stepm;
2413: 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 */
2414: ipmx +=1;
2415: sw += weight[i];
2416: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2417: } /* end of wave */
2418: } /* end of individual */
2419: } else if(mle==3){ /* exponential inter-extrapolation */
2420: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2421: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2422: for(mi=1; mi<= wav[i]-1; mi++){
2423: for (ii=1;ii<=nlstate+ndeath;ii++)
2424: for (j=1;j<=nlstate+ndeath;j++){
2425: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2426: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2427: }
2428: for(d=0; d<dh[mi][i]; d++){
2429: newm=savm;
2430: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2431: cov[2]=agexact;
2432: if(nagesqr==1)
2433: cov[3]= agexact*agexact;
2434: for (kk=1; kk<=cptcovage;kk++) {
2435: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2436: }
2437: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2438: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2439: savm=oldm;
2440: oldm=newm;
2441: } /* end mult */
2442:
2443: s1=s[mw[mi][i]][i];
2444: s2=s[mw[mi+1][i]][i];
2445: bbh=(double)bh[mi][i]/(double)stepm;
2446: 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 */
2447: ipmx +=1;
2448: sw += weight[i];
2449: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2450: } /* end of wave */
2451: } /* end of individual */
2452: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2453: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2454: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2455: for(mi=1; mi<= wav[i]-1; mi++){
2456: for (ii=1;ii<=nlstate+ndeath;ii++)
2457: for (j=1;j<=nlstate+ndeath;j++){
2458: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2459: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2460: }
2461: for(d=0; d<dh[mi][i]; d++){
2462: newm=savm;
2463: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2464: cov[2]=agexact;
2465: if(nagesqr==1)
2466: cov[3]= agexact*agexact;
2467: for (kk=1; kk<=cptcovage;kk++) {
2468: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2469: }
2470:
2471: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2472: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2473: savm=oldm;
2474: oldm=newm;
2475: } /* end mult */
2476:
2477: s1=s[mw[mi][i]][i];
2478: s2=s[mw[mi+1][i]][i];
2479: if( s2 > nlstate){
2480: lli=log(out[s1][s2] - savm[s1][s2]);
2481: }else{
2482: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2483: }
2484: ipmx +=1;
2485: sw += weight[i];
2486: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2487: /* 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]); */
2488: } /* end of wave */
2489: } /* end of individual */
2490: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2491: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2492: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2493: for(mi=1; mi<= wav[i]-1; mi++){
2494: for (ii=1;ii<=nlstate+ndeath;ii++)
2495: for (j=1;j<=nlstate+ndeath;j++){
2496: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2497: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2498: }
2499: for(d=0; d<dh[mi][i]; d++){
2500: newm=savm;
2501: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2502: cov[2]=agexact;
2503: if(nagesqr==1)
2504: cov[3]= agexact*agexact;
2505: for (kk=1; kk<=cptcovage;kk++) {
2506: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2507: }
2508:
2509: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2510: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2511: savm=oldm;
2512: oldm=newm;
2513: } /* end mult */
2514:
2515: s1=s[mw[mi][i]][i];
2516: s2=s[mw[mi+1][i]][i];
2517: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2518: ipmx +=1;
2519: sw += weight[i];
2520: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2521: /*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]);*/
2522: } /* end of wave */
2523: } /* end of individual */
2524: } /* End of if */
2525: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2526: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2527: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2528: return -l;
2529: }
2530:
2531: /*************** log-likelihood *************/
2532: double funcone( double *x)
2533: {
2534: /* Same as likeli but slower because of a lot of printf and if */
2535: int i, ii, j, k, mi, d, kk;
2536: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2537: double **out;
2538: double lli; /* Individual log likelihood */
2539: double llt;
2540: int s1, s2;
2541: double bbh, survp;
2542: double agexact;
2543: /*extern weight */
2544: /* We are differentiating ll according to initial status */
2545: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2546: /*for(i=1;i<imx;i++)
2547: printf(" %d\n",s[4][i]);
2548: */
2549: cov[1]=1.;
2550:
2551: for(k=1; k<=nlstate; k++) ll[k]=0.;
2552:
2553: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2554: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2555: for(mi=1; mi<= wav[i]-1; mi++){
2556: for (ii=1;ii<=nlstate+ndeath;ii++)
2557: for (j=1;j<=nlstate+ndeath;j++){
2558: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2559: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2560: }
2561: for(d=0; d<dh[mi][i]; d++){
2562: newm=savm;
2563: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2564: cov[2]=agexact;
2565: if(nagesqr==1)
2566: cov[3]= agexact*agexact;
2567: for (kk=1; kk<=cptcovage;kk++) {
2568: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2569: }
2570:
2571: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2572: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2573: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2574: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2575: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2576: savm=oldm;
2577: oldm=newm;
2578: } /* end mult */
2579:
2580: s1=s[mw[mi][i]][i];
2581: s2=s[mw[mi+1][i]][i];
2582: bbh=(double)bh[mi][i]/(double)stepm;
2583: /* bias is positive if real duration
2584: * is higher than the multiple of stepm and negative otherwise.
2585: */
2586: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2587: lli=log(out[s1][s2] - savm[s1][s2]);
2588: } else if (s2==-2) {
2589: for (j=1,survp=0. ; j<=nlstate; j++)
2590: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2591: lli= log(survp);
2592: }else if (mle==1){
2593: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2594: } else if(mle==2){
2595: 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 */
2596: } else if(mle==3){ /* exponential inter-extrapolation */
2597: 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 */
2598: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2599: lli=log(out[s1][s2]); /* Original formula */
2600: } else{ /* mle=0 back to 1 */
2601: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2602: /*lli=log(out[s1][s2]); */ /* Original formula */
2603: } /* End of if */
2604: ipmx +=1;
2605: sw += weight[i];
2606: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2607: /*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]); */
2608: if(globpr){
2609: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2610: %11.6f %11.6f %11.6f ", \
2611: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2612: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2613: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2614: llt +=ll[k]*gipmx/gsw;
2615: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2616: }
2617: fprintf(ficresilk," %10.6f\n", -llt);
2618: }
2619: } /* end of wave */
2620: } /* end of individual */
2621: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2622: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2623: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2624: if(globpr==0){ /* First time we count the contributions and weights */
2625: gipmx=ipmx;
2626: gsw=sw;
2627: }
2628: return -l;
2629: }
2630:
2631:
2632: /*************** function likelione ***********/
2633: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2634: {
2635: /* This routine should help understanding what is done with
2636: the selection of individuals/waves and
2637: to check the exact contribution to the likelihood.
2638: Plotting could be done.
2639: */
2640: int k;
2641:
2642: if(*globpri !=0){ /* Just counts and sums, no printings */
2643: strcpy(fileresilk,"ILK_");
2644: strcat(fileresilk,fileresu);
2645: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2646: printf("Problem with resultfile: %s\n", fileresilk);
2647: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2648: }
2649: fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
2650: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %weight 2wlli out sav ");
2651: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2652: for(k=1; k<=nlstate; k++)
2653: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2654: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2655: }
2656:
2657: *fretone=(*funcone)(p);
2658: if(*globpri !=0){
2659: fclose(ficresilk);
2660: if (mle ==0)
2661: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2662: else if(mle >=1)
2663: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2664: fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2665:
2666: fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
2667: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2668: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2669: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2670: fflush(fichtm);
2671:
2672: for (k=1; k<= nlstate ; k++) {
2673: fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
2674: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2675: }
2676: }
2677: return;
2678: }
2679:
2680:
2681: /*********** Maximum Likelihood Estimation ***************/
2682:
2683: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2684: {
2685: int i,j, iter=0;
2686: double **xi;
2687: double fret;
2688: double fretone; /* Only one call to likelihood */
2689: /* char filerespow[FILENAMELENGTH];*/
2690:
2691: #ifdef NLOPT
2692: int creturn;
2693: nlopt_opt opt;
2694: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2695: double *lb;
2696: double minf; /* the minimum objective value, upon return */
2697: double * p1; /* Shifted parameters from 0 instead of 1 */
2698: myfunc_data dinst, *d = &dinst;
2699: #endif
2700:
2701:
2702: xi=matrix(1,npar,1,npar);
2703: for (i=1;i<=npar;i++)
2704: for (j=1;j<=npar;j++)
2705: xi[i][j]=(i==j ? 1.0 : 0.0);
2706: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2707: strcpy(filerespow,"POW_");
2708: strcat(filerespow,fileres);
2709: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2710: printf("Problem with resultfile: %s\n", filerespow);
2711: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2712: }
2713: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2714: for (i=1;i<=nlstate;i++)
2715: for(j=1;j<=nlstate+ndeath;j++)
2716: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2717: fprintf(ficrespow,"\n");
2718: #ifdef POWELL
2719: powell(p,xi,npar,ftol,&iter,&fret,func);
2720: #endif
2721:
2722: #ifdef NLOPT
2723: #ifdef NEWUOA
2724: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2725: #else
2726: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2727: #endif
2728: lb=vector(0,npar-1);
2729: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2730: nlopt_set_lower_bounds(opt, lb);
2731: nlopt_set_initial_step1(opt, 0.1);
2732:
2733: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2734: d->function = func;
2735: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2736: nlopt_set_min_objective(opt, myfunc, d);
2737: nlopt_set_xtol_rel(opt, ftol);
2738: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2739: printf("nlopt failed! %d\n",creturn);
2740: }
2741: else {
2742: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2743: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2744: iter=1; /* not equal */
2745: }
2746: nlopt_destroy(opt);
2747: #endif
2748: free_matrix(xi,1,npar,1,npar);
2749: fclose(ficrespow);
2750: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2751: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2752: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2753:
2754: }
2755:
2756: /**** Computes Hessian and covariance matrix ***/
2757: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2758: {
2759: double **a,**y,*x,pd;
2760: /* double **hess; */
2761: int i, j;
2762: int *indx;
2763:
2764: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2765: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2766: void lubksb(double **a, int npar, int *indx, double b[]) ;
2767: void ludcmp(double **a, int npar, int *indx, double *d) ;
2768: double gompertz(double p[]);
2769: /* hess=matrix(1,npar,1,npar); */
2770:
2771: printf("\nCalculation of the hessian matrix. Wait...\n");
2772: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2773: for (i=1;i<=npar;i++){
2774: printf("%d-",i);fflush(stdout);
2775: fprintf(ficlog,"%d-",i);fflush(ficlog);
2776:
2777: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2778:
2779: /* printf(" %f ",p[i]);
2780: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2781: }
2782:
2783: for (i=1;i<=npar;i++) {
2784: for (j=1;j<=npar;j++) {
2785: if (j>i) {
2786: printf(".%d-%d",i,j);fflush(stdout);
2787: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2788: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2789:
2790: hess[j][i]=hess[i][j];
2791: /*printf(" %lf ",hess[i][j]);*/
2792: }
2793: }
2794: }
2795: printf("\n");
2796: fprintf(ficlog,"\n");
2797:
2798: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2799: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2800:
2801: a=matrix(1,npar,1,npar);
2802: y=matrix(1,npar,1,npar);
2803: x=vector(1,npar);
2804: indx=ivector(1,npar);
2805: for (i=1;i<=npar;i++)
2806: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2807: ludcmp(a,npar,indx,&pd);
2808:
2809: for (j=1;j<=npar;j++) {
2810: for (i=1;i<=npar;i++) x[i]=0;
2811: x[j]=1;
2812: lubksb(a,npar,indx,x);
2813: for (i=1;i<=npar;i++){
2814: matcov[i][j]=x[i];
2815: }
2816: }
2817:
2818: printf("\n#Hessian matrix#\n");
2819: fprintf(ficlog,"\n#Hessian matrix#\n");
2820: for (i=1;i<=npar;i++) {
2821: for (j=1;j<=npar;j++) {
2822: printf("%.6e ",hess[i][j]);
2823: fprintf(ficlog,"%.6e ",hess[i][j]);
2824: }
2825: printf("\n");
2826: fprintf(ficlog,"\n");
2827: }
2828:
2829: /* printf("\n#Covariance matrix#\n"); */
2830: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2831: /* for (i=1;i<=npar;i++) { */
2832: /* for (j=1;j<=npar;j++) { */
2833: /* printf("%.6e ",matcov[i][j]); */
2834: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2835: /* } */
2836: /* printf("\n"); */
2837: /* fprintf(ficlog,"\n"); */
2838: /* } */
2839:
2840: /* Recompute Inverse */
2841: /* for (i=1;i<=npar;i++) */
2842: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2843: /* ludcmp(a,npar,indx,&pd); */
2844:
2845: /* printf("\n#Hessian matrix recomputed#\n"); */
2846:
2847: /* for (j=1;j<=npar;j++) { */
2848: /* for (i=1;i<=npar;i++) x[i]=0; */
2849: /* x[j]=1; */
2850: /* lubksb(a,npar,indx,x); */
2851: /* for (i=1;i<=npar;i++){ */
2852: /* y[i][j]=x[i]; */
2853: /* printf("%.3e ",y[i][j]); */
2854: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2855: /* } */
2856: /* printf("\n"); */
2857: /* fprintf(ficlog,"\n"); */
2858: /* } */
2859:
2860: /* Verifying the inverse matrix */
2861: #ifdef DEBUGHESS
2862: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2863:
2864: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2865: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2866:
2867: for (j=1;j<=npar;j++) {
2868: for (i=1;i<=npar;i++){
2869: printf("%.2f ",y[i][j]);
2870: fprintf(ficlog,"%.2f ",y[i][j]);
2871: }
2872: printf("\n");
2873: fprintf(ficlog,"\n");
2874: }
2875: #endif
2876:
2877: free_matrix(a,1,npar,1,npar);
2878: free_matrix(y,1,npar,1,npar);
2879: free_vector(x,1,npar);
2880: free_ivector(indx,1,npar);
2881: /* free_matrix(hess,1,npar,1,npar); */
2882:
2883:
2884: }
2885:
2886: /*************** hessian matrix ****************/
2887: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2888: { /* Around values of x, computes the function func and returns the scales delti and hessian */
2889: int i;
2890: int l=1, lmax=20;
2891: double k1,k2, res, fx;
2892: double p2[MAXPARM+1]; /* identical to x */
2893: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2894: int k=0,kmax=10;
2895: double l1;
2896:
2897: fx=func(x);
2898: for (i=1;i<=npar;i++) p2[i]=x[i];
2899: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2900: l1=pow(10,l);
2901: delts=delt;
2902: for(k=1 ; k <kmax; k=k+1){
2903: delt = delta*(l1*k);
2904: p2[theta]=x[theta] +delt;
2905: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2906: p2[theta]=x[theta]-delt;
2907: k2=func(p2)-fx;
2908: /*res= (k1-2.0*fx+k2)/delt/delt; */
2909: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
2910:
2911: #ifdef DEBUGHESSII
2912: 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);
2913: 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);
2914: #endif
2915: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2916: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2917: k=kmax;
2918: }
2919: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2920: k=kmax; l=lmax*10;
2921: }
2922: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2923: delts=delt;
2924: }
2925: } /* End loop k */
2926: }
2927: delti[theta]=delts;
2928: return res;
2929:
2930: }
2931:
2932: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2933: {
2934: int i;
2935: int l=1, lmax=20;
2936: double k1,k2,k3,k4,res,fx;
2937: double p2[MAXPARM+1];
2938: int k, kmax=1;
2939: double v1, v2, cv12, lc1, lc2;
2940:
2941: fx=func(x);
2942: for (k=1; k<=kmax; k=k+10) {
2943: for (i=1;i<=npar;i++) p2[i]=x[i];
2944: p2[thetai]=x[thetai]+delti[thetai]*k;
2945: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
2946: k1=func(p2)-fx;
2947:
2948: p2[thetai]=x[thetai]+delti[thetai]*k;
2949: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
2950: k2=func(p2)-fx;
2951:
2952: p2[thetai]=x[thetai]-delti[thetai]*k;
2953: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
2954: k3=func(p2)-fx;
2955:
2956: p2[thetai]=x[thetai]-delti[thetai]*k;
2957: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
2958: k4=func(p2)-fx;
2959: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
2960: if(k1*k2*k3*k4 <0.){
2961: kmax=kmax+10;
2962: if(kmax >=10){
2963: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
2964: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
2965: 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);
2966: 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);
2967: }
2968: }
2969: #ifdef DEBUGHESSIJ
2970: v1=hess[thetai][thetai];
2971: v2=hess[thetaj][thetaj];
2972: cv12=res;
2973: /* Computing eigen value of Hessian matrix */
2974: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
2975: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
2976: if ((lc2 <0) || (lc1 <0) ){
2977: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
2978: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
2979: 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);
2980: 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);
2981: }
2982: #endif
2983: }
2984: return res;
2985: }
2986:
2987: /* Not done yet: Was supposed to fix if not exactly at the maximum */
2988: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
2989: /* { */
2990: /* int i; */
2991: /* int l=1, lmax=20; */
2992: /* double k1,k2,k3,k4,res,fx; */
2993: /* double p2[MAXPARM+1]; */
2994: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
2995: /* int k=0,kmax=10; */
2996: /* double l1; */
2997:
2998: /* fx=func(x); */
2999: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3000: /* l1=pow(10,l); */
3001: /* delts=delt; */
3002: /* for(k=1 ; k <kmax; k=k+1){ */
3003: /* delt = delti*(l1*k); */
3004: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3005: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3006: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3007: /* k1=func(p2)-fx; */
3008:
3009: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3010: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3011: /* k2=func(p2)-fx; */
3012:
3013: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3014: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3015: /* k3=func(p2)-fx; */
3016:
3017: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3018: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3019: /* k4=func(p2)-fx; */
3020: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3021: /* #ifdef DEBUGHESSIJ */
3022: /* 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); */
3023: /* 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); */
3024: /* #endif */
3025: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3026: /* k=kmax; */
3027: /* } */
3028: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3029: /* k=kmax; l=lmax*10; */
3030: /* } */
3031: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3032: /* delts=delt; */
3033: /* } */
3034: /* } /\* End loop k *\/ */
3035: /* } */
3036: /* delti[theta]=delts; */
3037: /* return res; */
3038: /* } */
3039:
3040:
3041: /************** Inverse of matrix **************/
3042: void ludcmp(double **a, int n, int *indx, double *d)
3043: {
3044: int i,imax,j,k;
3045: double big,dum,sum,temp;
3046: double *vv;
3047:
3048: vv=vector(1,n);
3049: *d=1.0;
3050: for (i=1;i<=n;i++) {
3051: big=0.0;
3052: for (j=1;j<=n;j++)
3053: if ((temp=fabs(a[i][j])) > big) big=temp;
3054: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3055: vv[i]=1.0/big;
3056: }
3057: for (j=1;j<=n;j++) {
3058: for (i=1;i<j;i++) {
3059: sum=a[i][j];
3060: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3061: a[i][j]=sum;
3062: }
3063: big=0.0;
3064: for (i=j;i<=n;i++) {
3065: sum=a[i][j];
3066: for (k=1;k<j;k++)
3067: sum -= a[i][k]*a[k][j];
3068: a[i][j]=sum;
3069: if ( (dum=vv[i]*fabs(sum)) >= big) {
3070: big=dum;
3071: imax=i;
3072: }
3073: }
3074: if (j != imax) {
3075: for (k=1;k<=n;k++) {
3076: dum=a[imax][k];
3077: a[imax][k]=a[j][k];
3078: a[j][k]=dum;
3079: }
3080: *d = -(*d);
3081: vv[imax]=vv[j];
3082: }
3083: indx[j]=imax;
3084: if (a[j][j] == 0.0) a[j][j]=TINY;
3085: if (j != n) {
3086: dum=1.0/(a[j][j]);
3087: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3088: }
3089: }
3090: free_vector(vv,1,n); /* Doesn't work */
3091: ;
3092: }
3093:
3094: void lubksb(double **a, int n, int *indx, double b[])
3095: {
3096: int i,ii=0,ip,j;
3097: double sum;
3098:
3099: for (i=1;i<=n;i++) {
3100: ip=indx[i];
3101: sum=b[ip];
3102: b[ip]=b[i];
3103: if (ii)
3104: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3105: else if (sum) ii=i;
3106: b[i]=sum;
3107: }
3108: for (i=n;i>=1;i--) {
3109: sum=b[i];
3110: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3111: b[i]=sum/a[i][i];
3112: }
3113: }
3114:
3115: void pstamp(FILE *fichier)
3116: {
3117: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3118: }
3119:
3120: /************ Frequencies ********************/
3121: 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[])
3122: { /* Some frequencies */
3123:
3124: int i, m, jk, j1, bool, z1,j;
3125: int first;
3126: double ***freq; /* Frequencies */
3127: double *pp, **prop;
3128: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3129: char fileresp[FILENAMELENGTH];
3130:
3131: pp=vector(1,nlstate);
3132: prop=matrix(1,nlstate,iagemin,iagemax+3);
3133: strcpy(fileresp,"P_");
3134: strcat(fileresp,fileresu);
3135: if((ficresp=fopen(fileresp,"w"))==NULL) {
3136: printf("Problem with prevalence resultfile: %s\n", fileresp);
3137: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3138: exit(0);
3139: }
3140: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3141: j1=0;
3142:
3143: j=cptcoveff;
3144: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3145:
3146: first=1;
3147:
3148: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3149: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3150: /* j1++; */
3151: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
3152: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3153: scanf("%d", i);*/
3154: for (i=-5; i<=nlstate+ndeath; i++)
3155: for (jk=-5; jk<=nlstate+ndeath; jk++)
3156: for(m=iagemin; m <= iagemax+3; m++)
3157: freq[i][jk][m]=0;
3158:
3159: for (i=1; i<=nlstate; i++)
3160: for(m=iagemin; m <= iagemax+3; m++)
3161: prop[i][m]=0;
3162:
3163: dateintsum=0;
3164: k2cpt=0;
3165: for (i=1; i<=imx; i++) {
3166: bool=1;
3167: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3168: for (z1=1; z1<=cptcoveff; z1++)
3169: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3170: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3171: bool=0;
3172: /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n",
3173: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3174: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3175: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3176: }
3177: }
3178:
3179: if (bool==1){
3180: for(m=firstpass; m<=lastpass; m++){
3181: k2=anint[m][i]+(mint[m][i]/12.);
3182: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3183: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3184: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3185: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
3186: if (m<lastpass) {
3187: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3188: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3189: }
3190:
3191: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
3192: dateintsum=dateintsum+k2;
3193: k2cpt++;
3194: }
3195: /*}*/
3196: }
3197: }
3198: } /* end i */
3199:
3200: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3201: pstamp(ficresp);
3202: if (cptcovn>0) {
3203: fprintf(ficresp, "\n#********** Variable ");
3204: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3205: fprintf(ficresp, "**********\n#");
3206: fprintf(ficlog, "\n#********** Variable ");
3207: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3208: fprintf(ficlog, "**********\n#");
3209: }
3210: for(i=1; i<=nlstate;i++)
3211: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3212: fprintf(ficresp, "\n");
3213:
3214: for(i=iagemin; i <= iagemax+3; i++){
3215: if(i==iagemax+3){
3216: fprintf(ficlog,"Total");
3217: }else{
3218: if(first==1){
3219: first=0;
3220: printf("See log file for details...\n");
3221: }
3222: fprintf(ficlog,"Age %d", i);
3223: }
3224: for(jk=1; jk <=nlstate ; jk++){
3225: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3226: pp[jk] += freq[jk][m][i];
3227: }
3228: for(jk=1; jk <=nlstate ; jk++){
3229: for(m=-1, pos=0; m <=0 ; m++)
3230: pos += freq[jk][m][i];
3231: if(pp[jk]>=1.e-10){
3232: if(first==1){
3233: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3234: }
3235: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3236: }else{
3237: if(first==1)
3238: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3239: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3240: }
3241: }
3242:
3243: for(jk=1; jk <=nlstate ; jk++){
3244: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3245: pp[jk] += freq[jk][m][i];
3246: }
3247: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3248: pos += pp[jk];
3249: posprop += prop[jk][i];
3250: }
3251: for(jk=1; jk <=nlstate ; jk++){
3252: if(pos>=1.e-5){
3253: if(first==1)
3254: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3255: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3256: }else{
3257: if(first==1)
3258: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3259: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3260: }
3261: if( i <= iagemax){
3262: if(pos>=1.e-5){
3263: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3264: /*probs[i][jk][j1]= pp[jk]/pos;*/
3265: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3266: }
3267: else
3268: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3269: }
3270: }
3271:
3272: for(jk=-1; jk <=nlstate+ndeath; jk++)
3273: for(m=-1; m <=nlstate+ndeath; m++)
3274: if(freq[jk][m][i] !=0 ) {
3275: if(first==1)
3276: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3277: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3278: }
3279: if(i <= iagemax)
3280: fprintf(ficresp,"\n");
3281: if(first==1)
3282: printf("Others in log...\n");
3283: fprintf(ficlog,"\n");
3284: }
3285: /*}*/
3286: }
3287: dateintmean=dateintsum/k2cpt;
3288:
3289: fclose(ficresp);
3290: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3291: free_vector(pp,1,nlstate);
3292: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3293: /* End of Freq */
3294: }
3295:
3296: /************ Prevalence ********************/
3297: 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)
3298: {
3299: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3300: in each health status at the date of interview (if between dateprev1 and dateprev2).
3301: We still use firstpass and lastpass as another selection.
3302: */
3303:
3304: int i, m, jk, j1, bool, z1,j;
3305:
3306: double **prop;
3307: double posprop;
3308: double y2; /* in fractional years */
3309: int iagemin, iagemax;
3310: int first; /** to stop verbosity which is redirected to log file */
3311:
3312: iagemin= (int) agemin;
3313: iagemax= (int) agemax;
3314: /*pp=vector(1,nlstate);*/
3315: prop=matrix(1,nlstate,iagemin,iagemax+3);
3316: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3317: j1=0;
3318:
3319: /*j=cptcoveff;*/
3320: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3321:
3322: first=1;
3323: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3324: /*for(i1=1; i1<=ncodemax[k1];i1++){
3325: j1++;*/
3326:
3327: for (i=1; i<=nlstate; i++)
3328: for(m=iagemin; m <= iagemax+3; m++)
3329: prop[i][m]=0.0;
3330:
3331: for (i=1; i<=imx; i++) { /* Each individual */
3332: bool=1;
3333: if (cptcovn>0) {
3334: for (z1=1; z1<=cptcoveff; z1++)
3335: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3336: bool=0;
3337: }
3338: if (bool==1) {
3339: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3340: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3341: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3342: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3343: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3344: 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);
3345: if (s[m][i]>0 && s[m][i]<=nlstate) {
3346: /*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]]);*/
3347: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3348: prop[s[m][i]][iagemax+3] += weight[i];
3349: }
3350: }
3351: } /* end selection of waves */
3352: }
3353: }
3354: for(i=iagemin; i <= iagemax+3; i++){
3355: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3356: posprop += prop[jk][i];
3357: }
3358:
3359: for(jk=1; jk <=nlstate ; jk++){
3360: if( i <= iagemax){
3361: if(posprop>=1.e-5){
3362: probs[i][jk][j1]= prop[jk][i]/posprop;
3363: } else{
3364: if(first==1){
3365: first=0;
3366: 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]);
3367: }
3368: }
3369: }
3370: }/* end jk */
3371: }/* end i */
3372: /*} *//* end i1 */
3373: } /* end j1 */
3374:
3375: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3376: /*free_vector(pp,1,nlstate);*/
3377: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3378: } /* End of prevalence */
3379:
3380: /************* Waves Concatenation ***************/
3381:
3382: 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)
3383: {
3384: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3385: Death is a valid wave (if date is known).
3386: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3387: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3388: and mw[mi+1][i]. dh depends on stepm.
3389: */
3390:
3391: int i, mi, m;
3392: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3393: double sum=0., jmean=0.;*/
3394: int first;
3395: int j, k=0,jk, ju, jl;
3396: double sum=0.;
3397: first=0;
3398: jmin=100000;
3399: jmax=-1;
3400: jmean=0.;
3401: for(i=1; i<=imx; i++){
3402: mi=0;
3403: m=firstpass;
3404: while(s[m][i] <= nlstate){
3405: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3406: mw[++mi][i]=m;
3407: if(m >=lastpass)
3408: break;
3409: else
3410: m++;
3411: }/* end while */
3412: if (s[m][i] > nlstate){
3413: mi++; /* Death is another wave */
3414: /* if(mi==0) never been interviewed correctly before death */
3415: /* Only death is a correct wave */
3416: mw[mi][i]=m;
3417: }
3418:
3419: wav[i]=mi;
3420: if(mi==0){
3421: nbwarn++;
3422: if(first==0){
3423: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3424: first=1;
3425: }
3426: if(first==1){
3427: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3428: }
3429: } /* end mi==0 */
3430: } /* End individuals */
3431:
3432: for(i=1; i<=imx; i++){
3433: for(mi=1; mi<wav[i];mi++){
3434: if (stepm <=0)
3435: dh[mi][i]=1;
3436: else{
3437: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3438: if (agedc[i] < 2*AGESUP) {
3439: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3440: if(j==0) j=1; /* Survives at least one month after exam */
3441: else if(j<0){
3442: nberr++;
3443: 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]);
3444: j=1; /* Temporary Dangerous patch */
3445: 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);
3446: 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]);
3447: 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);
3448: }
3449: k=k+1;
3450: if (j >= jmax){
3451: jmax=j;
3452: ijmax=i;
3453: }
3454: if (j <= jmin){
3455: jmin=j;
3456: ijmin=i;
3457: }
3458: sum=sum+j;
3459: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3460: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3461: }
3462: }
3463: else{
3464: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3465: /* 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]); */
3466:
3467: k=k+1;
3468: if (j >= jmax) {
3469: jmax=j;
3470: ijmax=i;
3471: }
3472: else if (j <= jmin){
3473: jmin=j;
3474: ijmin=i;
3475: }
3476: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3477: /*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]);*/
3478: if(j<0){
3479: nberr++;
3480: 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]);
3481: 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]);
3482: }
3483: sum=sum+j;
3484: }
3485: jk= j/stepm;
3486: jl= j -jk*stepm;
3487: ju= j -(jk+1)*stepm;
3488: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3489: if(jl==0){
3490: dh[mi][i]=jk;
3491: bh[mi][i]=0;
3492: }else{ /* We want a negative bias in order to only have interpolation ie
3493: * to avoid the price of an extra matrix product in likelihood */
3494: dh[mi][i]=jk+1;
3495: bh[mi][i]=ju;
3496: }
3497: }else{
3498: if(jl <= -ju){
3499: dh[mi][i]=jk;
3500: bh[mi][i]=jl; /* bias is positive if real duration
3501: * is higher than the multiple of stepm and negative otherwise.
3502: */
3503: }
3504: else{
3505: dh[mi][i]=jk+1;
3506: bh[mi][i]=ju;
3507: }
3508: if(dh[mi][i]==0){
3509: dh[mi][i]=1; /* At least one step */
3510: bh[mi][i]=ju; /* At least one step */
3511: /* 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);*/
3512: }
3513: } /* end if mle */
3514: }
3515: } /* end wave */
3516: }
3517: jmean=sum/k;
3518: 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);
3519: 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);
3520: }
3521:
3522: /*********** Tricode ****************************/
3523: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3524: {
3525: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3526: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3527: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3528: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3529: * nbcode[Tvar[j]][1]=
3530: */
3531:
3532: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3533: int modmaxcovj=0; /* Modality max of covariates j */
3534: int cptcode=0; /* Modality max of covariates j */
3535: int modmincovj=0; /* Modality min of covariates j */
3536:
3537:
3538: cptcoveff=0;
3539:
3540: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3541:
3542: /* Loop on covariates without age and products */
3543: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3544: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3545: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3546: modality of this covariate Vj*/
3547: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3548: * If product of Vn*Vm, still boolean *:
3549: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3550: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3551: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3552: modality of the nth covariate of individual i. */
3553: if (ij > modmaxcovj)
3554: modmaxcovj=ij;
3555: else if (ij < modmincovj)
3556: modmincovj=ij;
3557: if ((ij < -1) && (ij > NCOVMAX)){
3558: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3559: exit(1);
3560: }else
3561: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3562: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3563: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3564: /* getting the maximum value of the modality of the covariate
3565: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3566: female is 1, then modmaxcovj=1.*/
3567: } /* end for loop on individuals i */
3568: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3569: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3570: cptcode=modmaxcovj;
3571: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3572: /*for (i=0; i<=cptcode; i++) {*/
3573: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3574: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3575: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3576: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3577: if( k != -1){
3578: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3579: covariate for which somebody answered excluding
3580: undefined. Usually 2: 0 and 1. */
3581: }
3582: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3583: covariate for which somebody answered including
3584: undefined. Usually 3: -1, 0 and 1. */
3585: }
3586: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3587: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3588: } /* Ndum[-1] number of undefined modalities */
3589:
3590: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3591: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3592: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3593: modmincovj=3; modmaxcovj = 7;
3594: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3595: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3596: defining two dummy variables: variables V1_1 and V1_2.
3597: nbcode[Tvar[j]][ij]=k;
3598: nbcode[Tvar[j]][1]=0;
3599: nbcode[Tvar[j]][2]=1;
3600: nbcode[Tvar[j]][3]=2;
3601: To be continued (not working yet).
3602: */
3603: ij=0; /* ij is similar to i but can jump over null modalities */
3604: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
3605: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3606: break;
3607: }
3608: ij++;
3609: nbcode[Tvar[j]][ij]=i; /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
3610: cptcode = ij; /* New max modality for covar j */
3611: } /* end of loop on modality i=-1 to 1 or more */
3612:
3613: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3614: /* /\*recode from 0 *\/ */
3615: /* k is a modality. If we have model=V1+V1*sex */
3616: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3617: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3618: /* } */
3619: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3620: /* if (ij > ncodemax[j]) { */
3621: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3622: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3623: /* break; */
3624: /* } */
3625: /* } /\* end of loop on modality k *\/ */
3626: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3627:
3628: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3629:
3630: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3631: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3632: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3633: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3634: }
3635:
3636: ij=0;
3637: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3638: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3639: if((Ndum[i]!=0) && (i<=ncovcol)){
3640: ij++;
3641: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3642: Tvaraff[ij]=i; /*For printing (unclear) */
3643: }else{
3644: /* Tvaraff[ij]=0; */
3645: }
3646: }
3647: /* ij--; */
3648: cptcoveff=ij; /*Number of total covariates*/
3649:
3650: }
3651:
3652:
3653: /*********** Health Expectancies ****************/
3654:
3655: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3656:
3657: {
3658: /* Health expectancies, no variances */
3659: int i, j, nhstepm, hstepm, h, nstepm;
3660: int nhstepma, nstepma; /* Decreasing with age */
3661: double age, agelim, hf;
3662: double ***p3mat;
3663: double eip;
3664:
3665: pstamp(ficreseij);
3666: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3667: fprintf(ficreseij,"# Age");
3668: for(i=1; i<=nlstate;i++){
3669: for(j=1; j<=nlstate;j++){
3670: fprintf(ficreseij," e%1d%1d ",i,j);
3671: }
3672: fprintf(ficreseij," e%1d. ",i);
3673: }
3674: fprintf(ficreseij,"\n");
3675:
3676:
3677: if(estepm < stepm){
3678: printf ("Problem %d lower than %d\n",estepm, stepm);
3679: }
3680: else hstepm=estepm;
3681: /* We compute the life expectancy from trapezoids spaced every estepm months
3682: * This is mainly to measure the difference between two models: for example
3683: * if stepm=24 months pijx are given only every 2 years and by summing them
3684: * we are calculating an estimate of the Life Expectancy assuming a linear
3685: * progression in between and thus overestimating or underestimating according
3686: * to the curvature of the survival function. If, for the same date, we
3687: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3688: * to compare the new estimate of Life expectancy with the same linear
3689: * hypothesis. A more precise result, taking into account a more precise
3690: * curvature will be obtained if estepm is as small as stepm. */
3691:
3692: /* For example we decided to compute the life expectancy with the smallest unit */
3693: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3694: nhstepm is the number of hstepm from age to agelim
3695: nstepm is the number of stepm from age to agelin.
3696: Look at hpijx to understand the reason of that which relies in memory size
3697: and note for a fixed period like estepm months */
3698: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3699: survival function given by stepm (the optimization length). Unfortunately it
3700: means that if the survival funtion is printed only each two years of age and if
3701: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3702: results. So we changed our mind and took the option of the best precision.
3703: */
3704: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3705:
3706: agelim=AGESUP;
3707: /* If stepm=6 months */
3708: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3709: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3710:
3711: /* nhstepm age range expressed in number of stepm */
3712: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3713: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3714: /* if (stepm >= YEARM) hstepm=1;*/
3715: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3716: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3717:
3718: for (age=bage; age<=fage; age ++){
3719: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3720: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3721: /* if (stepm >= YEARM) hstepm=1;*/
3722: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3723:
3724: /* If stepm=6 months */
3725: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3726: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3727:
3728: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3729:
3730: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3731:
3732: printf("%d|",(int)age);fflush(stdout);
3733: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3734:
3735: /* Computing expectancies */
3736: for(i=1; i<=nlstate;i++)
3737: for(j=1; j<=nlstate;j++)
3738: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3739: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3740:
3741: /* 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]);*/
3742:
3743: }
3744:
3745: fprintf(ficreseij,"%3.0f",age );
3746: for(i=1; i<=nlstate;i++){
3747: eip=0;
3748: for(j=1; j<=nlstate;j++){
3749: eip +=eij[i][j][(int)age];
3750: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3751: }
3752: fprintf(ficreseij,"%9.4f", eip );
3753: }
3754: fprintf(ficreseij,"\n");
3755:
3756: }
3757: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3758: printf("\n");
3759: fprintf(ficlog,"\n");
3760:
3761: }
3762:
3763: 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[] )
3764:
3765: {
3766: /* Covariances of health expectancies eij and of total life expectancies according
3767: to initial status i, ei. .
3768: */
3769: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3770: int nhstepma, nstepma; /* Decreasing with age */
3771: double age, agelim, hf;
3772: double ***p3matp, ***p3matm, ***varhe;
3773: double **dnewm,**doldm;
3774: double *xp, *xm;
3775: double **gp, **gm;
3776: double ***gradg, ***trgradg;
3777: int theta;
3778:
3779: double eip, vip;
3780:
3781: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3782: xp=vector(1,npar);
3783: xm=vector(1,npar);
3784: dnewm=matrix(1,nlstate*nlstate,1,npar);
3785: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3786:
3787: pstamp(ficresstdeij);
3788: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3789: fprintf(ficresstdeij,"# Age");
3790: for(i=1; i<=nlstate;i++){
3791: for(j=1; j<=nlstate;j++)
3792: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3793: fprintf(ficresstdeij," e%1d. ",i);
3794: }
3795: fprintf(ficresstdeij,"\n");
3796:
3797: pstamp(ficrescveij);
3798: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3799: fprintf(ficrescveij,"# Age");
3800: for(i=1; i<=nlstate;i++)
3801: for(j=1; j<=nlstate;j++){
3802: cptj= (j-1)*nlstate+i;
3803: for(i2=1; i2<=nlstate;i2++)
3804: for(j2=1; j2<=nlstate;j2++){
3805: cptj2= (j2-1)*nlstate+i2;
3806: if(cptj2 <= cptj)
3807: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3808: }
3809: }
3810: fprintf(ficrescveij,"\n");
3811:
3812: if(estepm < stepm){
3813: printf ("Problem %d lower than %d\n",estepm, stepm);
3814: }
3815: else hstepm=estepm;
3816: /* We compute the life expectancy from trapezoids spaced every estepm months
3817: * This is mainly to measure the difference between two models: for example
3818: * if stepm=24 months pijx are given only every 2 years and by summing them
3819: * we are calculating an estimate of the Life Expectancy assuming a linear
3820: * progression in between and thus overestimating or underestimating according
3821: * to the curvature of the survival function. If, for the same date, we
3822: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3823: * to compare the new estimate of Life expectancy with the same linear
3824: * hypothesis. A more precise result, taking into account a more precise
3825: * curvature will be obtained if estepm is as small as stepm. */
3826:
3827: /* For example we decided to compute the life expectancy with the smallest unit */
3828: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3829: nhstepm is the number of hstepm from age to agelim
3830: nstepm is the number of stepm from age to agelin.
3831: Look at hpijx to understand the reason of that which relies in memory size
3832: and note for a fixed period like estepm months */
3833: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3834: survival function given by stepm (the optimization length). Unfortunately it
3835: means that if the survival funtion is printed only each two years of age and if
3836: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3837: results. So we changed our mind and took the option of the best precision.
3838: */
3839: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3840:
3841: /* If stepm=6 months */
3842: /* nhstepm age range expressed in number of stepm */
3843: agelim=AGESUP;
3844: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3845: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3846: /* if (stepm >= YEARM) hstepm=1;*/
3847: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3848:
3849: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3850: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3851: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3852: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3853: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3854: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3855:
3856: for (age=bage; age<=fage; age ++){
3857: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3858: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3859: /* if (stepm >= YEARM) hstepm=1;*/
3860: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3861:
3862: /* If stepm=6 months */
3863: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3864: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3865:
3866: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3867:
3868: /* Computing Variances of health expectancies */
3869: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3870: decrease memory allocation */
3871: for(theta=1; theta <=npar; theta++){
3872: for(i=1; i<=npar; i++){
3873: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3874: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3875: }
3876: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3877: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3878:
3879: for(j=1; j<= nlstate; j++){
3880: for(i=1; i<=nlstate; i++){
3881: for(h=0; h<=nhstepm-1; h++){
3882: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3883: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3884: }
3885: }
3886: }
3887:
3888: for(ij=1; ij<= nlstate*nlstate; ij++)
3889: for(h=0; h<=nhstepm-1; h++){
3890: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3891: }
3892: }/* End theta */
3893:
3894:
3895: for(h=0; h<=nhstepm-1; h++)
3896: for(j=1; j<=nlstate*nlstate;j++)
3897: for(theta=1; theta <=npar; theta++)
3898: trgradg[h][j][theta]=gradg[h][theta][j];
3899:
3900:
3901: for(ij=1;ij<=nlstate*nlstate;ij++)
3902: for(ji=1;ji<=nlstate*nlstate;ji++)
3903: varhe[ij][ji][(int)age] =0.;
3904:
3905: printf("%d|",(int)age);fflush(stdout);
3906: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3907: for(h=0;h<=nhstepm-1;h++){
3908: for(k=0;k<=nhstepm-1;k++){
3909: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3910: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3911: for(ij=1;ij<=nlstate*nlstate;ij++)
3912: for(ji=1;ji<=nlstate*nlstate;ji++)
3913: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3914: }
3915: }
3916:
3917: /* Computing expectancies */
3918: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3919: for(i=1; i<=nlstate;i++)
3920: for(j=1; j<=nlstate;j++)
3921: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3922: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3923:
3924: /* 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]);*/
3925:
3926: }
3927:
3928: fprintf(ficresstdeij,"%3.0f",age );
3929: for(i=1; i<=nlstate;i++){
3930: eip=0.;
3931: vip=0.;
3932: for(j=1; j<=nlstate;j++){
3933: eip += eij[i][j][(int)age];
3934: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3935: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3936: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3937: }
3938: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3939: }
3940: fprintf(ficresstdeij,"\n");
3941:
3942: fprintf(ficrescveij,"%3.0f",age );
3943: for(i=1; i<=nlstate;i++)
3944: for(j=1; j<=nlstate;j++){
3945: cptj= (j-1)*nlstate+i;
3946: for(i2=1; i2<=nlstate;i2++)
3947: for(j2=1; j2<=nlstate;j2++){
3948: cptj2= (j2-1)*nlstate+i2;
3949: if(cptj2 <= cptj)
3950: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3951: }
3952: }
3953: fprintf(ficrescveij,"\n");
3954:
3955: }
3956: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3957: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3958: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3959: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3960: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3961: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3962: printf("\n");
3963: fprintf(ficlog,"\n");
3964:
3965: free_vector(xm,1,npar);
3966: free_vector(xp,1,npar);
3967: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3968: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3969: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3970: }
3971:
3972: /************ Variance ******************/
3973: 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 *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
3974: {
3975: /* Variance of health expectancies */
3976: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3977: /* double **newm;*/
3978: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3979:
3980: int movingaverage();
3981: double **dnewm,**doldm;
3982: double **dnewmp,**doldmp;
3983: int i, j, nhstepm, hstepm, h, nstepm ;
3984: int k;
3985: double *xp;
3986: double **gp, **gm; /* for var eij */
3987: double ***gradg, ***trgradg; /*for var eij */
3988: double **gradgp, **trgradgp; /* for var p point j */
3989: double *gpp, *gmp; /* for var p point j */
3990: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3991: double ***p3mat;
3992: double age,agelim, hf;
3993: double ***mobaverage;
3994: int theta;
3995: char digit[4];
3996: char digitp[25];
3997:
3998: char fileresprobmorprev[FILENAMELENGTH];
3999:
4000: if(popbased==1){
4001: if(mobilav!=0)
4002: strcpy(digitp,"-POPULBASED-MOBILAV_");
4003: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4004: }
4005: else
4006: strcpy(digitp,"-STABLBASED_");
4007:
4008: if (mobilav!=0) {
4009: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4010: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4011: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4012: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4013: }
4014: }
4015:
4016: strcpy(fileresprobmorprev,"PRMORPREV-");
4017: sprintf(digit,"%-d",ij);
4018: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4019: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4020: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4021: strcat(fileresprobmorprev,fileresu);
4022: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4023: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4024: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4025: }
4026: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4027:
4028: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4029: pstamp(ficresprobmorprev);
4030: 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);
4031: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4032: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4033: fprintf(ficresprobmorprev," p.%-d SE",j);
4034: for(i=1; i<=nlstate;i++)
4035: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4036: }
4037: fprintf(ficresprobmorprev,"\n");
4038: fprintf(ficgp,"\n# Routine varevsij");
4039: fprintf(ficgp,"\nunset title \n");
4040: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4041: 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");
4042: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4043: /* } */
4044: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4045: pstamp(ficresvij);
4046: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4047: if(popbased==1)
4048: 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);
4049: else
4050: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4051: fprintf(ficresvij,"# Age");
4052: for(i=1; i<=nlstate;i++)
4053: for(j=1; j<=nlstate;j++)
4054: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4055: fprintf(ficresvij,"\n");
4056:
4057: xp=vector(1,npar);
4058: dnewm=matrix(1,nlstate,1,npar);
4059: doldm=matrix(1,nlstate,1,nlstate);
4060: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4061: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4062:
4063: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4064: gpp=vector(nlstate+1,nlstate+ndeath);
4065: gmp=vector(nlstate+1,nlstate+ndeath);
4066: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4067:
4068: if(estepm < stepm){
4069: printf ("Problem %d lower than %d\n",estepm, stepm);
4070: }
4071: else hstepm=estepm;
4072: /* For example we decided to compute the life expectancy with the smallest unit */
4073: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4074: nhstepm is the number of hstepm from age to agelim
4075: nstepm is the number of stepm from age to agelin.
4076: Look at function hpijx to understand why (it is linked to memory size questions) */
4077: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4078: survival function given by stepm (the optimization length). Unfortunately it
4079: means that if the survival funtion is printed every two years of age and if
4080: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4081: results. So we changed our mind and took the option of the best precision.
4082: */
4083: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4084: agelim = AGESUP;
4085: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4086: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4087: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4088: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4089: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4090: gp=matrix(0,nhstepm,1,nlstate);
4091: gm=matrix(0,nhstepm,1,nlstate);
4092:
4093:
4094: for(theta=1; theta <=npar; theta++){
4095: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4096: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4097: }
4098: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4099: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4100:
4101: if (popbased==1) {
4102: if(mobilav ==0){
4103: for(i=1; i<=nlstate;i++)
4104: prlim[i][i]=probs[(int)age][i][ij];
4105: }else{ /* mobilav */
4106: for(i=1; i<=nlstate;i++)
4107: prlim[i][i]=mobaverage[(int)age][i][ij];
4108: }
4109: }
4110:
4111: for(j=1; j<= nlstate; j++){
4112: for(h=0; h<=nhstepm; h++){
4113: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4114: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4115: }
4116: }
4117: /* This for computing probability of death (h=1 means
4118: computed over hstepm matrices product = hstepm*stepm months)
4119: as a weighted average of prlim.
4120: */
4121: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4122: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4123: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4124: }
4125: /* end probability of death */
4126:
4127: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4128: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4129: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4130: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
4131:
4132: if (popbased==1) {
4133: if(mobilav ==0){
4134: for(i=1; i<=nlstate;i++)
4135: prlim[i][i]=probs[(int)age][i][ij];
4136: }else{ /* mobilav */
4137: for(i=1; i<=nlstate;i++)
4138: prlim[i][i]=mobaverage[(int)age][i][ij];
4139: }
4140: }
4141:
4142: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4143: for(h=0; h<=nhstepm; h++){
4144: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4145: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4146: }
4147: }
4148: /* This for computing probability of death (h=1 means
4149: computed over hstepm matrices product = hstepm*stepm months)
4150: as a weighted average of prlim.
4151: */
4152: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4153: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4154: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4155: }
4156: /* end probability of death */
4157:
4158: for(j=1; j<= nlstate; j++) /* vareij */
4159: for(h=0; h<=nhstepm; h++){
4160: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4161: }
4162:
4163: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4164: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4165: }
4166:
4167: } /* End theta */
4168:
4169: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4170:
4171: for(h=0; h<=nhstepm; h++) /* veij */
4172: for(j=1; j<=nlstate;j++)
4173: for(theta=1; theta <=npar; theta++)
4174: trgradg[h][j][theta]=gradg[h][theta][j];
4175:
4176: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4177: for(theta=1; theta <=npar; theta++)
4178: trgradgp[j][theta]=gradgp[theta][j];
4179:
4180:
4181: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4182: for(i=1;i<=nlstate;i++)
4183: for(j=1;j<=nlstate;j++)
4184: vareij[i][j][(int)age] =0.;
4185:
4186: for(h=0;h<=nhstepm;h++){
4187: for(k=0;k<=nhstepm;k++){
4188: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4189: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4190: for(i=1;i<=nlstate;i++)
4191: for(j=1;j<=nlstate;j++)
4192: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4193: }
4194: }
4195:
4196: /* pptj */
4197: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4198: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4199: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4200: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4201: varppt[j][i]=doldmp[j][i];
4202: /* end ppptj */
4203: /* x centered again */
4204: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4205: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
4206:
4207: if (popbased==1) {
4208: if(mobilav ==0){
4209: for(i=1; i<=nlstate;i++)
4210: prlim[i][i]=probs[(int)age][i][ij];
4211: }else{ /* mobilav */
4212: for(i=1; i<=nlstate;i++)
4213: prlim[i][i]=mobaverage[(int)age][i][ij];
4214: }
4215: }
4216:
4217: /* This for computing probability of death (h=1 means
4218: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4219: as a weighted average of prlim.
4220: */
4221: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4222: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4223: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4224: }
4225: /* end probability of death */
4226:
4227: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4228: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4229: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4230: for(i=1; i<=nlstate;i++){
4231: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4232: }
4233: }
4234: fprintf(ficresprobmorprev,"\n");
4235:
4236: fprintf(ficresvij,"%.0f ",age );
4237: for(i=1; i<=nlstate;i++)
4238: for(j=1; j<=nlstate;j++){
4239: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4240: }
4241: fprintf(ficresvij,"\n");
4242: free_matrix(gp,0,nhstepm,1,nlstate);
4243: free_matrix(gm,0,nhstepm,1,nlstate);
4244: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4245: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4246: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4247: } /* End age */
4248: free_vector(gpp,nlstate+1,nlstate+ndeath);
4249: free_vector(gmp,nlstate+1,nlstate+ndeath);
4250: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4251: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4252: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4253: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4254: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4255: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4256: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4257: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4258: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4259: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4260: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4261: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4262: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4263: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4264: fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4265: /* 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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
4266: */
4267: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4268: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4269:
4270: free_vector(xp,1,npar);
4271: free_matrix(doldm,1,nlstate,1,nlstate);
4272: free_matrix(dnewm,1,nlstate,1,npar);
4273: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4274: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4275: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4276: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4277: fclose(ficresprobmorprev);
4278: fflush(ficgp);
4279: fflush(fichtm);
4280: } /* end varevsij */
4281:
4282: /************ Variance of prevlim ******************/
4283: 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 *ncvyear, int ij, char strstart[])
4284: {
4285: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4286: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4287:
4288: double **dnewm,**doldm;
4289: int i, j, nhstepm, hstepm;
4290: double *xp;
4291: double *gp, *gm;
4292: double **gradg, **trgradg;
4293: double age,agelim;
4294: int theta;
4295:
4296: pstamp(ficresvpl);
4297: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4298: fprintf(ficresvpl,"# Age");
4299: for(i=1; i<=nlstate;i++)
4300: fprintf(ficresvpl," %1d-%1d",i,i);
4301: fprintf(ficresvpl,"\n");
4302:
4303: xp=vector(1,npar);
4304: dnewm=matrix(1,nlstate,1,npar);
4305: doldm=matrix(1,nlstate,1,nlstate);
4306:
4307: hstepm=1*YEARM; /* Every year of age */
4308: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4309: agelim = AGESUP;
4310: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4311: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4312: if (stepm >= YEARM) hstepm=1;
4313: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4314: gradg=matrix(1,npar,1,nlstate);
4315: gp=vector(1,nlstate);
4316: gm=vector(1,nlstate);
4317:
4318: for(theta=1; theta <=npar; theta++){
4319: for(i=1; i<=npar; i++){ /* Computes gradient */
4320: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4321: }
4322: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4323: for(i=1;i<=nlstate;i++)
4324: gp[i] = prlim[i][i];
4325:
4326: for(i=1; i<=npar; i++) /* Computes gradient */
4327: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4328: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4329: for(i=1;i<=nlstate;i++)
4330: gm[i] = prlim[i][i];
4331:
4332: for(i=1;i<=nlstate;i++)
4333: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4334: } /* End theta */
4335:
4336: trgradg =matrix(1,nlstate,1,npar);
4337:
4338: for(j=1; j<=nlstate;j++)
4339: for(theta=1; theta <=npar; theta++)
4340: trgradg[j][theta]=gradg[theta][j];
4341:
4342: for(i=1;i<=nlstate;i++)
4343: varpl[i][(int)age] =0.;
4344: if((int)age==67 ||(int)age== 66 ){
4345: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4346: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4347: }else{
4348: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4349: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4350: }
4351: for(i=1;i<=nlstate;i++)
4352: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4353:
4354: fprintf(ficresvpl,"%.0f ",age );
4355: for(i=1; i<=nlstate;i++)
4356: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4357: fprintf(ficresvpl,"\n");
4358: free_vector(gp,1,nlstate);
4359: free_vector(gm,1,nlstate);
4360: free_matrix(gradg,1,npar,1,nlstate);
4361: free_matrix(trgradg,1,nlstate,1,npar);
4362: } /* End age */
4363:
4364: free_vector(xp,1,npar);
4365: free_matrix(doldm,1,nlstate,1,npar);
4366: free_matrix(dnewm,1,nlstate,1,nlstate);
4367:
4368: }
4369:
4370: /************ Variance of one-step probabilities ******************/
4371: 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[])
4372: {
4373: int i, j=0, k1, l1, tj;
4374: int k2, l2, j1, z1;
4375: int k=0, l;
4376: int first=1, first1, first2;
4377: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4378: double **dnewm,**doldm;
4379: double *xp;
4380: double *gp, *gm;
4381: double **gradg, **trgradg;
4382: double **mu;
4383: double age, cov[NCOVMAX+1];
4384: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4385: int theta;
4386: char fileresprob[FILENAMELENGTH];
4387: char fileresprobcov[FILENAMELENGTH];
4388: char fileresprobcor[FILENAMELENGTH];
4389: double ***varpij;
4390:
4391: strcpy(fileresprob,"PROB_");
4392: strcat(fileresprob,fileres);
4393: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4394: printf("Problem with resultfile: %s\n", fileresprob);
4395: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4396: }
4397: strcpy(fileresprobcov,"PROBCOV_");
4398: strcat(fileresprobcov,fileresu);
4399: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4400: printf("Problem with resultfile: %s\n", fileresprobcov);
4401: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4402: }
4403: strcpy(fileresprobcor,"PROBCOR_");
4404: strcat(fileresprobcor,fileresu);
4405: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4406: printf("Problem with resultfile: %s\n", fileresprobcor);
4407: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4408: }
4409: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4410: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4411: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4412: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4413: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4414: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4415: pstamp(ficresprob);
4416: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4417: fprintf(ficresprob,"# Age");
4418: pstamp(ficresprobcov);
4419: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4420: fprintf(ficresprobcov,"# Age");
4421: pstamp(ficresprobcor);
4422: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4423: fprintf(ficresprobcor,"# Age");
4424:
4425:
4426: for(i=1; i<=nlstate;i++)
4427: for(j=1; j<=(nlstate+ndeath);j++){
4428: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4429: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4430: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4431: }
4432: /* fprintf(ficresprob,"\n");
4433: fprintf(ficresprobcov,"\n");
4434: fprintf(ficresprobcor,"\n");
4435: */
4436: xp=vector(1,npar);
4437: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4438: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4439: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4440: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4441: first=1;
4442: fprintf(ficgp,"\n# Routine varprob");
4443: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4444: fprintf(fichtm,"\n");
4445:
4446: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
4447: fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
4448: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4449: and drawn. It helps understanding how is the covariance between two incidences.\
4450: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4451: 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. \
4452: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4453: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4454: standard deviations wide on each axis. <br>\
4455: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4456: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4457: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4458:
4459: cov[1]=1;
4460: /* tj=cptcoveff; */
4461: tj = (int) pow(2,cptcoveff);
4462: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4463: j1=0;
4464: for(j1=1; j1<=tj;j1++){
4465: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4466: /*j1++;*/
4467: if (cptcovn>0) {
4468: fprintf(ficresprob, "\n#********** Variable ");
4469: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4470: fprintf(ficresprob, "**********\n#\n");
4471: fprintf(ficresprobcov, "\n#********** Variable ");
4472: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4473: fprintf(ficresprobcov, "**********\n#\n");
4474:
4475: fprintf(ficgp, "\n#********** Variable ");
4476: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4477: fprintf(ficgp, "**********\n#\n");
4478:
4479:
4480: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4481: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4482: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4483:
4484: fprintf(ficresprobcor, "\n#********** Variable ");
4485: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4486: fprintf(ficresprobcor, "**********\n#");
4487: }
4488:
4489: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4490: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4491: gp=vector(1,(nlstate)*(nlstate+ndeath));
4492: gm=vector(1,(nlstate)*(nlstate+ndeath));
4493: for (age=bage; age<=fage; age ++){
4494: cov[2]=age;
4495: if(nagesqr==1)
4496: cov[3]= age*age;
4497: for (k=1; k<=cptcovn;k++) {
4498: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4499: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4500: * 1 1 1 1 1
4501: * 2 2 1 1 1
4502: * 3 1 2 1 1
4503: */
4504: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4505: }
4506: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4507: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4508: for (k=1; k<=cptcovprod;k++)
4509: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4510:
4511:
4512: for(theta=1; theta <=npar; theta++){
4513: for(i=1; i<=npar; i++)
4514: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4515:
4516: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4517:
4518: k=0;
4519: for(i=1; i<= (nlstate); i++){
4520: for(j=1; j<=(nlstate+ndeath);j++){
4521: k=k+1;
4522: gp[k]=pmmij[i][j];
4523: }
4524: }
4525:
4526: for(i=1; i<=npar; i++)
4527: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4528:
4529: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4530: k=0;
4531: for(i=1; i<=(nlstate); i++){
4532: for(j=1; j<=(nlstate+ndeath);j++){
4533: k=k+1;
4534: gm[k]=pmmij[i][j];
4535: }
4536: }
4537:
4538: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4539: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4540: }
4541:
4542: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4543: for(theta=1; theta <=npar; theta++)
4544: trgradg[j][theta]=gradg[theta][j];
4545:
4546: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4547: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4548:
4549: pmij(pmmij,cov,ncovmodel,x,nlstate);
4550:
4551: k=0;
4552: for(i=1; i<=(nlstate); i++){
4553: for(j=1; j<=(nlstate+ndeath);j++){
4554: k=k+1;
4555: mu[k][(int) age]=pmmij[i][j];
4556: }
4557: }
4558: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4559: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4560: varpij[i][j][(int)age] = doldm[i][j];
4561:
4562: /*printf("\n%d ",(int)age);
4563: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4564: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4565: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4566: }*/
4567:
4568: fprintf(ficresprob,"\n%d ",(int)age);
4569: fprintf(ficresprobcov,"\n%d ",(int)age);
4570: fprintf(ficresprobcor,"\n%d ",(int)age);
4571:
4572: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4573: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4574: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4575: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4576: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4577: }
4578: i=0;
4579: for (k=1; k<=(nlstate);k++){
4580: for (l=1; l<=(nlstate+ndeath);l++){
4581: i++;
4582: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4583: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4584: for (j=1; j<=i;j++){
4585: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4586: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4587: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4588: }
4589: }
4590: }/* end of loop for state */
4591: } /* end of loop for age */
4592: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4593: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4594: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4595: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4596:
4597: /* Confidence intervalle of pij */
4598: /*
4599: fprintf(ficgp,"\nunset parametric;unset label");
4600: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4601: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4602: 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);
4603: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4604: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4605: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4606: */
4607:
4608: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4609: first1=1;first2=2;
4610: for (k2=1; k2<=(nlstate);k2++){
4611: for (l2=1; l2<=(nlstate+ndeath);l2++){
4612: if(l2==k2) continue;
4613: j=(k2-1)*(nlstate+ndeath)+l2;
4614: for (k1=1; k1<=(nlstate);k1++){
4615: for (l1=1; l1<=(nlstate+ndeath);l1++){
4616: if(l1==k1) continue;
4617: i=(k1-1)*(nlstate+ndeath)+l1;
4618: if(i<=j) continue;
4619: for (age=bage; age<=fage; age ++){
4620: if ((int)age %5==0){
4621: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4622: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4623: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4624: mu1=mu[i][(int) age]/stepm*YEARM ;
4625: mu2=mu[j][(int) age]/stepm*YEARM;
4626: c12=cv12/sqrt(v1*v2);
4627: /* Computing eigen value of matrix of covariance */
4628: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4629: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4630: if ((lc2 <0) || (lc1 <0) ){
4631: if(first2==1){
4632: first1=0;
4633: 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);
4634: }
4635: 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);
4636: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4637: /* lc2=fabs(lc2); */
4638: }
4639:
4640: /* Eigen vectors */
4641: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4642: /*v21=sqrt(1.-v11*v11); *//* error */
4643: v21=(lc1-v1)/cv12*v11;
4644: v12=-v21;
4645: v22=v11;
4646: tnalp=v21/v11;
4647: if(first1==1){
4648: first1=0;
4649: 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);
4650: }
4651: 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);
4652: /*printf(fignu*/
4653: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4654: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4655: if(first==1){
4656: first=0;
4657: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4658: fprintf(ficgp,"\nset parametric;unset label");
4659: 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);
4660: fprintf(ficgp,"\nset ter svg size 640, 480");
4661: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4662: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4663: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4664: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4665: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4666: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4667: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4668: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4669: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4670: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4671: 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",\
4672: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4673: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4674: }else{
4675: first=0;
4676: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4677: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4678: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4679: 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",\
4680: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4681: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4682: }/* if first */
4683: } /* age mod 5 */
4684: } /* end loop age */
4685: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4686: first=1;
4687: } /*l12 */
4688: } /* k12 */
4689: } /*l1 */
4690: }/* k1 */
4691: /* } */ /* loop covariates */
4692: }
4693: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4694: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4695: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4696: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4697: free_vector(xp,1,npar);
4698: fclose(ficresprob);
4699: fclose(ficresprobcov);
4700: fclose(ficresprobcor);
4701: fflush(ficgp);
4702: fflush(fichtmcov);
4703: }
4704:
4705:
4706: /******************* Printing html file ***********/
4707: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4708: int lastpass, int stepm, int weightopt, char model[],\
4709: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4710: int popforecast, int estepm ,\
4711: double jprev1, double mprev1,double anprev1, \
4712: double jprev2, double mprev2,double anprev2){
4713: int jj1, k1, i1, cpt;
4714:
4715: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4716: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4717: </ul>");
4718: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4719: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4720: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
4721: fprintf(fichtm,"\
4722: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4723: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
4724: fprintf(fichtm,"\
4725: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4726: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
4727: fprintf(fichtm,"\
4728: - (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): \
4729: <a href=\"%s\">%s</a> <br>\n",
4730: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
4731: fprintf(fichtm,"\
4732: - Population projections by age and states: \
4733: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
4734:
4735: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4736:
4737: m=pow(2,cptcoveff);
4738: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4739:
4740: jj1=0;
4741: for(k1=1; k1<=m;k1++){
4742: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4743: jj1++;
4744: if (cptcovn > 0) {
4745: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4746: for (cpt=1; cpt<=cptcoveff;cpt++){
4747: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4748: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
4749: }
4750: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4751: }
4752: /* aij, bij */
4753: fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
4754: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4755: /* Pij */
4756: fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
4757: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4758: /* Quasi-incidences */
4759: fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4760: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
4761: incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
4762: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
4763: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4764: /* Survival functions (period) in state j */
4765: for(cpt=1; cpt<=nlstate;cpt++){
4766: fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
4767: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4768: }
4769: /* State specific survival functions (period) */
4770: for(cpt=1; cpt<=nlstate;cpt++){
4771: fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
4772: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4773: <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
4774: }
4775: /* Period (stable) prevalence in each health state */
4776: for(cpt=1; cpt<=nlstate;cpt++){
4777: fprintf(fichtm,"<br>\n- 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.svg\">%s%d_%d.svg</a><br> \
4778: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4779: }
4780: for(cpt=1; cpt<=nlstate;cpt++) {
4781: 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) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
4782: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
4783: }
4784: /* } /\* end i1 *\/ */
4785: }/* End k1 */
4786: fprintf(fichtm,"</ul>");
4787:
4788: fprintf(fichtm,"\
4789: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4790: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
4791: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
4792: But because parameters are usually highly correlated (a higher incidence of disability \
4793: and a higher incidence of recovery can give very close observed transition) it might \
4794: be very useful to look not only at linear confidence intervals estimated from the \
4795: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4796: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4797: covariance matrix of the one-step probabilities. \
4798: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
4799:
4800: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4801: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
4802: fprintf(fichtm,"\
4803: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4804: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
4805:
4806: fprintf(fichtm,"\
4807: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4808: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
4809: fprintf(fichtm,"\
4810: - 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): \
4811: <a href=\"%s\">%s</a> <br>\n</li>",
4812: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
4813: fprintf(fichtm,"\
4814: - (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): \
4815: <a href=\"%s\">%s</a> <br>\n</li>",
4816: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
4817: fprintf(fichtm,"\
4818: - 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",
4819: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
4820: fprintf(fichtm,"\
4821: - 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",
4822: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
4823: fprintf(fichtm,"\
4824: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4825: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
4826:
4827: /* if(popforecast==1) fprintf(fichtm,"\n */
4828: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4829: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4830: /* <br>",fileres,fileres,fileres,fileres); */
4831: /* else */
4832: /* 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); */
4833: fflush(fichtm);
4834: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4835:
4836: m=pow(2,cptcoveff);
4837: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4838:
4839: jj1=0;
4840: for(k1=1; k1<=m;k1++){
4841: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4842: jj1++;
4843: if (cptcovn > 0) {
4844: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4845: for (cpt=1; cpt<=cptcoveff;cpt++)
4846: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4847: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4848: }
4849: for(cpt=1; cpt<=nlstate;cpt++) {
4850: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4851: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
4852: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
4853: }
4854: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4855: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4856: true period expectancies (those weighted with period prevalences are also\
4857: drawn in addition to the population based expectancies computed using\
4858: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
4859: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
4860: /* } /\* end i1 *\/ */
4861: }/* End k1 */
4862: fprintf(fichtm,"</ul>");
4863: fflush(fichtm);
4864: }
4865:
4866: /******************* Gnuplot file **************/
4867: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4868:
4869: char dirfileres[132],optfileres[132];
4870: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4871: int ng=0;
4872: int vpopbased;
4873: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4874: /* printf("Problem with file %s",optionfilegnuplot); */
4875: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4876: /* } */
4877:
4878: /*#ifdef windows */
4879: fprintf(ficgp,"cd \"%s\" \n",pathc);
4880: /*#endif */
4881: m=pow(2,cptcoveff);
4882:
4883: /* Contribution to likelihood */
4884: /* Plot the probability implied in the likelihood */
4885: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
4886: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
4887: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
4888: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
4889: /* nice for mle=4 plot by number of matrix products.
4890: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
4891: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
4892: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
4893: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
4894: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
4895: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
4896: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
4897: for (i=1; i<= nlstate ; i ++) {
4898: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
4899: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
4900: fprintf(ficgp," u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
4901: for (j=2; j<= nlstate+ndeath ; j ++) {
4902: fprintf(ficgp,",\\\n \"\" u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
4903: }
4904: fprintf(ficgp,";\nset out; unset ylabel;\n");
4905: }
4906: /* unset log; plot "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */
4907: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
4908: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
4909: fprintf(ficgp,"\nset out;unset log\n");
4910: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
4911:
4912: strcpy(dirfileres,optionfilefiname);
4913: strcpy(optfileres,"vpl");
4914: /* 1eme*/
4915: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
4916: for (cpt=1; cpt<= nlstate ; cpt ++) {
4917: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4918: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
4919: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
4920: fprintf(ficgp,"set xlabel \"Age\" \n\
4921: set ylabel \"Probability\" \n\
4922: set ter svg size 640, 480\n\
4923: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
4924:
4925: for (i=1; i<= nlstate ; i ++) {
4926: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4927: else fprintf(ficgp," %%*lf (%%*lf)");
4928: }
4929: fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
4930: for (i=1; i<= nlstate ; i ++) {
4931: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4932: else fprintf(ficgp," %%*lf (%%*lf)");
4933: }
4934: fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
4935: for (i=1; i<= nlstate ; i ++) {
4936: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4937: else fprintf(ficgp," %%*lf (%%*lf)");
4938: }
4939: fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
4940: fprintf(ficgp,"\nset out \n");
4941: } /* k1 */
4942: } /* cpt */
4943: /*2 eme*/
4944: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4945: for (k1=1; k1<= m ; k1 ++) {
4946: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
4947: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
4948: if(vpopbased==0)
4949: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
4950: else
4951: fprintf(ficgp,"\nreplot ");
4952: for (i=1; i<= nlstate+1 ; i ++) {
4953: k=2*i;
4954: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
4955: for (j=1; j<= nlstate+1 ; j ++) {
4956: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4957: else fprintf(ficgp," %%*lf (%%*lf)");
4958: }
4959: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
4960: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
4961: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
4962: for (j=1; j<= nlstate+1 ; j ++) {
4963: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4964: else fprintf(ficgp," %%*lf (%%*lf)");
4965: }
4966: fprintf(ficgp,"\" t\"\" w l lt 0,");
4967: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
4968: for (j=1; j<= nlstate+1 ; j ++) {
4969: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4970: else fprintf(ficgp," %%*lf (%%*lf)");
4971: }
4972: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4973: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
4974: } /* state */
4975: } /* vpopbased */
4976: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
4977: } /* k1 */
4978: /*3eme*/
4979:
4980: for (k1=1; k1<= m ; k1 ++) {
4981: for (cpt=1; cpt<= nlstate ; cpt ++) {
4982: /* k=2+nlstate*(2*cpt-2); */
4983: k=2+(nlstate+1)*(cpt-1);
4984: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
4985: fprintf(ficgp,"set ter svg size 640, 480\n\
4986: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
4987: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4988: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4989: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4990: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4991: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4992: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4993:
4994: */
4995: for (i=1; i< nlstate ; i ++) {
4996: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
4997: /* 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);*/
4998:
4999: }
5000: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5001: }
5002: }
5003:
5004: /* Survival functions (period) from state i in state j by initial state i */
5005: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5006: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5007: k=3;
5008: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
5009: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5010: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5011: set ter svg size 640, 480\n\
5012: unset log y\n\
5013: plot [%.f:%.f] ", ageminpar, agemaxpar);
5014: for (i=1; i<= nlstate ; i ++){
5015: if(i==1)
5016: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5017: else
5018: fprintf(ficgp,", '' ");
5019: l=(nlstate+ndeath)*(i-1)+1;
5020: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5021: for (j=2; j<= nlstate+ndeath ; j ++)
5022: fprintf(ficgp,"+$%d",k+l+j-1);
5023: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5024: } /* nlstate */
5025: fprintf(ficgp,"\nset out\n");
5026: } /* end cpt state*/
5027: } /* end covariate */
5028:
5029: /* Survival functions (period) from state i in state j by final state j */
5030: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5031: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5032: k=3;
5033: fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
5034: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5035: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5036: set ter svg size 640, 480\n\
5037: unset log y\n\
5038: plot [%.f:%.f] ", ageminpar, agemaxpar);
5039: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5040: if(j==1)
5041: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5042: else
5043: fprintf(ficgp,", '' ");
5044: l=(nlstate+ndeath)*(cpt-1) +j;
5045: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5046: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5047: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5048: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5049: } /* nlstate */
5050: fprintf(ficgp,", '' ");
5051: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5052: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5053: l=(nlstate+ndeath)*(cpt-1) +j;
5054: if(j < nlstate)
5055: fprintf(ficgp,"$%d +",k+l);
5056: else
5057: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5058: }
5059: fprintf(ficgp,"\nset out\n");
5060: } /* end cpt state*/
5061: } /* end covariate */
5062:
5063: /* CV preval stable (period) for each covariate */
5064: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5065: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5066: k=3;
5067: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
5068: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5069: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5070: set ter svg size 640, 480\n\
5071: unset log y\n\
5072: plot [%.f:%.f] ", ageminpar, agemaxpar);
5073: for (i=1; i<= nlstate ; i ++){
5074: if(i==1)
5075: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5076: else
5077: fprintf(ficgp,", '' ");
5078: l=(nlstate+ndeath)*(i-1)+1;
5079: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5080: for (j=2; j<= nlstate ; j ++)
5081: fprintf(ficgp,"+$%d",k+l+j-1);
5082: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5083: } /* nlstate */
5084: fprintf(ficgp,"\nset out\n");
5085: } /* end cpt state*/
5086: } /* end covariate */
5087:
5088: /* proba elementaires */
5089: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5090: for(i=1,jk=1; i <=nlstate; i++){
5091: fprintf(ficgp,"# initial state %d\n",i);
5092: for(k=1; k <=(nlstate+ndeath); k++){
5093: if (k != i) {
5094: fprintf(ficgp,"# current state %d\n",k);
5095: for(j=1; j <=ncovmodel; j++){
5096: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5097: jk++;
5098: }
5099: fprintf(ficgp,"\n");
5100: }
5101: }
5102: }
5103: fprintf(ficgp,"##############\n#\n");
5104:
5105: /*goto avoid;*/
5106: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5107: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5108: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5109: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5110: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5111: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5112: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5113: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5114: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5115: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5116: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5117: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5118: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5119: fprintf(ficgp,"#\n");
5120: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5121: fprintf(ficgp,"# ng=%d\n",ng);
5122: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5123: for(jk=1; jk <=m; jk++) {
5124: fprintf(ficgp,"# jk=%d\n",jk);
5125: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5126: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5127: if (ng==1){
5128: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5129: fprintf(ficgp,"\nunset log y");
5130: }else if (ng==2){
5131: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5132: fprintf(ficgp,"\nset log y");
5133: }else if (ng==3){
5134: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5135: fprintf(ficgp,"\nset log y");
5136: }else
5137: fprintf(ficgp,"\nunset title ");
5138: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5139: i=1;
5140: for(k2=1; k2<=nlstate; k2++) {
5141: k3=i;
5142: for(k=1; k<=(nlstate+ndeath); k++) {
5143: if (k != k2){
5144: switch( ng) {
5145: case 1:
5146: if(nagesqr==0)
5147: fprintf(ficgp," p%d+p%d*x",i,i+1);
5148: else /* nagesqr =1 */
5149: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5150: break;
5151: case 2: /* ng=2 */
5152: if(nagesqr==0)
5153: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5154: else /* nagesqr =1 */
5155: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5156: break;
5157: case 3:
5158: if(nagesqr==0)
5159: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5160: else /* nagesqr =1 */
5161: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5162: break;
5163: }
5164: ij=1;/* To be checked else nbcode[0][0] wrong */
5165: for(j=3; j <=ncovmodel-nagesqr; j++) {
5166: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5167: if(ij <=cptcovage) { /* Bug valgrind */
5168: if((j-2)==Tage[ij]) { /* Bug valgrind */
5169: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5170: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5171: ij++;
5172: }
5173: }
5174: else
5175: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5176: }
5177: if(ng != 1){
5178: fprintf(ficgp,")/(1");
5179:
5180: for(k1=1; k1 <=nlstate; k1++){
5181: if(nagesqr==0)
5182: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5183: else /* nagesqr =1 */
5184: fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
5185:
5186: ij=1;
5187: for(j=3; j <=ncovmodel-nagesqr; j++){
5188: if(ij <=cptcovage) { /* Bug valgrind */
5189: if((j-2)==Tage[ij]) { /* Bug valgrind */
5190: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5191: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5192: ij++;
5193: }
5194: }
5195: else
5196: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5197: }
5198: fprintf(ficgp,")");
5199: }
5200: fprintf(ficgp,")");
5201: if(ng ==2)
5202: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5203: else /* ng= 3 */
5204: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5205: }else{ /* end ng <> 1 */
5206: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5207: }
5208: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5209: i=i+ncovmodel;
5210: }
5211: } /* end k */
5212: } /* end k2 */
5213: fprintf(ficgp,"\n set out\n");
5214: } /* end jk */
5215: } /* end ng */
5216: /* avoid: */
5217: fflush(ficgp);
5218: } /* end gnuplot */
5219:
5220:
5221: /*************** Moving average **************/
5222: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5223:
5224: int i, cpt, cptcod;
5225: int modcovmax =1;
5226: int mobilavrange, mob;
5227: double age;
5228:
5229: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5230: a covariate has 2 modalities */
5231: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5232:
5233: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5234: if(mobilav==1) mobilavrange=5; /* default */
5235: else mobilavrange=mobilav;
5236: for (age=bage; age<=fage; age++)
5237: for (i=1; i<=nlstate;i++)
5238: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5239: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5240: /* We keep the original values on the extreme ages bage, fage and for
5241: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5242: we use a 5 terms etc. until the borders are no more concerned.
5243: */
5244: for (mob=3;mob <=mobilavrange;mob=mob+2){
5245: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5246: for (i=1; i<=nlstate;i++){
5247: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5248: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5249: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5250: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5251: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5252: }
5253: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5254: }
5255: }
5256: }/* end age */
5257: }/* end mob */
5258: }else return -1;
5259: return 0;
5260: }/* End movingaverage */
5261:
5262:
5263: /************** Forecasting ******************/
5264: 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){
5265: /* proj1, year, month, day of starting projection
5266: agemin, agemax range of age
5267: dateprev1 dateprev2 range of dates during which prevalence is computed
5268: anproj2 year of en of projection (same day and month as proj1).
5269: */
5270: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5271: double agec; /* generic age */
5272: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5273: double *popeffectif,*popcount;
5274: double ***p3mat;
5275: double ***mobaverage;
5276: char fileresf[FILENAMELENGTH];
5277:
5278: agelim=AGESUP;
5279: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5280:
5281: strcpy(fileresf,"F_");
5282: strcat(fileresf,fileresu);
5283: if((ficresf=fopen(fileresf,"w"))==NULL) {
5284: printf("Problem with forecast resultfile: %s\n", fileresf);
5285: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5286: }
5287: printf("Computing forecasting: result on file '%s' \n", fileresf);
5288: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5289:
5290: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5291:
5292: if (mobilav!=0) {
5293: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5294: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5295: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5296: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5297: }
5298: }
5299:
5300: stepsize=(int) (stepm+YEARM-1)/YEARM;
5301: if (stepm<=12) stepsize=1;
5302: if(estepm < stepm){
5303: printf ("Problem %d lower than %d\n",estepm, stepm);
5304: }
5305: else hstepm=estepm;
5306:
5307: hstepm=hstepm/stepm;
5308: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5309: fractional in yp1 */
5310: anprojmean=yp;
5311: yp2=modf((yp1*12),&yp);
5312: mprojmean=yp;
5313: yp1=modf((yp2*30.5),&yp);
5314: jprojmean=yp;
5315: if(jprojmean==0) jprojmean=1;
5316: if(mprojmean==0) jprojmean=1;
5317:
5318: i1=cptcoveff;
5319: if (cptcovn < 1){i1=1;}
5320:
5321: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5322:
5323: fprintf(ficresf,"#****** Routine prevforecast **\n");
5324:
5325: /* if (h==(int)(YEARM*yearp)){ */
5326: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5327: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5328: k=k+1;
5329: fprintf(ficresf,"\n#******");
5330: for(j=1;j<=cptcoveff;j++) {
5331: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5332: }
5333: fprintf(ficresf,"******\n");
5334: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
5335: for(j=1; j<=nlstate+ndeath;j++){
5336: for(i=1; i<=nlstate;i++)
5337: fprintf(ficresf," p%d%d",i,j);
5338: fprintf(ficresf," p.%d",j);
5339: }
5340: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5341: fprintf(ficresf,"\n");
5342: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5343:
5344: for (agec=fage; agec>=(ageminpar-1); agec--){
5345: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5346: nhstepm = nhstepm/hstepm;
5347: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5348: oldm=oldms;savm=savms;
5349: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5350:
5351: for (h=0; h<=nhstepm; h++){
5352: if (h*hstepm/YEARM*stepm ==yearp) {
5353: fprintf(ficresf,"\n");
5354: for(j=1;j<=cptcoveff;j++)
5355: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5356: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5357: }
5358: for(j=1; j<=nlstate+ndeath;j++) {
5359: ppij=0.;
5360: for(i=1; i<=nlstate;i++) {
5361: if (mobilav==1)
5362: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5363: else {
5364: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5365: }
5366: if (h*hstepm/YEARM*stepm== yearp) {
5367: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5368: }
5369: } /* end i */
5370: if (h*hstepm/YEARM*stepm==yearp) {
5371: fprintf(ficresf," %.3f", ppij);
5372: }
5373: }/* end j */
5374: } /* end h */
5375: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5376: } /* end agec */
5377: } /* end yearp */
5378: } /* end cptcod */
5379: } /* end cptcov */
5380:
5381: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5382:
5383: fclose(ficresf);
5384: }
5385:
5386: /************** Forecasting *****not tested NB*************/
5387: 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){
5388:
5389: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5390: int *popage;
5391: double calagedatem, agelim, kk1, kk2;
5392: double *popeffectif,*popcount;
5393: double ***p3mat,***tabpop,***tabpopprev;
5394: double ***mobaverage;
5395: char filerespop[FILENAMELENGTH];
5396:
5397: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5398: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5399: agelim=AGESUP;
5400: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5401:
5402: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5403:
5404:
5405: strcpy(filerespop,"POP_");
5406: strcat(filerespop,fileresu);
5407: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5408: printf("Problem with forecast resultfile: %s\n", filerespop);
5409: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5410: }
5411: printf("Computing forecasting: result on file '%s' \n", filerespop);
5412: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5413:
5414: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5415:
5416: if (mobilav!=0) {
5417: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5418: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5419: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5420: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5421: }
5422: }
5423:
5424: stepsize=(int) (stepm+YEARM-1)/YEARM;
5425: if (stepm<=12) stepsize=1;
5426:
5427: agelim=AGESUP;
5428:
5429: hstepm=1;
5430: hstepm=hstepm/stepm;
5431:
5432: if (popforecast==1) {
5433: if((ficpop=fopen(popfile,"r"))==NULL) {
5434: printf("Problem with population file : %s\n",popfile);exit(0);
5435: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5436: }
5437: popage=ivector(0,AGESUP);
5438: popeffectif=vector(0,AGESUP);
5439: popcount=vector(0,AGESUP);
5440:
5441: i=1;
5442: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5443:
5444: imx=i;
5445: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5446: }
5447:
5448: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5449: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5450: k=k+1;
5451: fprintf(ficrespop,"\n#******");
5452: for(j=1;j<=cptcoveff;j++) {
5453: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5454: }
5455: fprintf(ficrespop,"******\n");
5456: fprintf(ficrespop,"# Age");
5457: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5458: if (popforecast==1) fprintf(ficrespop," [Population]");
5459:
5460: for (cpt=0; cpt<=0;cpt++) {
5461: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5462:
5463: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5464: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5465: nhstepm = nhstepm/hstepm;
5466:
5467: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5468: oldm=oldms;savm=savms;
5469: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5470:
5471: for (h=0; h<=nhstepm; h++){
5472: if (h==(int) (calagedatem+YEARM*cpt)) {
5473: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5474: }
5475: for(j=1; j<=nlstate+ndeath;j++) {
5476: kk1=0.;kk2=0;
5477: for(i=1; i<=nlstate;i++) {
5478: if (mobilav==1)
5479: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5480: else {
5481: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5482: }
5483: }
5484: if (h==(int)(calagedatem+12*cpt)){
5485: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5486: /*fprintf(ficrespop," %.3f", kk1);
5487: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5488: }
5489: }
5490: for(i=1; i<=nlstate;i++){
5491: kk1=0.;
5492: for(j=1; j<=nlstate;j++){
5493: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5494: }
5495: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5496: }
5497:
5498: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5499: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5500: }
5501: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5502: }
5503: }
5504:
5505: /******/
5506:
5507: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5508: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5509: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5510: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5511: nhstepm = nhstepm/hstepm;
5512:
5513: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5514: oldm=oldms;savm=savms;
5515: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5516: for (h=0; h<=nhstepm; h++){
5517: if (h==(int) (calagedatem+YEARM*cpt)) {
5518: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5519: }
5520: for(j=1; j<=nlstate+ndeath;j++) {
5521: kk1=0.;kk2=0;
5522: for(i=1; i<=nlstate;i++) {
5523: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5524: }
5525: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5526: }
5527: }
5528: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5529: }
5530: }
5531: }
5532: }
5533:
5534: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5535:
5536: if (popforecast==1) {
5537: free_ivector(popage,0,AGESUP);
5538: free_vector(popeffectif,0,AGESUP);
5539: free_vector(popcount,0,AGESUP);
5540: }
5541: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5542: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5543: fclose(ficrespop);
5544: } /* End of popforecast */
5545:
5546: int fileappend(FILE *fichier, char *optionfich)
5547: {
5548: if((fichier=fopen(optionfich,"a"))==NULL) {
5549: printf("Problem with file: %s\n", optionfich);
5550: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5551: return (0);
5552: }
5553: fflush(fichier);
5554: return (1);
5555: }
5556:
5557:
5558: /**************** function prwizard **********************/
5559: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5560: {
5561:
5562: /* Wizard to print covariance matrix template */
5563:
5564: char ca[32], cb[32];
5565: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5566: int numlinepar;
5567:
5568: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5569: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5570: for(i=1; i <=nlstate; i++){
5571: jj=0;
5572: for(j=1; j <=nlstate+ndeath; j++){
5573: if(j==i) continue;
5574: jj++;
5575: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5576: printf("%1d%1d",i,j);
5577: fprintf(ficparo,"%1d%1d",i,j);
5578: for(k=1; k<=ncovmodel;k++){
5579: /* printf(" %lf",param[i][j][k]); */
5580: /* fprintf(ficparo," %lf",param[i][j][k]); */
5581: printf(" 0.");
5582: fprintf(ficparo," 0.");
5583: }
5584: printf("\n");
5585: fprintf(ficparo,"\n");
5586: }
5587: }
5588: printf("# Scales (for hessian or gradient estimation)\n");
5589: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5590: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5591: for(i=1; i <=nlstate; i++){
5592: jj=0;
5593: for(j=1; j <=nlstate+ndeath; j++){
5594: if(j==i) continue;
5595: jj++;
5596: fprintf(ficparo,"%1d%1d",i,j);
5597: printf("%1d%1d",i,j);
5598: fflush(stdout);
5599: for(k=1; k<=ncovmodel;k++){
5600: /* printf(" %le",delti3[i][j][k]); */
5601: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5602: printf(" 0.");
5603: fprintf(ficparo," 0.");
5604: }
5605: numlinepar++;
5606: printf("\n");
5607: fprintf(ficparo,"\n");
5608: }
5609: }
5610: printf("# Covariance matrix\n");
5611: /* # 121 Var(a12)\n\ */
5612: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5613: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5614: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5615: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5616: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5617: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5618: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5619: fflush(stdout);
5620: fprintf(ficparo,"# Covariance matrix\n");
5621: /* # 121 Var(a12)\n\ */
5622: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5623: /* # ...\n\ */
5624: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5625:
5626: for(itimes=1;itimes<=2;itimes++){
5627: jj=0;
5628: for(i=1; i <=nlstate; i++){
5629: for(j=1; j <=nlstate+ndeath; j++){
5630: if(j==i) continue;
5631: for(k=1; k<=ncovmodel;k++){
5632: jj++;
5633: ca[0]= k+'a'-1;ca[1]='\0';
5634: if(itimes==1){
5635: printf("#%1d%1d%d",i,j,k);
5636: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5637: }else{
5638: printf("%1d%1d%d",i,j,k);
5639: fprintf(ficparo,"%1d%1d%d",i,j,k);
5640: /* printf(" %.5le",matcov[i][j]); */
5641: }
5642: ll=0;
5643: for(li=1;li <=nlstate; li++){
5644: for(lj=1;lj <=nlstate+ndeath; lj++){
5645: if(lj==li) continue;
5646: for(lk=1;lk<=ncovmodel;lk++){
5647: ll++;
5648: if(ll<=jj){
5649: cb[0]= lk +'a'-1;cb[1]='\0';
5650: if(ll<jj){
5651: if(itimes==1){
5652: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5653: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5654: }else{
5655: printf(" 0.");
5656: fprintf(ficparo," 0.");
5657: }
5658: }else{
5659: if(itimes==1){
5660: printf(" Var(%s%1d%1d)",ca,i,j);
5661: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5662: }else{
5663: printf(" 0.");
5664: fprintf(ficparo," 0.");
5665: }
5666: }
5667: }
5668: } /* end lk */
5669: } /* end lj */
5670: } /* end li */
5671: printf("\n");
5672: fprintf(ficparo,"\n");
5673: numlinepar++;
5674: } /* end k*/
5675: } /*end j */
5676: } /* end i */
5677: } /* end itimes */
5678:
5679: } /* end of prwizard */
5680: /******************* Gompertz Likelihood ******************************/
5681: double gompertz(double x[])
5682: {
5683: double A,B,L=0.0,sump=0.,num=0.;
5684: int i,n=0; /* n is the size of the sample */
5685:
5686: for (i=0;i<=imx-1 ; i++) {
5687: sump=sump+weight[i];
5688: /* sump=sump+1;*/
5689: num=num+1;
5690: }
5691:
5692:
5693: /* for (i=0; i<=imx; i++)
5694: 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]);*/
5695:
5696: for (i=1;i<=imx ; i++)
5697: {
5698: if (cens[i] == 1 && wav[i]>1)
5699: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5700:
5701: if (cens[i] == 0 && wav[i]>1)
5702: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5703: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5704:
5705: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5706: if (wav[i] > 1 ) { /* ??? */
5707: L=L+A*weight[i];
5708: /* 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]);*/
5709: }
5710: }
5711:
5712: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5713:
5714: return -2*L*num/sump;
5715: }
5716:
5717: #ifdef GSL
5718: /******************* Gompertz_f Likelihood ******************************/
5719: double gompertz_f(const gsl_vector *v, void *params)
5720: {
5721: double A,B,LL=0.0,sump=0.,num=0.;
5722: double *x= (double *) v->data;
5723: int i,n=0; /* n is the size of the sample */
5724:
5725: for (i=0;i<=imx-1 ; i++) {
5726: sump=sump+weight[i];
5727: /* sump=sump+1;*/
5728: num=num+1;
5729: }
5730:
5731:
5732: /* for (i=0; i<=imx; i++)
5733: 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]);*/
5734: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5735: for (i=1;i<=imx ; i++)
5736: {
5737: if (cens[i] == 1 && wav[i]>1)
5738: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5739:
5740: if (cens[i] == 0 && wav[i]>1)
5741: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5742: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5743:
5744: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5745: if (wav[i] > 1 ) { /* ??? */
5746: LL=LL+A*weight[i];
5747: /* 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]);*/
5748: }
5749: }
5750:
5751: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5752: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5753:
5754: return -2*LL*num/sump;
5755: }
5756: #endif
5757:
5758: /******************* Printing html file ***********/
5759: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
5760: int lastpass, int stepm, int weightopt, char model[],\
5761: int imx, double p[],double **matcov,double agemortsup){
5762: int i,k;
5763:
5764: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5765: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5766: for (i=1;i<=2;i++)
5767: 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]));
5768: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
5769: fprintf(fichtm,"</ul>");
5770:
5771: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5772:
5773: 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>");
5774:
5775: for (k=agegomp;k<(agemortsup-2);k++)
5776: 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]);
5777:
5778:
5779: fflush(fichtm);
5780: }
5781:
5782: /******************* Gnuplot file **************/
5783: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5784:
5785: char dirfileres[132],optfileres[132];
5786:
5787: int ng;
5788:
5789:
5790: /*#ifdef windows */
5791: fprintf(ficgp,"cd \"%s\" \n",pathc);
5792: /*#endif */
5793:
5794:
5795: strcpy(dirfileres,optionfilefiname);
5796: strcpy(optfileres,"vpl");
5797: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
5798: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5799: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
5800: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5801: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5802:
5803: }
5804:
5805: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5806: {
5807:
5808: /*-------- data file ----------*/
5809: FILE *fic;
5810: char dummy[]=" ";
5811: int i=0, j=0, n=0;
5812: int linei, month, year,iout;
5813: char line[MAXLINE], linetmp[MAXLINE];
5814: char stra[MAXLINE], strb[MAXLINE];
5815: char *stratrunc;
5816: int lstra;
5817:
5818:
5819: if((fic=fopen(datafile,"r"))==NULL) {
5820: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5821: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
5822: }
5823:
5824: i=1;
5825: linei=0;
5826: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5827: linei=linei+1;
5828: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5829: if(line[j] == '\t')
5830: line[j] = ' ';
5831: }
5832: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5833: ;
5834: };
5835: line[j+1]=0; /* Trims blanks at end of line */
5836: if(line[0]=='#'){
5837: fprintf(ficlog,"Comment line\n%s\n",line);
5838: printf("Comment line\n%s\n",line);
5839: continue;
5840: }
5841: trimbb(linetmp,line); /* Trims multiple blanks in line */
5842: strcpy(line, linetmp);
5843:
5844:
5845: for (j=maxwav;j>=1;j--){
5846: cutv(stra, strb, line, ' ');
5847: if(strb[0]=='.') { /* Missing status */
5848: lval=-1;
5849: }else{
5850: errno=0;
5851: lval=strtol(strb,&endptr,10);
5852: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5853: if( strb[0]=='\0' || (*endptr != '\0')){
5854: 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);
5855: 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);
5856: return 1;
5857: }
5858: }
5859: s[j][i]=lval;
5860:
5861: strcpy(line,stra);
5862: cutv(stra, strb,line,' ');
5863: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5864: }
5865: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5866: month=99;
5867: year=9999;
5868: }else{
5869: 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);
5870: 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);
5871: return 1;
5872: }
5873: anint[j][i]= (double) year;
5874: mint[j][i]= (double)month;
5875: strcpy(line,stra);
5876: } /* ENd Waves */
5877:
5878: cutv(stra, strb,line,' ');
5879: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5880: }
5881: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5882: month=99;
5883: year=9999;
5884: }else{
5885: 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);
5886: 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);
5887: return 1;
5888: }
5889: andc[i]=(double) year;
5890: moisdc[i]=(double) month;
5891: strcpy(line,stra);
5892:
5893: cutv(stra, strb,line,' ');
5894: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5895: }
5896: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5897: month=99;
5898: year=9999;
5899: }else{
5900: 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);
5901: 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);
5902: return 1;
5903: }
5904: if (year==9999) {
5905: 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);
5906: 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);
5907: return 1;
5908:
5909: }
5910: annais[i]=(double)(year);
5911: moisnais[i]=(double)(month);
5912: strcpy(line,stra);
5913:
5914: cutv(stra, strb,line,' ');
5915: errno=0;
5916: dval=strtod(strb,&endptr);
5917: if( strb[0]=='\0' || (*endptr != '\0')){
5918: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5919: 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);
5920: fflush(ficlog);
5921: return 1;
5922: }
5923: weight[i]=dval;
5924: strcpy(line,stra);
5925:
5926: for (j=ncovcol;j>=1;j--){
5927: cutv(stra, strb,line,' ');
5928: if(strb[0]=='.') { /* Missing status */
5929: lval=-1;
5930: }else{
5931: errno=0;
5932: lval=strtol(strb,&endptr,10);
5933: if( strb[0]=='\0' || (*endptr != '\0')){
5934: 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);
5935: 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);
5936: return 1;
5937: }
5938: }
5939: if(lval <-1 || lval >1){
5940: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5941: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5942: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5943: For example, for multinomial values like 1, 2 and 3,\n \
5944: build V1=0 V2=0 for the reference value (1),\n \
5945: V1=1 V2=0 for (2) \n \
5946: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5947: output of IMaCh is often meaningless.\n \
5948: Exiting.\n",lval,linei, i,line,j);
5949: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5950: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5951: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5952: For example, for multinomial values like 1, 2 and 3,\n \
5953: build V1=0 V2=0 for the reference value (1),\n \
5954: V1=1 V2=0 for (2) \n \
5955: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5956: output of IMaCh is often meaningless.\n \
5957: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5958: return 1;
5959: }
5960: covar[j][i]=(double)(lval);
5961: strcpy(line,stra);
5962: }
5963: lstra=strlen(stra);
5964:
5965: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5966: stratrunc = &(stra[lstra-9]);
5967: num[i]=atol(stratrunc);
5968: }
5969: else
5970: num[i]=atol(stra);
5971: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5972: 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;}*/
5973:
5974: i=i+1;
5975: } /* End loop reading data */
5976:
5977: *imax=i-1; /* Number of individuals */
5978: fclose(fic);
5979:
5980: return (0);
5981: /* endread: */
5982: printf("Exiting readdata: ");
5983: fclose(fic);
5984: return (1);
5985:
5986:
5987:
5988: }
5989: void removespace(char *str) {
5990: char *p1 = str, *p2 = str;
5991: do
5992: while (*p2 == ' ')
5993: p2++;
5994: while (*p1++ == *p2++);
5995: }
5996:
5997: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5998: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5999: * - nagesqr = 1 if age*age in the model, otherwise 0.
6000: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6001: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6002: * - cptcovage number of covariates with age*products =2
6003: * - cptcovs number of simple covariates
6004: * - 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
6005: * which is a new column after the 9 (ncovcol) variables.
6006: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6007: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6008: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6009: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6010: */
6011: {
6012: int i, j, k, ks;
6013: int j1, k1, k2;
6014: char modelsav[80];
6015: char stra[80], strb[80], strc[80], strd[80],stre[80];
6016: char *strpt;
6017:
6018: /*removespace(model);*/
6019: if (strlen(model) >1){ /* If there is at least 1 covariate */
6020: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6021: if (strstr(model,"AGE") !=0){
6022: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6023: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6024: return 1;
6025: }
6026: if (strstr(model,"v") !=0){
6027: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6028: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6029: return 1;
6030: }
6031: strcpy(modelsav,model);
6032: if ((strpt=strstr(model,"age*age")) !=0){
6033: printf(" strpt=%s, model=%s\n",strpt, model);
6034: if(strpt != model){
6035: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6036: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6037: corresponding column of parameters.\n",model);
6038: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6039: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6040: corresponding column of parameters.\n",model); fflush(ficlog);
6041: return 1;
6042: }
6043:
6044: nagesqr=1;
6045: if (strstr(model,"+age*age") !=0)
6046: substrchaine(modelsav, model, "+age*age");
6047: else if (strstr(model,"age*age+") !=0)
6048: substrchaine(modelsav, model, "age*age+");
6049: else
6050: substrchaine(modelsav, model, "age*age");
6051: }else
6052: nagesqr=0;
6053: if (strlen(modelsav) >1){
6054: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6055: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6056: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6057: cptcovt= j+1; /* Number of total covariates in the model, not including
6058: * cst, age and age*age
6059: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6060: /* including age products which are counted in cptcovage.
6061: * but the covariates which are products must be treated
6062: * separately: ncovn=4- 2=2 (V1+V3). */
6063: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6064: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6065:
6066:
6067: /* Design
6068: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6069: * < ncovcol=8 >
6070: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6071: * k= 1 2 3 4 5 6 7 8
6072: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6073: * covar[k,i], value of kth covariate if not including age for individual i:
6074: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6075: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6076: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6077: * Tage[++cptcovage]=k
6078: * if products, new covar are created after ncovcol with k1
6079: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6080: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6081: * 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
6082: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6083: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6084: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6085: * < ncovcol=8 >
6086: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6087: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6088: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6089: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6090: * p Tprod[1]@2={ 6, 5}
6091: *p Tvard[1][1]@4= {7, 8, 5, 6}
6092: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6093: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6094: *How to reorganize?
6095: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6096: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6097: * {2, 1, 4, 8, 5, 6, 3, 7}
6098: * Struct []
6099: */
6100:
6101: /* This loop fills the array Tvar from the string 'model'.*/
6102: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6103: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6104: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6105: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6106: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6107: /* k=1 Tvar[1]=2 (from V2) */
6108: /* k=5 Tvar[5] */
6109: /* for (k=1; k<=cptcovn;k++) { */
6110: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6111: /* } */
6112: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6113: /*
6114: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6115: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6116: Tvar[k]=0;
6117: cptcovage=0;
6118: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6119: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6120: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6121: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6122: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6123: /*scanf("%d",i);*/
6124: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6125: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6126: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6127: /* covar is not filled and then is empty */
6128: cptcovprod--;
6129: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6130: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6131: cptcovage++; /* Sums the number of covariates which include age as a product */
6132: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6133: /*printf("stre=%s ", stre);*/
6134: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6135: cptcovprod--;
6136: cutl(stre,strb,strc,'V');
6137: Tvar[k]=atoi(stre);
6138: cptcovage++;
6139: Tage[cptcovage]=k;
6140: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6141: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6142: cptcovn++;
6143: cptcovprodnoage++;k1++;
6144: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6145: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6146: because this model-covariate is a construction we invent a new column
6147: ncovcol + k1
6148: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6149: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6150: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6151: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6152: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6153: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6154: k2=k2+2;
6155: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6156: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6157: for (i=1; i<=lastobs;i++){
6158: /* Computes the new covariate which is a product of
6159: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6160: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6161: }
6162: } /* End age is not in the model */
6163: } /* End if model includes a product */
6164: else { /* no more sum */
6165: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6166: /* scanf("%d",i);*/
6167: cutl(strd,strc,strb,'V');
6168: ks++; /**< Number of simple covariates */
6169: cptcovn++;
6170: Tvar[k]=atoi(strd);
6171: }
6172: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6173: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6174: scanf("%d",i);*/
6175: } /* end of loop + on total covariates */
6176: } /* end if strlen(modelsave == 0) age*age might exist */
6177: } /* end if strlen(model == 0) */
6178:
6179: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6180: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6181:
6182: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6183: printf("cptcovprod=%d ", cptcovprod);
6184: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6185:
6186: scanf("%d ",i);*/
6187:
6188:
6189: return (0); /* with covar[new additional covariate if product] and Tage if age */
6190: /*endread:*/
6191: printf("Exiting decodemodel: ");
6192: return (1);
6193: }
6194:
6195: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6196: {
6197: int i, m;
6198:
6199: for (i=1; i<=imx; i++) {
6200: for(m=2; (m<= maxwav); m++) {
6201: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6202: anint[m][i]=9999;
6203: s[m][i]=-1;
6204: }
6205: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6206: *nberr = *nberr + 1;
6207: 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);
6208: 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);
6209: s[m][i]=-1;
6210: }
6211: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6212: (*nberr)++;
6213: 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]);
6214: 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]);
6215: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6216: }
6217: }
6218: }
6219:
6220: for (i=1; i<=imx; i++) {
6221: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6222: for(m=firstpass; (m<= lastpass); m++){
6223: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6224: if (s[m][i] >= nlstate+1) {
6225: if(agedc[i]>0){
6226: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6227: agev[m][i]=agedc[i];
6228: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6229: }else {
6230: if ((int)andc[i]!=9999){
6231: nbwarn++;
6232: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6233: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6234: agev[m][i]=-1;
6235: }
6236: }
6237: } /* agedc > 0 */
6238: }
6239: else if(s[m][i] !=9){ /* Standard case, age in fractional
6240: years but with the precision of a month */
6241: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6242: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6243: agev[m][i]=1;
6244: else if(agev[m][i] < *agemin){
6245: *agemin=agev[m][i];
6246: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6247: }
6248: else if(agev[m][i] >*agemax){
6249: *agemax=agev[m][i];
6250: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6251: }
6252: /*agev[m][i]=anint[m][i]-annais[i];*/
6253: /* agev[m][i] = age[i]+2*m;*/
6254: }
6255: else { /* =9 */
6256: agev[m][i]=1;
6257: s[m][i]=-1;
6258: }
6259: }
6260: else /*= 0 Unknown */
6261: agev[m][i]=1;
6262: }
6263:
6264: }
6265: for (i=1; i<=imx; i++) {
6266: for(m=firstpass; (m<=lastpass); m++){
6267: if (s[m][i] > (nlstate+ndeath)) {
6268: (*nberr)++;
6269: 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);
6270: 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);
6271: return 1;
6272: }
6273: }
6274: }
6275:
6276: /*for (i=1; i<=imx; i++){
6277: for (m=firstpass; (m<lastpass); m++){
6278: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6279: }
6280:
6281: }*/
6282:
6283:
6284: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6285: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6286:
6287: return (0);
6288: /* endread:*/
6289: printf("Exiting calandcheckages: ");
6290: return (1);
6291: }
6292:
6293: #if defined(_MSC_VER)
6294: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6295: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6296: //#include "stdafx.h"
6297: //#include <stdio.h>
6298: //#include <tchar.h>
6299: //#include <windows.h>
6300: //#include <iostream>
6301: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6302:
6303: LPFN_ISWOW64PROCESS fnIsWow64Process;
6304:
6305: BOOL IsWow64()
6306: {
6307: BOOL bIsWow64 = FALSE;
6308:
6309: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6310: // (HANDLE, PBOOL);
6311:
6312: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6313:
6314: HMODULE module = GetModuleHandle(_T("kernel32"));
6315: const char funcName[] = "IsWow64Process";
6316: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6317: GetProcAddress(module, funcName);
6318:
6319: if (NULL != fnIsWow64Process)
6320: {
6321: if (!fnIsWow64Process(GetCurrentProcess(),
6322: &bIsWow64))
6323: //throw std::exception("Unknown error");
6324: printf("Unknown error\n");
6325: }
6326: return bIsWow64 != FALSE;
6327: }
6328: #endif
6329:
6330: void syscompilerinfo(int logged)
6331: {
6332: /* #include "syscompilerinfo.h"*/
6333: /* command line Intel compiler 32bit windows, XP compatible:*/
6334: /* /GS /W3 /Gy
6335: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6336: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6337: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6338: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6339: */
6340: /* 64 bits */
6341: /*
6342: /GS /W3 /Gy
6343: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6344: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6345: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6346: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6347: /* Optimization are useless and O3 is slower than O2 */
6348: /*
6349: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6350: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6351: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6352: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6353: */
6354: /* Link is */ /* /OUT:"visual studio
6355: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6356: /PDB:"visual studio
6357: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6358: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6359: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6360: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6361: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6362: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6363: uiAccess='false'"
6364: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6365: /NOLOGO /TLBID:1
6366: */
6367: #if defined __INTEL_COMPILER
6368: #if defined(__GNUC__)
6369: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6370: #endif
6371: #elif defined(__GNUC__)
6372: #ifndef __APPLE__
6373: #include <gnu/libc-version.h> /* Only on gnu */
6374: #endif
6375: struct utsname sysInfo;
6376: int cross = CROSS;
6377: if (cross){
6378: printf("Cross-");
6379: if(logged) fprintf(ficlog, "Cross-");
6380: }
6381: #endif
6382:
6383: #include <stdint.h>
6384:
6385: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6386: #if defined(__clang__)
6387: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6388: #endif
6389: #if defined(__ICC) || defined(__INTEL_COMPILER)
6390: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6391: #endif
6392: #if defined(__GNUC__) || defined(__GNUG__)
6393: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6394: #endif
6395: #if defined(__HP_cc) || defined(__HP_aCC)
6396: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6397: #endif
6398: #if defined(__IBMC__) || defined(__IBMCPP__)
6399: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6400: #endif
6401: #if defined(_MSC_VER)
6402: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6403: #endif
6404: #if defined(__PGI)
6405: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6406: #endif
6407: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6408: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6409: #endif
6410: printf(" for "); if (logged) fprintf(ficlog, " for ");
6411:
6412: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6413: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6414: // Windows (x64 and x86)
6415: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6416: #elif __unix__ // all unices, not all compilers
6417: // Unix
6418: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6419: #elif __linux__
6420: // linux
6421: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6422: #elif __APPLE__
6423: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6424: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6425: #endif
6426:
6427: /* __MINGW32__ */
6428: /* __CYGWIN__ */
6429: /* __MINGW64__ */
6430: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6431: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6432: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6433: /* _WIN64 // Defined for applications for Win64. */
6434: /* _M_X64 // Defined for compilations that target x64 processors. */
6435: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6436:
6437: #if UINTPTR_MAX == 0xffffffff
6438: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6439: #elif UINTPTR_MAX == 0xffffffffffffffff
6440: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6441: #else
6442: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6443: #endif
6444:
6445: #if defined(__GNUC__)
6446: # if defined(__GNUC_PATCHLEVEL__)
6447: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6448: + __GNUC_MINOR__ * 100 \
6449: + __GNUC_PATCHLEVEL__)
6450: # else
6451: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6452: + __GNUC_MINOR__ * 100)
6453: # endif
6454: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6455: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6456:
6457: if (uname(&sysInfo) != -1) {
6458: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6459: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6460: }
6461: else
6462: perror("uname() error");
6463: //#ifndef __INTEL_COMPILER
6464: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6465: printf("GNU libc version: %s\n", gnu_get_libc_version());
6466: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6467: #endif
6468: #endif
6469:
6470: // void main()
6471: // {
6472: #if defined(_MSC_VER)
6473: if (IsWow64()){
6474: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6475: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6476: }
6477: else{
6478: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6479: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6480: }
6481: // printf("\nPress Enter to continue...");
6482: // getchar();
6483: // }
6484:
6485: #endif
6486:
6487:
6488: }
6489:
6490: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
6491: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6492: int i, j, k, i1 ;
6493: /* double ftolpl = 1.e-10; */
6494: double age, agebase, agelim;
6495: double tot;
6496:
6497: strcpy(filerespl,"PL_");
6498: strcat(filerespl,fileresu);
6499: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6500: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6501: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6502: }
6503: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6504: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6505: pstamp(ficrespl);
6506: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6507: fprintf(ficrespl,"#Age ");
6508: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6509: fprintf(ficrespl,"\n");
6510:
6511: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6512:
6513: agebase=ageminpar;
6514: agelim=agemaxpar;
6515:
6516: i1=pow(2,cptcoveff);
6517: if (cptcovn < 1){i1=1;}
6518:
6519: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6520: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6521: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6522: k=k+1;
6523: /* to clean */
6524: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6525: fprintf(ficrespl,"#******");
6526: printf("#******");
6527: fprintf(ficlog,"#******");
6528: for(j=1;j<=cptcoveff;j++) {
6529: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6530: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6531: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6532: }
6533: fprintf(ficrespl,"******\n");
6534: printf("******\n");
6535: fprintf(ficlog,"******\n");
6536:
6537: fprintf(ficrespl,"#Age ");
6538: for(j=1;j<=cptcoveff;j++) {
6539: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6540: }
6541: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6542: fprintf(ficrespl,"Total Years_to_converge\n");
6543:
6544: for (age=agebase; age<=agelim; age++){
6545: /* for (age=agebase; age<=agebase; age++){ */
6546: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
6547: fprintf(ficrespl,"%.0f ",age );
6548: for(j=1;j<=cptcoveff;j++)
6549: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6550: tot=0.;
6551: for(i=1; i<=nlstate;i++){
6552: tot += prlim[i][i];
6553: fprintf(ficrespl," %.5f", prlim[i][i]);
6554: }
6555: fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
6556: } /* Age */
6557: /* was end of cptcod */
6558: } /* cptcov */
6559: return 0;
6560: }
6561:
6562: int hPijx(double *p, int bage, int fage){
6563: /*------------- h Pij x at various ages ------------*/
6564:
6565: int stepsize;
6566: int agelim;
6567: int hstepm;
6568: int nhstepm;
6569: int h, i, i1, j, k;
6570:
6571: double agedeb;
6572: double ***p3mat;
6573:
6574: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
6575: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6576: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6577: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6578: }
6579: printf("Computing pij: result on file '%s' \n", filerespij);
6580: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6581:
6582: stepsize=(int) (stepm+YEARM-1)/YEARM;
6583: /*if (stepm<=24) stepsize=2;*/
6584:
6585: agelim=AGESUP;
6586: hstepm=stepsize*YEARM; /* Every year of age */
6587: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6588:
6589: /* hstepm=1; aff par mois*/
6590: pstamp(ficrespij);
6591: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6592: i1= pow(2,cptcoveff);
6593: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6594: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6595: /* k=k+1; */
6596: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6597: fprintf(ficrespij,"\n#****** ");
6598: for(j=1;j<=cptcoveff;j++)
6599: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6600: fprintf(ficrespij,"******\n");
6601:
6602: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6603: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6604: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6605:
6606: /* nhstepm=nhstepm*YEARM; aff par mois*/
6607:
6608: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6609: oldm=oldms;savm=savms;
6610: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6611: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6612: for(i=1; i<=nlstate;i++)
6613: for(j=1; j<=nlstate+ndeath;j++)
6614: fprintf(ficrespij," %1d-%1d",i,j);
6615: fprintf(ficrespij,"\n");
6616: for (h=0; h<=nhstepm; h++){
6617: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6618: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
6619: for(i=1; i<=nlstate;i++)
6620: for(j=1; j<=nlstate+ndeath;j++)
6621: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
6622: fprintf(ficrespij,"\n");
6623: }
6624: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6625: fprintf(ficrespij,"\n");
6626: }
6627: /*}*/
6628: }
6629: return 0;
6630: }
6631:
6632:
6633: /***********************************************/
6634: /**************** Main Program *****************/
6635: /***********************************************/
6636:
6637: int main(int argc, char *argv[])
6638: {
6639: #ifdef GSL
6640: const gsl_multimin_fminimizer_type *T;
6641: size_t iteri = 0, it;
6642: int rval = GSL_CONTINUE;
6643: int status = GSL_SUCCESS;
6644: double ssval;
6645: #endif
6646: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
6647: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6648: int ncvyearnp=0;
6649: int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
6650: int jj, ll, li, lj, lk;
6651: int numlinepar=0; /* Current linenumber of parameter file */
6652: int num_filled;
6653: int itimes;
6654: int NDIM=2;
6655: int vpopbased=0;
6656:
6657: char ca[32], cb[32];
6658: /* FILE *fichtm; *//* Html File */
6659: /* FILE *ficgp;*/ /*Gnuplot File */
6660: struct stat info;
6661: double agedeb=0.;
6662:
6663: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
6664:
6665: double fret;
6666: double dum=0.; /* Dummy variable */
6667: double ***p3mat;
6668: double ***mobaverage;
6669:
6670: char line[MAXLINE];
6671: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6672:
6673: char model[MAXLINE], modeltemp[MAXLINE];
6674: char pathr[MAXLINE], pathimach[MAXLINE];
6675: char *tok, *val; /* pathtot */
6676: int firstobs=1, lastobs=10;
6677: int c, h , cpt, c2;
6678: int jl=0;
6679: int i1, j1, jk, stepsize=0;
6680: int count=0;
6681:
6682: int *tab;
6683: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6684: int mobilav=0,popforecast=0;
6685: int hstepm=0, nhstepm=0;
6686: int agemortsup;
6687: float sumlpop=0.;
6688: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6689: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6690:
6691: double bage=0, fage=110., age, agelim=0., agebase=0.;
6692: double ftolpl=FTOL;
6693: double **prlim;
6694: double ***param; /* Matrix of parameters */
6695: double *p;
6696: double **matcov; /* Matrix of covariance */
6697: double **hess; /* Hessian matrix */
6698: double ***delti3; /* Scale */
6699: double *delti; /* Scale */
6700: double ***eij, ***vareij;
6701: double **varpl; /* Variances of prevalence limits by age */
6702: double *epj, vepp;
6703:
6704: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6705: double **ximort;
6706: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
6707: int *dcwave;
6708:
6709: char z[1]="c";
6710:
6711: /*char *strt;*/
6712: char strtend[80];
6713:
6714:
6715: /* setlocale (LC_ALL, ""); */
6716: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6717: /* textdomain (PACKAGE); */
6718: /* setlocale (LC_CTYPE, ""); */
6719: /* setlocale (LC_MESSAGES, ""); */
6720:
6721: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
6722: rstart_time = time(NULL);
6723: /* (void) gettimeofday(&start_time,&tzp);*/
6724: start_time = *localtime(&rstart_time);
6725: curr_time=start_time;
6726: /*tml = *localtime(&start_time.tm_sec);*/
6727: /* strcpy(strstart,asctime(&tml)); */
6728: strcpy(strstart,asctime(&start_time));
6729:
6730: /* printf("Localtime (at start)=%s",strstart); */
6731: /* tp.tm_sec = tp.tm_sec +86400; */
6732: /* tm = *localtime(&start_time.tm_sec); */
6733: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6734: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6735: /* tmg.tm_hour=tmg.tm_hour + 1; */
6736: /* tp.tm_sec = mktime(&tmg); */
6737: /* strt=asctime(&tmg); */
6738: /* printf("Time(after) =%s",strstart); */
6739: /* (void) time (&time_value);
6740: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6741: * tm = *localtime(&time_value);
6742: * strstart=asctime(&tm);
6743: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6744: */
6745:
6746: nberr=0; /* Number of errors and warnings */
6747: nbwarn=0;
6748: #ifdef WIN32
6749: _getcwd(pathcd, size);
6750: #else
6751: getcwd(pathcd, size);
6752: #endif
6753: syscompilerinfo(0);
6754: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
6755: if(argc <=1){
6756: printf("\nEnter the parameter file name: ");
6757: if(!fgets(pathr,FILENAMELENGTH,stdin)){
6758: printf("ERROR Empty parameter file name\n");
6759: goto end;
6760: }
6761: i=strlen(pathr);
6762: if(pathr[i-1]=='\n')
6763: pathr[i-1]='\0';
6764: i=strlen(pathr);
6765: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
6766: pathr[i-1]='\0';
6767: }
6768: i=strlen(pathr);
6769: if( i==0 ){
6770: printf("ERROR Empty parameter file name\n");
6771: goto end;
6772: }
6773: for (tok = pathr; tok != NULL; ){
6774: printf("Pathr |%s|\n",pathr);
6775: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6776: printf("val= |%s| pathr=%s\n",val,pathr);
6777: strcpy (pathtot, val);
6778: if(pathr[0] == '\0') break; /* Dirty */
6779: }
6780: }
6781: else{
6782: strcpy(pathtot,argv[1]);
6783: }
6784: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6785: /*cygwin_split_path(pathtot,path,optionfile);
6786: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6787: /* cutv(path,optionfile,pathtot,'\\');*/
6788:
6789: /* Split argv[0], imach program to get pathimach */
6790: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6791: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6792: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6793: /* strcpy(pathimach,argv[0]); */
6794: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6795: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6796: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6797: #ifdef WIN32
6798: _chdir(path); /* Can be a relative path */
6799: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6800: #else
6801: chdir(path); /* Can be a relative path */
6802: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6803: #endif
6804: printf("Current directory %s!\n",pathcd);
6805: strcpy(command,"mkdir ");
6806: strcat(command,optionfilefiname);
6807: if((outcmd=system(command)) != 0){
6808: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6809: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6810: /* fclose(ficlog); */
6811: /* exit(1); */
6812: }
6813: /* if((imk=mkdir(optionfilefiname))<0){ */
6814: /* perror("mkdir"); */
6815: /* } */
6816:
6817: /*-------- arguments in the command line --------*/
6818:
6819: /* Main Log file */
6820: strcat(filelog, optionfilefiname);
6821: strcat(filelog,".log"); /* */
6822: if((ficlog=fopen(filelog,"w"))==NULL) {
6823: printf("Problem with logfile %s\n",filelog);
6824: goto end;
6825: }
6826: fprintf(ficlog,"Log filename:%s\n",filelog);
6827: fprintf(ficlog,"Version %s %s",version,fullversion);
6828: fprintf(ficlog,"\nEnter the parameter file name: \n");
6829: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6830: path=%s \n\
6831: optionfile=%s\n\
6832: optionfilext=%s\n\
6833: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6834:
6835: syscompilerinfo(1);
6836:
6837: printf("Local time (at start):%s",strstart);
6838: fprintf(ficlog,"Local time (at start): %s",strstart);
6839: fflush(ficlog);
6840: /* (void) gettimeofday(&curr_time,&tzp); */
6841: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6842:
6843: /* */
6844: strcpy(fileres,"r");
6845: strcat(fileres, optionfilefiname);
6846: strcat(fileresu, optionfilefiname); /* Without r in front */
6847: strcat(fileres,".txt"); /* Other files have txt extension */
6848: strcat(fileresu,".txt"); /* Other files have txt extension */
6849:
6850: /* Main ---------arguments file --------*/
6851:
6852: if((ficpar=fopen(optionfile,"r"))==NULL) {
6853: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6854: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6855: fflush(ficlog);
6856: /* goto end; */
6857: exit(70);
6858: }
6859:
6860:
6861:
6862: strcpy(filereso,"o");
6863: strcat(filereso,fileresu);
6864: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6865: printf("Problem with Output resultfile: %s\n", filereso);
6866: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6867: fflush(ficlog);
6868: goto end;
6869: }
6870:
6871: /* Reads comments: lines beginning with '#' */
6872: numlinepar=0;
6873:
6874: /* First parameter line */
6875: while(fgets(line, MAXLINE, ficpar)) {
6876: /* If line starts with a # it is a comment */
6877: if (line[0] == '#') {
6878: numlinepar++;
6879: fputs(line,stdout);
6880: fputs(line,ficparo);
6881: fputs(line,ficlog);
6882: continue;
6883: }else
6884: break;
6885: }
6886: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6887: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6888: if (num_filled != 5) {
6889: printf("Should be 5 parameters\n");
6890: }
6891: numlinepar++;
6892: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6893: }
6894: /* Second parameter line */
6895: while(fgets(line, MAXLINE, ficpar)) {
6896: /* If line starts with a # it is a comment */
6897: if (line[0] == '#') {
6898: numlinepar++;
6899: fputs(line,stdout);
6900: fputs(line,ficparo);
6901: fputs(line,ficlog);
6902: continue;
6903: }else
6904: break;
6905: }
6906: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6907: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
6908: if (num_filled != 8) {
6909: printf("Not 8\n");
6910: }
6911: printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
6912: }
6913: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
6914: ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
6915: /* Third parameter line */
6916: while(fgets(line, MAXLINE, ficpar)) {
6917: /* If line starts with a # it is a comment */
6918: if (line[0] == '#') {
6919: numlinepar++;
6920: fputs(line,stdout);
6921: fputs(line,ficparo);
6922: fputs(line,ficlog);
6923: continue;
6924: }else
6925: break;
6926: }
6927: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
6928: if (num_filled == 0)
6929: model[0]='\0';
6930: else if (num_filled != 1){
6931: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6932: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6933: model[0]='\0';
6934: goto end;
6935: }
6936: else{
6937: if (model[0]=='+'){
6938: for(i=1; i<=strlen(model);i++)
6939: modeltemp[i-1]=model[i];
6940: strcpy(model,modeltemp);
6941: }
6942: }
6943: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
6944: printf("model=1+age+%s\n",model);fflush(stdout);
6945: }
6946: /* fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
6947: /* numlinepar=numlinepar+3; /\* In general *\/ */
6948: /* printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
6949: fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6950: fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6951: fflush(ficlog);
6952: /* if(model[0]=='#'|| model[0]== '\0'){ */
6953: if(model[0]=='#'){
6954: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6955: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6956: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6957: if(mle != -1){
6958: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6959: exit(1);
6960: }
6961: }
6962: while((c=getc(ficpar))=='#' && c!= EOF){
6963: ungetc(c,ficpar);
6964: fgets(line, MAXLINE, ficpar);
6965: numlinepar++;
6966: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
6967: z[0]=line[1];
6968: }
6969: /* printf("****line [1] = %c \n",line[1]); */
6970: fputs(line, stdout);
6971: //puts(line);
6972: fputs(line,ficparo);
6973: fputs(line,ficlog);
6974: }
6975: ungetc(c,ficpar);
6976:
6977:
6978: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6979: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6980: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6981: v1+v2*age+v2*v3 makes cptcovn = 3
6982: */
6983: if (strlen(model)>1)
6984: ncovmodel=2+nbocc(model,'+')+1; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7,age*age makes 3*/
6985: else
6986: ncovmodel=2; /* Constant and age */
6987: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6988: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6989: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6990: 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);
6991: 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);
6992: fflush(stdout);
6993: fclose (ficlog);
6994: goto end;
6995: }
6996: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6997: delti=delti3[1][1];
6998: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6999: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7000: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7001: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7002: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7003: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7004: fclose (ficparo);
7005: fclose (ficlog);
7006: goto end;
7007: exit(0);
7008: }
7009: else if(mle==-3) { /* Main Wizard */
7010: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7011: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7012: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7013: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7014: matcov=matrix(1,npar,1,npar);
7015: hess=matrix(1,npar,1,npar);
7016: }
7017: else{
7018: /* Read guessed parameters */
7019: /* Reads comments: lines beginning with '#' */
7020: while((c=getc(ficpar))=='#' && c!= EOF){
7021: ungetc(c,ficpar);
7022: fgets(line, MAXLINE, ficpar);
7023: numlinepar++;
7024: fputs(line,stdout);
7025: fputs(line,ficparo);
7026: fputs(line,ficlog);
7027: }
7028: ungetc(c,ficpar);
7029:
7030: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7031: for(i=1; i <=nlstate; i++){
7032: j=0;
7033: for(jj=1; jj <=nlstate+ndeath; jj++){
7034: if(jj==i) continue;
7035: j++;
7036: fscanf(ficpar,"%1d%1d",&i1,&j1);
7037: if ((i1 != i) || (j1 != jj)){
7038: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7039: It might be a problem of design; if ncovcol and the model are correct\n \
7040: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7041: exit(1);
7042: }
7043: fprintf(ficparo,"%1d%1d",i1,j1);
7044: if(mle==1)
7045: printf("%1d%1d",i,jj);
7046: fprintf(ficlog,"%1d%1d",i,jj);
7047: for(k=1; k<=ncovmodel;k++){
7048: fscanf(ficpar," %lf",¶m[i][j][k]);
7049: if(mle==1){
7050: printf(" %lf",param[i][j][k]);
7051: fprintf(ficlog," %lf",param[i][j][k]);
7052: }
7053: else
7054: fprintf(ficlog," %lf",param[i][j][k]);
7055: fprintf(ficparo," %lf",param[i][j][k]);
7056: }
7057: fscanf(ficpar,"\n");
7058: numlinepar++;
7059: if(mle==1)
7060: printf("\n");
7061: fprintf(ficlog,"\n");
7062: fprintf(ficparo,"\n");
7063: }
7064: }
7065: fflush(ficlog);
7066:
7067: /* Reads scales values */
7068: p=param[1][1];
7069:
7070: /* Reads comments: lines beginning with '#' */
7071: while((c=getc(ficpar))=='#' && c!= EOF){
7072: ungetc(c,ficpar);
7073: fgets(line, MAXLINE, ficpar);
7074: numlinepar++;
7075: fputs(line,stdout);
7076: fputs(line,ficparo);
7077: fputs(line,ficlog);
7078: }
7079: ungetc(c,ficpar);
7080:
7081: for(i=1; i <=nlstate; i++){
7082: for(j=1; j <=nlstate+ndeath-1; j++){
7083: fscanf(ficpar,"%1d%1d",&i1,&j1);
7084: if ( (i1-i) * (j1-j) != 0){
7085: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7086: exit(1);
7087: }
7088: printf("%1d%1d",i,j);
7089: fprintf(ficparo,"%1d%1d",i1,j1);
7090: fprintf(ficlog,"%1d%1d",i1,j1);
7091: for(k=1; k<=ncovmodel;k++){
7092: fscanf(ficpar,"%le",&delti3[i][j][k]);
7093: printf(" %le",delti3[i][j][k]);
7094: fprintf(ficparo," %le",delti3[i][j][k]);
7095: fprintf(ficlog," %le",delti3[i][j][k]);
7096: }
7097: fscanf(ficpar,"\n");
7098: numlinepar++;
7099: printf("\n");
7100: fprintf(ficparo,"\n");
7101: fprintf(ficlog,"\n");
7102: }
7103: }
7104: fflush(ficlog);
7105:
7106: /* Reads covariance matrix */
7107: delti=delti3[1][1];
7108:
7109:
7110: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7111:
7112: /* Reads comments: lines beginning with '#' */
7113: while((c=getc(ficpar))=='#' && c!= EOF){
7114: ungetc(c,ficpar);
7115: fgets(line, MAXLINE, ficpar);
7116: numlinepar++;
7117: fputs(line,stdout);
7118: fputs(line,ficparo);
7119: fputs(line,ficlog);
7120: }
7121: ungetc(c,ficpar);
7122:
7123: matcov=matrix(1,npar,1,npar);
7124: hess=matrix(1,npar,1,npar);
7125: for(i=1; i <=npar; i++)
7126: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7127:
7128: /* Scans npar lines */
7129: for(i=1; i <=npar; i++){
7130: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7131: if(count != 3){
7132: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7133: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7134: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7135: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7136: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7137: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7138: exit(1);
7139: }else
7140: if(mle==1)
7141: printf("%1d%1d%1d",i1,j1,jk);
7142: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7143: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7144: for(j=1; j <=i; j++){
7145: fscanf(ficpar," %le",&matcov[i][j]);
7146: if(mle==1){
7147: printf(" %.5le",matcov[i][j]);
7148: }
7149: fprintf(ficlog," %.5le",matcov[i][j]);
7150: fprintf(ficparo," %.5le",matcov[i][j]);
7151: }
7152: fscanf(ficpar,"\n");
7153: numlinepar++;
7154: if(mle==1)
7155: printf("\n");
7156: fprintf(ficlog,"\n");
7157: fprintf(ficparo,"\n");
7158: }
7159: /* End of read covariance matrix npar lines */
7160: for(i=1; i <=npar; i++)
7161: for(j=i+1;j<=npar;j++)
7162: matcov[i][j]=matcov[j][i];
7163:
7164: if(mle==1)
7165: printf("\n");
7166: fprintf(ficlog,"\n");
7167:
7168: fflush(ficlog);
7169:
7170: /*-------- Rewriting parameter file ----------*/
7171: strcpy(rfileres,"r"); /* "Rparameterfile */
7172: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7173: strcat(rfileres,"."); /* */
7174: strcat(rfileres,optionfilext); /* Other files have txt extension */
7175: if((ficres =fopen(rfileres,"w"))==NULL) {
7176: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7177: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7178: }
7179: fprintf(ficres,"#%s\n",version);
7180: } /* End of mle != -3 */
7181:
7182: /* Main data
7183: */
7184: n= lastobs;
7185: num=lvector(1,n);
7186: moisnais=vector(1,n);
7187: annais=vector(1,n);
7188: moisdc=vector(1,n);
7189: andc=vector(1,n);
7190: agedc=vector(1,n);
7191: cod=ivector(1,n);
7192: weight=vector(1,n);
7193: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7194: mint=matrix(1,maxwav,1,n);
7195: anint=matrix(1,maxwav,1,n);
7196: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7197: tab=ivector(1,NCOVMAX);
7198: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7199: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7200:
7201: /* Reads data from file datafile */
7202: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7203: goto end;
7204:
7205: /* Calculation of the number of parameters from char model */
7206: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7207: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7208: k=3 V4 Tvar[k=3]= 4 (from V4)
7209: k=2 V1 Tvar[k=2]= 1 (from V1)
7210: k=1 Tvar[1]=2 (from V2)
7211: */
7212: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7213: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7214: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7215: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7216: */
7217: /* For model-covariate k tells which data-covariate to use but
7218: because this model-covariate is a construction we invent a new column
7219: ncovcol + k1
7220: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7221: Tvar[3=V1*V4]=4+1 etc */
7222: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7223: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7224: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7225: */
7226: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7227: 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
7228: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7229: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7230: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7231: 4 covariates (3 plus signs)
7232: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7233: */
7234:
7235: /* Main decodemodel */
7236:
7237:
7238: if(decodemodel(model, lastobs) == 1)
7239: goto end;
7240:
7241: if((double)(lastobs-imx)/(double)imx > 1.10){
7242: nbwarn++;
7243: 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);
7244: 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);
7245: }
7246: /* if(mle==1){*/
7247: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7248: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7249: }
7250:
7251: /*-calculation of age at interview from date of interview and age at death -*/
7252: agev=matrix(1,maxwav,1,imx);
7253:
7254: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7255: goto end;
7256:
7257:
7258: agegomp=(int)agemin;
7259: free_vector(moisnais,1,n);
7260: free_vector(annais,1,n);
7261: /* free_matrix(mint,1,maxwav,1,n);
7262: free_matrix(anint,1,maxwav,1,n);*/
7263: free_vector(moisdc,1,n);
7264: free_vector(andc,1,n);
7265: /* */
7266:
7267: wav=ivector(1,imx);
7268: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7269: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7270: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7271:
7272: /* Concatenates waves */
7273: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7274: /* */
7275:
7276: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7277:
7278: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7279: ncodemax[1]=1;
7280: Ndum =ivector(-1,NCOVMAX);
7281: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7282: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7283: /* Nbcode gives the value of the lth modality of jth covariate, in
7284: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7285: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
7286:
7287: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7288: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7289: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7290: h=0;
7291:
7292:
7293: /*if (cptcovn > 0) */
7294:
7295:
7296: m=pow(2,cptcoveff);
7297:
7298: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7299: * For k=4 covariates, h goes from 1 to 2**k
7300: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
7301: * h\k 1 2 3 4
7302: *______________________________
7303: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7304: * 2 2 1 1 1
7305: * 3 i=2 1 2 1 1
7306: * 4 2 2 1 1
7307: * 5 i=3 1 i=2 1 2 1
7308: * 6 2 1 2 1
7309: * 7 i=4 1 2 2 1
7310: * 8 2 2 2 1
7311: * 9 i=5 1 i=3 1 i=2 1 2
7312: * 10 2 1 1 2
7313: * 11 i=6 1 2 1 2
7314: * 12 2 2 1 2
7315: * 13 i=7 1 i=4 1 2 2
7316: * 14 2 1 2 2
7317: * 15 i=8 1 2 2 2
7318: * 16 2 2 2 2
7319: */
7320: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7321: /* /\* printf("h=%2d ", h); *\/ */
7322: /* /\* for(k=1; k <=10; k++){ *\/ */
7323: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7324: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7325: /* /\* } *\/ */
7326: /* /\* printf("\n"); *\/ */
7327: /* } */
7328: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7329: /* 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 *\/ */
7330: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7331: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7332: /* h++; */
7333: /* if (h>m) */
7334: /* h=1; */
7335: /* codtab[h][k]=j; */
7336: /* /\* codtab[12][3]=1; *\/ */
7337: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7338: /* /\* 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]]); *\/ */
7339: /* } */
7340: /* } */
7341: /* } */
7342: /* } */
7343: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7344: codtab[1][2]=1;codtab[2][2]=2; */
7345: /* for(i=1; i <=m ;i++){ */
7346: /* for(k=1; k <=cptcovn; k++){ */
7347: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7348: /* } */
7349: /* printf("\n"); */
7350: /* } */
7351: /* scanf("%d",i);*/
7352:
7353: free_ivector(Ndum,-1,NCOVMAX);
7354:
7355:
7356:
7357: /* Initialisation of ----------- gnuplot -------------*/
7358: strcpy(optionfilegnuplot,optionfilefiname);
7359: if(mle==-3)
7360: strcat(optionfilegnuplot,"-MORT_");
7361: strcat(optionfilegnuplot,".gp");
7362:
7363: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7364: printf("Problem with file %s",optionfilegnuplot);
7365: }
7366: else{
7367: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7368: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7369: //fprintf(ficgp,"set missing 'NaNq'\n");
7370: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7371: }
7372: /* fclose(ficgp);*/
7373:
7374:
7375: /* Initialisation of --------- index.htm --------*/
7376:
7377: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7378: if(mle==-3)
7379: strcat(optionfilehtm,"-MORT_");
7380: strcat(optionfilehtm,".htm");
7381: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7382: printf("Problem with %s \n",optionfilehtm);
7383: exit(0);
7384: }
7385:
7386: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7387: strcat(optionfilehtmcov,"-cov.htm");
7388: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7389: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7390: }
7391: else{
7392: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7393: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7394: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7395: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7396: }
7397:
7398: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br> \
7399: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7400: <font size=\"2\">IMaCh-%s <br> %s</font> \
7401: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7402: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7403: \n\
7404: <hr size=\"2\" color=\"#EC5E5E\">\
7405: <ul><li><h4>Parameter files</h4>\n\
7406: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7407: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7408: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7409: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7410: - Date and time at start: %s</ul>\n",\
7411: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7412: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7413: fileres,fileres,\
7414: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7415: fflush(fichtm);
7416:
7417: strcpy(pathr,path);
7418: strcat(pathr,optionfilefiname);
7419: #ifdef WIN32
7420: _chdir(optionfilefiname); /* Move to directory named optionfile */
7421: #else
7422: chdir(optionfilefiname); /* Move to directory named optionfile */
7423: #endif
7424:
7425:
7426: /* Calculates basic frequencies. Computes observed prevalence at single age
7427: and prints on file fileres'p'. */
7428: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7429:
7430: fprintf(fichtm,"\n");
7431: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7432: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7433: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7434: imx,agemin,agemax,jmin,jmax,jmean);
7435: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7436: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7437: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7438: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7439: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7440:
7441:
7442: /* For Powell, parameters are in a vector p[] starting at p[1]
7443: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7444: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7445:
7446: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7447: /* For mortality only */
7448: if (mle==-3){
7449: ximort=matrix(1,NDIM,1,NDIM);
7450: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7451: cens=ivector(1,n);
7452: ageexmed=vector(1,n);
7453: agecens=vector(1,n);
7454: dcwave=ivector(1,n);
7455:
7456: for (i=1; i<=imx; i++){
7457: dcwave[i]=-1;
7458: for (m=firstpass; m<=lastpass; m++)
7459: if (s[m][i]>nlstate) {
7460: dcwave[i]=m;
7461: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7462: break;
7463: }
7464: }
7465:
7466: for (i=1; i<=imx; i++) {
7467: if (wav[i]>0){
7468: ageexmed[i]=agev[mw[1][i]][i];
7469: j=wav[i];
7470: agecens[i]=1.;
7471:
7472: if (ageexmed[i]> 1 && wav[i] > 0){
7473: agecens[i]=agev[mw[j][i]][i];
7474: cens[i]= 1;
7475: }else if (ageexmed[i]< 1)
7476: cens[i]= -1;
7477: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7478: cens[i]=0 ;
7479: }
7480: else cens[i]=-1;
7481: }
7482:
7483: for (i=1;i<=NDIM;i++) {
7484: for (j=1;j<=NDIM;j++)
7485: ximort[i][j]=(i == j ? 1.0 : 0.0);
7486: }
7487:
7488: /*p[1]=0.0268; p[NDIM]=0.083;*/
7489: /*printf("%lf %lf", p[1], p[2]);*/
7490:
7491:
7492: #ifdef GSL
7493: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
7494: #else
7495: printf("Powell\n"); fprintf(ficlog,"Powell\n");
7496: #endif
7497: strcpy(filerespow,"POW-MORT_");
7498: strcat(filerespow,fileresu);
7499: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7500: printf("Problem with resultfile: %s\n", filerespow);
7501: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7502: }
7503: #ifdef GSL
7504: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
7505: #else
7506: fprintf(ficrespow,"# Powell\n# iter -2*LL");
7507: #endif
7508: /* for (i=1;i<=nlstate;i++)
7509: for(j=1;j<=nlstate+ndeath;j++)
7510: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7511: */
7512: fprintf(ficrespow,"\n");
7513: #ifdef GSL
7514: /* gsl starts here */
7515: T = gsl_multimin_fminimizer_nmsimplex;
7516: gsl_multimin_fminimizer *sfm = NULL;
7517: gsl_vector *ss, *x;
7518: gsl_multimin_function minex_func;
7519:
7520: /* Initial vertex size vector */
7521: ss = gsl_vector_alloc (NDIM);
7522:
7523: if (ss == NULL){
7524: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7525: }
7526: /* Set all step sizes to 1 */
7527: gsl_vector_set_all (ss, 0.001);
7528:
7529: /* Starting point */
7530:
7531: x = gsl_vector_alloc (NDIM);
7532:
7533: if (x == NULL){
7534: gsl_vector_free(ss);
7535: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7536: }
7537:
7538: /* Initialize method and iterate */
7539: /* p[1]=0.0268; p[NDIM]=0.083; */
7540: /* gsl_vector_set(x, 0, 0.0268); */
7541: /* gsl_vector_set(x, 1, 0.083); */
7542: gsl_vector_set(x, 0, p[1]);
7543: gsl_vector_set(x, 1, p[2]);
7544:
7545: minex_func.f = &gompertz_f;
7546: minex_func.n = NDIM;
7547: minex_func.params = (void *)&p; /* ??? */
7548:
7549: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7550: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7551:
7552: printf("Iterations beginning .....\n\n");
7553: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7554:
7555: iteri=0;
7556: while (rval == GSL_CONTINUE){
7557: iteri++;
7558: status = gsl_multimin_fminimizer_iterate(sfm);
7559:
7560: if (status) printf("error: %s\n", gsl_strerror (status));
7561: fflush(0);
7562:
7563: if (status)
7564: break;
7565:
7566: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7567: ssval = gsl_multimin_fminimizer_size (sfm);
7568:
7569: if (rval == GSL_SUCCESS)
7570: printf ("converged to a local maximum at\n");
7571:
7572: printf("%5d ", iteri);
7573: for (it = 0; it < NDIM; it++){
7574: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7575: }
7576: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7577: }
7578:
7579: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7580:
7581: gsl_vector_free(x); /* initial values */
7582: gsl_vector_free(ss); /* inital step size */
7583: for (it=0; it<NDIM; it++){
7584: p[it+1]=gsl_vector_get(sfm->x,it);
7585: fprintf(ficrespow," %.12lf", p[it]);
7586: }
7587: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7588: #endif
7589: #ifdef POWELL
7590: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7591: #endif
7592: fclose(ficrespow);
7593:
7594: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
7595:
7596: for(i=1; i <=NDIM; i++)
7597: for(j=i+1;j<=NDIM;j++)
7598: matcov[i][j]=matcov[j][i];
7599:
7600: printf("\nCovariance matrix\n ");
7601: fprintf(ficlog,"\nCovariance matrix\n ");
7602: for(i=1; i <=NDIM; i++) {
7603: for(j=1;j<=NDIM;j++){
7604: printf("%f ",matcov[i][j]);
7605: fprintf(ficlog,"%f ",matcov[i][j]);
7606: }
7607: printf("\n "); fprintf(ficlog,"\n ");
7608: }
7609:
7610: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7611: for (i=1;i<=NDIM;i++) {
7612: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7613: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7614: }
7615: lsurv=vector(1,AGESUP);
7616: lpop=vector(1,AGESUP);
7617: tpop=vector(1,AGESUP);
7618: lsurv[agegomp]=100000;
7619:
7620: for (k=agegomp;k<=AGESUP;k++) {
7621: agemortsup=k;
7622: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7623: }
7624:
7625: for (k=agegomp;k<agemortsup;k++)
7626: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7627:
7628: for (k=agegomp;k<agemortsup;k++){
7629: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7630: sumlpop=sumlpop+lpop[k];
7631: }
7632:
7633: tpop[agegomp]=sumlpop;
7634: for (k=agegomp;k<(agemortsup-3);k++){
7635: /* tpop[k+1]=2;*/
7636: tpop[k+1]=tpop[k]-lpop[k];
7637: }
7638:
7639:
7640: printf("\nAge lx qx dx Lx Tx e(x)\n");
7641: for (k=agegomp;k<(agemortsup-2);k++)
7642: 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]);
7643:
7644:
7645: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7646: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7647: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7648: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7649: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7650: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7651: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7652: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7653: }else
7654: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7655: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
7656: stepm, weightopt,\
7657: model,imx,p,matcov,agemortsup);
7658:
7659: free_vector(lsurv,1,AGESUP);
7660: free_vector(lpop,1,AGESUP);
7661: free_vector(tpop,1,AGESUP);
7662: #ifdef GSL
7663: free_ivector(cens,1,n);
7664: free_vector(agecens,1,n);
7665: free_ivector(dcwave,1,n);
7666: free_matrix(ximort,1,NDIM,1,NDIM);
7667: #endif
7668: } /* Endof if mle==-3 mortality only */
7669: /* Standard */
7670: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
7671: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7672: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7673: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7674: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7675: for (k=1; k<=npar;k++)
7676: printf(" %d %8.5f",k,p[k]);
7677: printf("\n");
7678: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
7679: /* mlikeli uses func not funcone */
7680: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7681: }
7682: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
7683: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7684: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7685: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7686: }
7687: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
7688: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7689: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7690: for (k=1; k<=npar;k++)
7691: printf(" %d %8.5f",k,p[k]);
7692: printf("\n");
7693:
7694: /*--------- results files --------------*/
7695: fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
7696:
7697:
7698: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7699: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7700: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7701: for(i=1,jk=1; i <=nlstate; i++){
7702: for(k=1; k <=(nlstate+ndeath); k++){
7703: if (k != i) {
7704: printf("%d%d ",i,k);
7705: fprintf(ficlog,"%d%d ",i,k);
7706: fprintf(ficres,"%1d%1d ",i,k);
7707: for(j=1; j <=ncovmodel; j++){
7708: printf("%12.7f ",p[jk]);
7709: fprintf(ficlog,"%12.7f ",p[jk]);
7710: fprintf(ficres,"%12.7f ",p[jk]);
7711: jk++;
7712: }
7713: printf("\n");
7714: fprintf(ficlog,"\n");
7715: fprintf(ficres,"\n");
7716: }
7717: }
7718: }
7719: if(mle != 0){
7720: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
7721: ftolhess=ftol; /* Usually correct */
7722: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
7723: printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
7724: fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
7725: for(i=1,jk=1; i <=nlstate; i++){
7726: for(k=1; k <=(nlstate+ndeath); k++){
7727: if (k != i) {
7728: printf("%d%d ",i,k);
7729: fprintf(ficlog,"%d%d ",i,k);
7730: for(j=1; j <=ncovmodel; j++){
7731: printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
7732: fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
7733: jk++;
7734: }
7735: printf("\n");
7736: fprintf(ficlog,"\n");
7737: }
7738: }
7739: }
7740: } /* end of hesscov and Wald tests */
7741:
7742: /* */
7743: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7744: printf("# Scales (for hessian or gradient estimation)\n");
7745: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7746: for(i=1,jk=1; i <=nlstate; i++){
7747: for(j=1; j <=nlstate+ndeath; j++){
7748: if (j!=i) {
7749: fprintf(ficres,"%1d%1d",i,j);
7750: printf("%1d%1d",i,j);
7751: fprintf(ficlog,"%1d%1d",i,j);
7752: for(k=1; k<=ncovmodel;k++){
7753: printf(" %.5e",delti[jk]);
7754: fprintf(ficlog," %.5e",delti[jk]);
7755: fprintf(ficres," %.5e",delti[jk]);
7756: jk++;
7757: }
7758: printf("\n");
7759: fprintf(ficlog,"\n");
7760: fprintf(ficres,"\n");
7761: }
7762: }
7763: }
7764:
7765: 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");
7766: if(mle >= 1) /* To big for the screen */
7767: 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");
7768: 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");
7769: /* # 121 Var(a12)\n\ */
7770: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7771: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7772: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7773: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7774: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7775: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7776: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7777:
7778:
7779: /* Just to have a covariance matrix which will be more understandable
7780: even is we still don't want to manage dictionary of variables
7781: */
7782: for(itimes=1;itimes<=2;itimes++){
7783: jj=0;
7784: for(i=1; i <=nlstate; i++){
7785: for(j=1; j <=nlstate+ndeath; j++){
7786: if(j==i) continue;
7787: for(k=1; k<=ncovmodel;k++){
7788: jj++;
7789: ca[0]= k+'a'-1;ca[1]='\0';
7790: if(itimes==1){
7791: if(mle>=1)
7792: printf("#%1d%1d%d",i,j,k);
7793: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7794: fprintf(ficres,"#%1d%1d%d",i,j,k);
7795: }else{
7796: if(mle>=1)
7797: printf("%1d%1d%d",i,j,k);
7798: fprintf(ficlog,"%1d%1d%d",i,j,k);
7799: fprintf(ficres,"%1d%1d%d",i,j,k);
7800: }
7801: ll=0;
7802: for(li=1;li <=nlstate; li++){
7803: for(lj=1;lj <=nlstate+ndeath; lj++){
7804: if(lj==li) continue;
7805: for(lk=1;lk<=ncovmodel;lk++){
7806: ll++;
7807: if(ll<=jj){
7808: cb[0]= lk +'a'-1;cb[1]='\0';
7809: if(ll<jj){
7810: if(itimes==1){
7811: if(mle>=1)
7812: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7813: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7814: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7815: }else{
7816: if(mle>=1)
7817: printf(" %.5e",matcov[jj][ll]);
7818: fprintf(ficlog," %.5e",matcov[jj][ll]);
7819: fprintf(ficres," %.5e",matcov[jj][ll]);
7820: }
7821: }else{
7822: if(itimes==1){
7823: if(mle>=1)
7824: printf(" Var(%s%1d%1d)",ca,i,j);
7825: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7826: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7827: }else{
7828: if(mle>=1)
7829: printf(" %.7e",matcov[jj][ll]);
7830: fprintf(ficlog," %.7e",matcov[jj][ll]);
7831: fprintf(ficres," %.7e",matcov[jj][ll]);
7832: }
7833: }
7834: }
7835: } /* end lk */
7836: } /* end lj */
7837: } /* end li */
7838: if(mle>=1)
7839: printf("\n");
7840: fprintf(ficlog,"\n");
7841: fprintf(ficres,"\n");
7842: numlinepar++;
7843: } /* end k*/
7844: } /*end j */
7845: } /* end i */
7846: } /* end itimes */
7847:
7848: fflush(ficlog);
7849: fflush(ficres);
7850:
7851: while((c=getc(ficpar))=='#' && c!= EOF){
7852: ungetc(c,ficpar);
7853: fgets(line, MAXLINE, ficpar);
7854: fputs(line,stdout);
7855: fputs(line,ficparo);
7856: }
7857: ungetc(c,ficpar);
7858:
7859: estepm=0;
7860: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7861: if (estepm==0 || estepm < stepm) estepm=stepm;
7862: if (fage <= 2) {
7863: bage = ageminpar;
7864: fage = agemaxpar;
7865: }
7866:
7867: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7868: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7869: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7870:
7871: /* Other stuffs, more or less useful */
7872: while((c=getc(ficpar))=='#' && c!= EOF){
7873: ungetc(c,ficpar);
7874: fgets(line, MAXLINE, ficpar);
7875: fputs(line,stdout);
7876: fputs(line,ficparo);
7877: }
7878: ungetc(c,ficpar);
7879:
7880: 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);
7881: 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);
7882: 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);
7883: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7884: 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);
7885:
7886: while((c=getc(ficpar))=='#' && c!= EOF){
7887: ungetc(c,ficpar);
7888: fgets(line, MAXLINE, ficpar);
7889: fputs(line,stdout);
7890: fputs(line,ficparo);
7891: }
7892: ungetc(c,ficpar);
7893:
7894:
7895: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7896: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7897:
7898: fscanf(ficpar,"pop_based=%d\n",&popbased);
7899: fprintf(ficlog,"pop_based=%d\n",popbased);
7900: fprintf(ficparo,"pop_based=%d\n",popbased);
7901: fprintf(ficres,"pop_based=%d\n",popbased);
7902:
7903: while((c=getc(ficpar))=='#' && c!= EOF){
7904: ungetc(c,ficpar);
7905: fgets(line, MAXLINE, ficpar);
7906: fputs(line,stdout);
7907: fputs(line,ficparo);
7908: }
7909: ungetc(c,ficpar);
7910:
7911: 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);
7912: 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);
7913: 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);
7914: 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);
7915: 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);
7916: /* day and month of proj2 are not used but only year anproj2.*/
7917:
7918:
7919:
7920: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7921: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
7922:
7923: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7924: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
7925: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7926: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7927: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7928: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7929: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7930: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7931: }else
7932: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7933:
7934: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
7935: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7936: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7937:
7938: /*------------ free_vector -------------*/
7939: /* chdir(path); */
7940:
7941: free_ivector(wav,1,imx);
7942: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7943: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7944: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7945: free_lvector(num,1,n);
7946: free_vector(agedc,1,n);
7947: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7948: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7949: fclose(ficparo);
7950: fclose(ficres);
7951:
7952:
7953: /* Other results (useful)*/
7954:
7955:
7956: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
7957: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7958: prlim=matrix(1,nlstate,1,nlstate);
7959: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, ncvyear);
7960: fclose(ficrespl);
7961:
7962: #ifdef FREEEXIT2
7963: #include "freeexit2.h"
7964: #endif
7965:
7966: /*------------- h Pij x at various ages ------------*/
7967: /*#include "hpijx.h"*/
7968: hPijx(p, bage, fage);
7969: fclose(ficrespij);
7970:
7971: /*-------------- Variance of one-step probabilities---*/
7972: k=1;
7973: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7974:
7975:
7976: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7977: for(i=1;i<=AGESUP;i++)
7978: for(j=1;j<=NCOVMAX;j++)
7979: for(k=1;k<=NCOVMAX;k++)
7980: probs[i][j][k]=0.;
7981:
7982: /*---------- Forecasting ------------------*/
7983: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7984: if(prevfcast==1){
7985: /* if(stepm ==1){*/
7986: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7987: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7988: /* } */
7989: /* else{ */
7990: /* erreur=108; */
7991: /* 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); */
7992: /* 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); */
7993: /* } */
7994: }
7995:
7996: /* ------ Other prevalence ratios------------ */
7997:
7998: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7999:
8000: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8001: /* 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",\
8002: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8003: */
8004:
8005: if (mobilav!=0) {
8006: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8007: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8008: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8009: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8010: }
8011: }
8012:
8013:
8014: /*---------- Health expectancies, no variances ------------*/
8015:
8016: strcpy(filerese,"E_");
8017: strcat(filerese,fileresu);
8018: if((ficreseij=fopen(filerese,"w"))==NULL) {
8019: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8020: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8021: }
8022: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
8023: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
8024: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8025: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8026:
8027: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8028: fprintf(ficreseij,"\n#****** ");
8029: for(j=1;j<=cptcoveff;j++) {
8030: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8031: }
8032: fprintf(ficreseij,"******\n");
8033:
8034: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8035: oldm=oldms;savm=savms;
8036: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8037:
8038: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8039: /*}*/
8040: }
8041: fclose(ficreseij);
8042:
8043:
8044: /*---------- Health expectancies and variances ------------*/
8045:
8046:
8047: strcpy(filerest,"T_");
8048: strcat(filerest,fileresu);
8049: if((ficrest=fopen(filerest,"w"))==NULL) {
8050: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8051: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8052: }
8053: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
8054: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
8055:
8056:
8057: strcpy(fileresstde,"STDE_");
8058: strcat(fileresstde,fileresu);
8059: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8060: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8061: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8062: }
8063: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8064: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8065:
8066: strcpy(filerescve,"CVE_");
8067: strcat(filerescve,fileresu);
8068: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8069: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8070: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8071: }
8072: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8073: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8074:
8075: strcpy(fileresv,"V_");
8076: strcat(fileresv,fileresu);
8077: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8078: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8079: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8080: }
8081: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
8082: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
8083:
8084: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8085: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8086:
8087: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8088: fprintf(ficrest,"\n#****** ");
8089: for(j=1;j<=cptcoveff;j++)
8090: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8091: fprintf(ficrest,"******\n");
8092:
8093: fprintf(ficresstdeij,"\n#****** ");
8094: fprintf(ficrescveij,"\n#****** ");
8095: for(j=1;j<=cptcoveff;j++) {
8096: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8097: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8098: }
8099: fprintf(ficresstdeij,"******\n");
8100: fprintf(ficrescveij,"******\n");
8101:
8102: fprintf(ficresvij,"\n#****** ");
8103: for(j=1;j<=cptcoveff;j++)
8104: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8105: fprintf(ficresvij,"******\n");
8106:
8107: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8108: oldm=oldms;savm=savms;
8109: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8110: /*
8111: */
8112: /* goto endfree; */
8113:
8114: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8115: pstamp(ficrest);
8116:
8117:
8118: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8119: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8120: cptcod= 0; /* To be deleted */
8121: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
8122: 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 ");
8123: if(vpopbased==1)
8124: 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);
8125: else
8126: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8127: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8128: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8129: fprintf(ficrest,"\n");
8130: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8131: epj=vector(1,nlstate+1);
8132: for(age=bage; age <=fage ;age++){
8133: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
8134: if (vpopbased==1) {
8135: if(mobilav ==0){
8136: for(i=1; i<=nlstate;i++)
8137: prlim[i][i]=probs[(int)age][i][k];
8138: }else{ /* mobilav */
8139: for(i=1; i<=nlstate;i++)
8140: prlim[i][i]=mobaverage[(int)age][i][k];
8141: }
8142: }
8143:
8144: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8145: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8146: /* printf(" age %4.0f ",age); */
8147: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8148: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8149: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8150: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8151: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8152: }
8153: epj[nlstate+1] +=epj[j];
8154: }
8155: /* printf(" age %4.0f \n",age); */
8156:
8157: for(i=1, vepp=0.;i <=nlstate;i++)
8158: for(j=1;j <=nlstate;j++)
8159: vepp += vareij[i][j][(int)age];
8160: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8161: for(j=1;j <=nlstate;j++){
8162: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8163: }
8164: fprintf(ficrest,"\n");
8165: }
8166: }
8167: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8168: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8169: free_vector(epj,1,nlstate+1);
8170: /*}*/
8171: }
8172: free_vector(weight,1,n);
8173: free_imatrix(Tvard,1,NCOVMAX,1,2);
8174: free_imatrix(s,1,maxwav+1,1,n);
8175: free_matrix(anint,1,maxwav,1,n);
8176: free_matrix(mint,1,maxwav,1,n);
8177: free_ivector(cod,1,n);
8178: free_ivector(tab,1,NCOVMAX);
8179: fclose(ficresstdeij);
8180: fclose(ficrescveij);
8181: fclose(ficresvij);
8182: fclose(ficrest);
8183: fclose(ficpar);
8184:
8185: /*------- Variance of period (stable) prevalence------*/
8186:
8187: strcpy(fileresvpl,"VPL_");
8188: strcat(fileresvpl,fileresu);
8189: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8190: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8191: exit(0);
8192: }
8193: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
8194:
8195: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8196: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8197:
8198: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8199: fprintf(ficresvpl,"\n#****** ");
8200: for(j=1;j<=cptcoveff;j++)
8201: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8202: fprintf(ficresvpl,"******\n");
8203:
8204: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8205: oldm=oldms;savm=savms;
8206: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
8207: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8208: /*}*/
8209: }
8210:
8211: fclose(ficresvpl);
8212:
8213: /*---------- End : free ----------------*/
8214: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8215: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8216: } /* mle==-3 arrives here for freeing */
8217: /* endfree:*/
8218: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8219: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8220: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8221: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8222: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8223: free_matrix(covar,0,NCOVMAX,1,n);
8224: free_matrix(matcov,1,npar,1,npar);
8225: free_matrix(hess,1,npar,1,npar);
8226: /*free_vector(delti,1,npar);*/
8227: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8228: free_matrix(agev,1,maxwav,1,imx);
8229: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8230:
8231: free_ivector(ncodemax,1,NCOVMAX);
8232: free_ivector(ncodemaxwundef,1,NCOVMAX);
8233: free_ivector(Tvar,1,NCOVMAX);
8234: free_ivector(Tprod,1,NCOVMAX);
8235: free_ivector(Tvaraff,1,NCOVMAX);
8236: free_ivector(Tage,1,NCOVMAX);
8237:
8238: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8239: /* free_imatrix(codtab,1,100,1,10); */
8240: fflush(fichtm);
8241: fflush(ficgp);
8242:
8243:
8244: if((nberr >0) || (nbwarn>0)){
8245: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8246: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8247: }else{
8248: printf("End of Imach\n");
8249: fprintf(ficlog,"End of Imach\n");
8250: }
8251: printf("See log file on %s\n",filelog);
8252: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8253: /*(void) gettimeofday(&end_time,&tzp);*/
8254: rend_time = time(NULL);
8255: end_time = *localtime(&rend_time);
8256: /* tml = *localtime(&end_time.tm_sec); */
8257: strcpy(strtend,asctime(&end_time));
8258: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8259: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8260: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8261:
8262: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8263: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8264: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8265: /* printf("Total time was %d uSec.\n", total_usecs);*/
8266: /* if(fileappend(fichtm,optionfilehtm)){ */
8267: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8268: fclose(fichtm);
8269: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8270: fclose(fichtmcov);
8271: fclose(ficgp);
8272: fclose(ficlog);
8273: /*------ End -----------*/
8274:
8275:
8276: printf("Before Current directory %s!\n",pathcd);
8277: #ifdef WIN32
8278: if (_chdir(pathcd) != 0)
8279: printf("Can't move to directory %s!\n",path);
8280: if(_getcwd(pathcd,MAXLINE) > 0)
8281: #else
8282: if(chdir(pathcd) != 0)
8283: printf("Can't move to directory %s!\n", path);
8284: if (getcwd(pathcd, MAXLINE) > 0)
8285: #endif
8286: printf("Current directory %s!\n",pathcd);
8287: /*strcat(plotcmd,CHARSEPARATOR);*/
8288: sprintf(plotcmd,"gnuplot");
8289: #ifdef _WIN32
8290: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8291: #endif
8292: if(!stat(plotcmd,&info)){
8293: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8294: if(!stat(getenv("GNUPLOTBIN"),&info)){
8295: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8296: }else
8297: strcpy(pplotcmd,plotcmd);
8298: #ifdef __unix
8299: strcpy(plotcmd,GNUPLOTPROGRAM);
8300: if(!stat(plotcmd,&info)){
8301: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8302: }else
8303: strcpy(pplotcmd,plotcmd);
8304: #endif
8305: }else
8306: strcpy(pplotcmd,plotcmd);
8307:
8308: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8309: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8310:
8311: if((outcmd=system(plotcmd)) != 0){
8312: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8313: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8314: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8315: if((outcmd=system(plotcmd)) != 0)
8316: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8317: }
8318: printf(" Successful, please wait...");
8319: while (z[0] != 'q') {
8320: /* chdir(path); */
8321: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8322: scanf("%s",z);
8323: /* if (z[0] == 'c') system("./imach"); */
8324: if (z[0] == 'e') {
8325: #ifdef __APPLE__
8326: sprintf(pplotcmd, "open %s", optionfilehtm);
8327: #elif __linux
8328: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8329: #else
8330: sprintf(pplotcmd, "%s", optionfilehtm);
8331: #endif
8332: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8333: system(pplotcmd);
8334: }
8335: else if (z[0] == 'g') system(plotcmd);
8336: else if (z[0] == 'q') exit(0);
8337: }
8338: end:
8339: while (z[0] != 'q') {
8340: printf("\nType q for exiting: "); fflush(stdout);
8341: scanf("%s",z);
8342: }
8343: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>