1: /* $Id: imach.c,v 1.213 2015/12/11 18:22:17 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.213 2015/12/11 18:22:17 brouard
5: Summary: 0.98r4
6:
7: Revision 1.212 2015/11/21 12:47:24 brouard
8: Summary: minor typo
9:
10: Revision 1.211 2015/11/21 12:41:11 brouard
11: Summary: 0.98r3 with some graph of projected cross-sectional
12:
13: Author: Nicolas Brouard
14:
15: Revision 1.210 2015/11/18 17:41:20 brouard
16: Summary: Start working on projected prevalences
17:
18: Revision 1.209 2015/11/17 22:12:03 brouard
19: Summary: Adding ftolpl parameter
20: Author: N Brouard
21:
22: We had difficulties to get smoothed confidence intervals. It was due
23: to the period prevalence which wasn't computed accurately. The inner
24: parameter ftolpl is now an outer parameter of the .imach parameter
25: file after estepm. If ftolpl is small 1.e-4 and estepm too,
26: computation are long.
27:
28: Revision 1.208 2015/11/17 14:31:57 brouard
29: Summary: temporary
30:
31: Revision 1.207 2015/10/27 17:36:57 brouard
32: *** empty log message ***
33:
34: Revision 1.206 2015/10/24 07:14:11 brouard
35: *** empty log message ***
36:
37: Revision 1.205 2015/10/23 15:50:53 brouard
38: Summary: 0.98r3 some clarification for graphs on likelihood contributions
39:
40: Revision 1.204 2015/10/01 16:20:26 brouard
41: Summary: Some new graphs of contribution to likelihood
42:
43: Revision 1.203 2015/09/30 17:45:14 brouard
44: Summary: looking at better estimation of the hessian
45:
46: Also a better criteria for convergence to the period prevalence And
47: therefore adding the number of years needed to converge. (The
48: prevalence in any alive state shold sum to one
49:
50: Revision 1.202 2015/09/22 19:45:16 brouard
51: Summary: Adding some overall graph on contribution to likelihood. Might change
52:
53: Revision 1.201 2015/09/15 17:34:58 brouard
54: Summary: 0.98r0
55:
56: - Some new graphs like suvival functions
57: - Some bugs fixed like model=1+age+V2.
58:
59: Revision 1.200 2015/09/09 16:53:55 brouard
60: Summary: Big bug thanks to Flavia
61:
62: Even model=1+age+V2. did not work anymore
63:
64: Revision 1.199 2015/09/07 14:09:23 brouard
65: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
66:
67: Revision 1.198 2015/09/03 07:14:39 brouard
68: Summary: 0.98q5 Flavia
69:
70: Revision 1.197 2015/09/01 18:24:39 brouard
71: *** empty log message ***
72:
73: Revision 1.196 2015/08/18 23:17:52 brouard
74: Summary: 0.98q5
75:
76: Revision 1.195 2015/08/18 16:28:39 brouard
77: Summary: Adding a hack for testing purpose
78:
79: After reading the title, ftol and model lines, if the comment line has
80: a q, starting with #q, the answer at the end of the run is quit. It
81: permits to run test files in batch with ctest. The former workaround was
82: $ echo q | imach foo.imach
83:
84: Revision 1.194 2015/08/18 13:32:00 brouard
85: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
86:
87: Revision 1.193 2015/08/04 07:17:42 brouard
88: Summary: 0.98q4
89:
90: Revision 1.192 2015/07/16 16:49:02 brouard
91: Summary: Fixing some outputs
92:
93: Revision 1.191 2015/07/14 10:00:33 brouard
94: Summary: Some fixes
95:
96: Revision 1.190 2015/05/05 08:51:13 brouard
97: Summary: Adding digits in output parameters (7 digits instead of 6)
98:
99: Fix 1+age+.
100:
101: Revision 1.189 2015/04/30 14:45:16 brouard
102: Summary: 0.98q2
103:
104: Revision 1.188 2015/04/30 08:27:53 brouard
105: *** empty log message ***
106:
107: Revision 1.187 2015/04/29 09:11:15 brouard
108: *** empty log message ***
109:
110: Revision 1.186 2015/04/23 12:01:52 brouard
111: Summary: V1*age is working now, version 0.98q1
112:
113: Some codes had been disabled in order to simplify and Vn*age was
114: working in the optimization phase, ie, giving correct MLE parameters,
115: but, as usual, outputs were not correct and program core dumped.
116:
117: Revision 1.185 2015/03/11 13:26:42 brouard
118: Summary: Inclusion of compile and links command line for Intel Compiler
119:
120: Revision 1.184 2015/03/11 11:52:39 brouard
121: Summary: Back from Windows 8. Intel Compiler
122:
123: Revision 1.183 2015/03/10 20:34:32 brouard
124: Summary: 0.98q0, trying with directest, mnbrak fixed
125:
126: We use directest instead of original Powell test; probably no
127: incidence on the results, but better justifications;
128: We fixed Numerical Recipes mnbrak routine which was wrong and gave
129: wrong results.
130:
131: Revision 1.182 2015/02/12 08:19:57 brouard
132: Summary: Trying to keep directest which seems simpler and more general
133: Author: Nicolas Brouard
134:
135: Revision 1.181 2015/02/11 23:22:24 brouard
136: Summary: Comments on Powell added
137:
138: Author:
139:
140: Revision 1.180 2015/02/11 17:33:45 brouard
141: Summary: Finishing move from main to function (hpijx and prevalence_limit)
142:
143: Revision 1.179 2015/01/04 09:57:06 brouard
144: Summary: back to OS/X
145:
146: Revision 1.178 2015/01/04 09:35:48 brouard
147: *** empty log message ***
148:
149: Revision 1.177 2015/01/03 18:40:56 brouard
150: Summary: Still testing ilc32 on OSX
151:
152: Revision 1.176 2015/01/03 16:45:04 brouard
153: *** empty log message ***
154:
155: Revision 1.175 2015/01/03 16:33:42 brouard
156: *** empty log message ***
157:
158: Revision 1.174 2015/01/03 16:15:49 brouard
159: Summary: Still in cross-compilation
160:
161: Revision 1.173 2015/01/03 12:06:26 brouard
162: Summary: trying to detect cross-compilation
163:
164: Revision 1.172 2014/12/27 12:07:47 brouard
165: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
166:
167: Revision 1.171 2014/12/23 13:26:59 brouard
168: Summary: Back from Visual C
169:
170: Still problem with utsname.h on Windows
171:
172: Revision 1.170 2014/12/23 11:17:12 brouard
173: Summary: Cleaning some \%% back to %%
174:
175: The escape was mandatory for a specific compiler (which one?), but too many warnings.
176:
177: Revision 1.169 2014/12/22 23:08:31 brouard
178: Summary: 0.98p
179:
180: Outputs some informations on compiler used, OS etc. Testing on different platforms.
181:
182: Revision 1.168 2014/12/22 15:17:42 brouard
183: Summary: update
184:
185: Revision 1.167 2014/12/22 13:50:56 brouard
186: Summary: Testing uname and compiler version and if compiled 32 or 64
187:
188: Testing on Linux 64
189:
190: Revision 1.166 2014/12/22 11:40:47 brouard
191: *** empty log message ***
192:
193: Revision 1.165 2014/12/16 11:20:36 brouard
194: Summary: After compiling on Visual C
195:
196: * imach.c (Module): Merging 1.61 to 1.162
197:
198: Revision 1.164 2014/12/16 10:52:11 brouard
199: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
200:
201: * imach.c (Module): Merging 1.61 to 1.162
202:
203: Revision 1.163 2014/12/16 10:30:11 brouard
204: * imach.c (Module): Merging 1.61 to 1.162
205:
206: Revision 1.162 2014/09/25 11:43:39 brouard
207: Summary: temporary backup 0.99!
208:
209: Revision 1.1 2014/09/16 11:06:58 brouard
210: Summary: With some code (wrong) for nlopt
211:
212: Author:
213:
214: Revision 1.161 2014/09/15 20:41:41 brouard
215: Summary: Problem with macro SQR on Intel compiler
216:
217: Revision 1.160 2014/09/02 09:24:05 brouard
218: *** empty log message ***
219:
220: Revision 1.159 2014/09/01 10:34:10 brouard
221: Summary: WIN32
222: Author: Brouard
223:
224: Revision 1.158 2014/08/27 17:11:51 brouard
225: *** empty log message ***
226:
227: Revision 1.157 2014/08/27 16:26:55 brouard
228: Summary: Preparing windows Visual studio version
229: Author: Brouard
230:
231: In order to compile on Visual studio, time.h is now correct and time_t
232: and tm struct should be used. difftime should be used but sometimes I
233: just make the differences in raw time format (time(&now).
234: Trying to suppress #ifdef LINUX
235: Add xdg-open for __linux in order to open default browser.
236:
237: Revision 1.156 2014/08/25 20:10:10 brouard
238: *** empty log message ***
239:
240: Revision 1.155 2014/08/25 18:32:34 brouard
241: Summary: New compile, minor changes
242: Author: Brouard
243:
244: Revision 1.154 2014/06/20 17:32:08 brouard
245: Summary: Outputs now all graphs of convergence to period prevalence
246:
247: Revision 1.153 2014/06/20 16:45:46 brouard
248: Summary: If 3 live state, convergence to period prevalence on same graph
249: Author: Brouard
250:
251: Revision 1.152 2014/06/18 17:54:09 brouard
252: Summary: open browser, use gnuplot on same dir than imach if not found in the path
253:
254: Revision 1.151 2014/06/18 16:43:30 brouard
255: *** empty log message ***
256:
257: Revision 1.150 2014/06/18 16:42:35 brouard
258: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
259: Author: brouard
260:
261: Revision 1.149 2014/06/18 15:51:14 brouard
262: Summary: Some fixes in parameter files errors
263: Author: Nicolas Brouard
264:
265: Revision 1.148 2014/06/17 17:38:48 brouard
266: Summary: Nothing new
267: Author: Brouard
268:
269: Just a new packaging for OS/X version 0.98nS
270:
271: Revision 1.147 2014/06/16 10:33:11 brouard
272: *** empty log message ***
273:
274: Revision 1.146 2014/06/16 10:20:28 brouard
275: Summary: Merge
276: Author: Brouard
277:
278: Merge, before building revised version.
279:
280: Revision 1.145 2014/06/10 21:23:15 brouard
281: Summary: Debugging with valgrind
282: Author: Nicolas Brouard
283:
284: Lot of changes in order to output the results with some covariates
285: After the Edimburgh REVES conference 2014, it seems mandatory to
286: improve the code.
287: No more memory valgrind error but a lot has to be done in order to
288: continue the work of splitting the code into subroutines.
289: Also, decodemodel has been improved. Tricode is still not
290: optimal. nbcode should be improved. Documentation has been added in
291: the source code.
292:
293: Revision 1.143 2014/01/26 09:45:38 brouard
294: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
295:
296: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
297: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
298:
299: Revision 1.142 2014/01/26 03:57:36 brouard
300: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
301:
302: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
303:
304: Revision 1.141 2014/01/26 02:42:01 brouard
305: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
306:
307: Revision 1.140 2011/09/02 10:37:54 brouard
308: Summary: times.h is ok with mingw32 now.
309:
310: Revision 1.139 2010/06/14 07:50:17 brouard
311: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
312: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
313:
314: Revision 1.138 2010/04/30 18:19:40 brouard
315: *** empty log message ***
316:
317: Revision 1.137 2010/04/29 18:11:38 brouard
318: (Module): Checking covariates for more complex models
319: than V1+V2. A lot of change to be done. Unstable.
320:
321: Revision 1.136 2010/04/26 20:30:53 brouard
322: (Module): merging some libgsl code. Fixing computation
323: of likelione (using inter/intrapolation if mle = 0) in order to
324: get same likelihood as if mle=1.
325: Some cleaning of code and comments added.
326:
327: Revision 1.135 2009/10/29 15:33:14 brouard
328: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
329:
330: Revision 1.134 2009/10/29 13:18:53 brouard
331: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
332:
333: Revision 1.133 2009/07/06 10:21:25 brouard
334: just nforces
335:
336: Revision 1.132 2009/07/06 08:22:05 brouard
337: Many tings
338:
339: Revision 1.131 2009/06/20 16:22:47 brouard
340: Some dimensions resccaled
341:
342: Revision 1.130 2009/05/26 06:44:34 brouard
343: (Module): Max Covariate is now set to 20 instead of 8. A
344: lot of cleaning with variables initialized to 0. Trying to make
345: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
346:
347: Revision 1.129 2007/08/31 13:49:27 lievre
348: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
349:
350: Revision 1.128 2006/06/30 13:02:05 brouard
351: (Module): Clarifications on computing e.j
352:
353: Revision 1.127 2006/04/28 18:11:50 brouard
354: (Module): Yes the sum of survivors was wrong since
355: imach-114 because nhstepm was no more computed in the age
356: loop. Now we define nhstepma in the age loop.
357: (Module): In order to speed up (in case of numerous covariates) we
358: compute health expectancies (without variances) in a first step
359: and then all the health expectancies with variances or standard
360: deviation (needs data from the Hessian matrices) which slows the
361: computation.
362: In the future we should be able to stop the program is only health
363: expectancies and graph are needed without standard deviations.
364:
365: Revision 1.126 2006/04/28 17:23:28 brouard
366: (Module): Yes the sum of survivors was wrong since
367: imach-114 because nhstepm was no more computed in the age
368: loop. Now we define nhstepma in the age loop.
369: Version 0.98h
370:
371: Revision 1.125 2006/04/04 15:20:31 lievre
372: Errors in calculation of health expectancies. Age was not initialized.
373: Forecasting file added.
374:
375: Revision 1.124 2006/03/22 17:13:53 lievre
376: Parameters are printed with %lf instead of %f (more numbers after the comma).
377: The log-likelihood is printed in the log file
378:
379: Revision 1.123 2006/03/20 10:52:43 brouard
380: * imach.c (Module): <title> changed, corresponds to .htm file
381: name. <head> headers where missing.
382:
383: * imach.c (Module): Weights can have a decimal point as for
384: English (a comma might work with a correct LC_NUMERIC environment,
385: otherwise the weight is truncated).
386: Modification of warning when the covariates values are not 0 or
387: 1.
388: Version 0.98g
389:
390: Revision 1.122 2006/03/20 09:45:41 brouard
391: (Module): Weights can have a decimal point as for
392: English (a comma might work with a correct LC_NUMERIC environment,
393: otherwise the weight is truncated).
394: Modification of warning when the covariates values are not 0 or
395: 1.
396: Version 0.98g
397:
398: Revision 1.121 2006/03/16 17:45:01 lievre
399: * imach.c (Module): Comments concerning covariates added
400:
401: * imach.c (Module): refinements in the computation of lli if
402: status=-2 in order to have more reliable computation if stepm is
403: not 1 month. Version 0.98f
404:
405: Revision 1.120 2006/03/16 15:10:38 lievre
406: (Module): refinements in the computation of lli if
407: status=-2 in order to have more reliable computation if stepm is
408: not 1 month. Version 0.98f
409:
410: Revision 1.119 2006/03/15 17:42:26 brouard
411: (Module): Bug if status = -2, the loglikelihood was
412: computed as likelihood omitting the logarithm. Version O.98e
413:
414: Revision 1.118 2006/03/14 18:20:07 brouard
415: (Module): varevsij Comments added explaining the second
416: table of variances if popbased=1 .
417: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
418: (Module): Function pstamp added
419: (Module): Version 0.98d
420:
421: Revision 1.117 2006/03/14 17:16:22 brouard
422: (Module): varevsij Comments added explaining the second
423: table of variances if popbased=1 .
424: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
425: (Module): Function pstamp added
426: (Module): Version 0.98d
427:
428: Revision 1.116 2006/03/06 10:29:27 brouard
429: (Module): Variance-covariance wrong links and
430: varian-covariance of ej. is needed (Saito).
431:
432: Revision 1.115 2006/02/27 12:17:45 brouard
433: (Module): One freematrix added in mlikeli! 0.98c
434:
435: Revision 1.114 2006/02/26 12:57:58 brouard
436: (Module): Some improvements in processing parameter
437: filename with strsep.
438:
439: Revision 1.113 2006/02/24 14:20:24 brouard
440: (Module): Memory leaks checks with valgrind and:
441: datafile was not closed, some imatrix were not freed and on matrix
442: allocation too.
443:
444: Revision 1.112 2006/01/30 09:55:26 brouard
445: (Module): Back to gnuplot.exe instead of wgnuplot.exe
446:
447: Revision 1.111 2006/01/25 20:38:18 brouard
448: (Module): Lots of cleaning and bugs added (Gompertz)
449: (Module): Comments can be added in data file. Missing date values
450: can be a simple dot '.'.
451:
452: Revision 1.110 2006/01/25 00:51:50 brouard
453: (Module): Lots of cleaning and bugs added (Gompertz)
454:
455: Revision 1.109 2006/01/24 19:37:15 brouard
456: (Module): Comments (lines starting with a #) are allowed in data.
457:
458: Revision 1.108 2006/01/19 18:05:42 lievre
459: Gnuplot problem appeared...
460: To be fixed
461:
462: Revision 1.107 2006/01/19 16:20:37 brouard
463: Test existence of gnuplot in imach path
464:
465: Revision 1.106 2006/01/19 13:24:36 brouard
466: Some cleaning and links added in html output
467:
468: Revision 1.105 2006/01/05 20:23:19 lievre
469: *** empty log message ***
470:
471: Revision 1.104 2005/09/30 16:11:43 lievre
472: (Module): sump fixed, loop imx fixed, and simplifications.
473: (Module): If the status is missing at the last wave but we know
474: that the person is alive, then we can code his/her status as -2
475: (instead of missing=-1 in earlier versions) and his/her
476: contributions to the likelihood is 1 - Prob of dying from last
477: health status (= 1-p13= p11+p12 in the easiest case of somebody in
478: the healthy state at last known wave). Version is 0.98
479:
480: Revision 1.103 2005/09/30 15:54:49 lievre
481: (Module): sump fixed, loop imx fixed, and simplifications.
482:
483: Revision 1.102 2004/09/15 17:31:30 brouard
484: Add the possibility to read data file including tab characters.
485:
486: Revision 1.101 2004/09/15 10:38:38 brouard
487: Fix on curr_time
488:
489: Revision 1.100 2004/07/12 18:29:06 brouard
490: Add version for Mac OS X. Just define UNIX in Makefile
491:
492: Revision 1.99 2004/06/05 08:57:40 brouard
493: *** empty log message ***
494:
495: Revision 1.98 2004/05/16 15:05:56 brouard
496: New version 0.97 . First attempt to estimate force of mortality
497: directly from the data i.e. without the need of knowing the health
498: state at each age, but using a Gompertz model: log u =a + b*age .
499: This is the basic analysis of mortality and should be done before any
500: other analysis, in order to test if the mortality estimated from the
501: cross-longitudinal survey is different from the mortality estimated
502: from other sources like vital statistic data.
503:
504: The same imach parameter file can be used but the option for mle should be -3.
505:
506: Agnès, who wrote this part of the code, tried to keep most of the
507: former routines in order to include the new code within the former code.
508:
509: The output is very simple: only an estimate of the intercept and of
510: the slope with 95% confident intervals.
511:
512: Current limitations:
513: A) Even if you enter covariates, i.e. with the
514: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
515: B) There is no computation of Life Expectancy nor Life Table.
516:
517: Revision 1.97 2004/02/20 13:25:42 lievre
518: Version 0.96d. Population forecasting command line is (temporarily)
519: suppressed.
520:
521: Revision 1.96 2003/07/15 15:38:55 brouard
522: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
523: rewritten within the same printf. Workaround: many printfs.
524:
525: Revision 1.95 2003/07/08 07:54:34 brouard
526: * imach.c (Repository):
527: (Repository): Using imachwizard code to output a more meaningful covariance
528: matrix (cov(a12,c31) instead of numbers.
529:
530: Revision 1.94 2003/06/27 13:00:02 brouard
531: Just cleaning
532:
533: Revision 1.93 2003/06/25 16:33:55 brouard
534: (Module): On windows (cygwin) function asctime_r doesn't
535: exist so I changed back to asctime which exists.
536: (Module): Version 0.96b
537:
538: Revision 1.92 2003/06/25 16:30:45 brouard
539: (Module): On windows (cygwin) function asctime_r doesn't
540: exist so I changed back to asctime which exists.
541:
542: Revision 1.91 2003/06/25 15:30:29 brouard
543: * imach.c (Repository): Duplicated warning errors corrected.
544: (Repository): Elapsed time after each iteration is now output. It
545: helps to forecast when convergence will be reached. Elapsed time
546: is stamped in powell. We created a new html file for the graphs
547: concerning matrix of covariance. It has extension -cov.htm.
548:
549: Revision 1.90 2003/06/24 12:34:15 brouard
550: (Module): Some bugs corrected for windows. Also, when
551: mle=-1 a template is output in file "or"mypar.txt with the design
552: of the covariance matrix to be input.
553:
554: Revision 1.89 2003/06/24 12:30:52 brouard
555: (Module): Some bugs corrected for windows. Also, when
556: mle=-1 a template is output in file "or"mypar.txt with the design
557: of the covariance matrix to be input.
558:
559: Revision 1.88 2003/06/23 17:54:56 brouard
560: * 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.
561:
562: Revision 1.87 2003/06/18 12:26:01 brouard
563: Version 0.96
564:
565: Revision 1.86 2003/06/17 20:04:08 brouard
566: (Module): Change position of html and gnuplot routines and added
567: routine fileappend.
568:
569: Revision 1.85 2003/06/17 13:12:43 brouard
570: * imach.c (Repository): Check when date of death was earlier that
571: current date of interview. It may happen when the death was just
572: prior to the death. In this case, dh was negative and likelihood
573: was wrong (infinity). We still send an "Error" but patch by
574: assuming that the date of death was just one stepm after the
575: interview.
576: (Repository): Because some people have very long ID (first column)
577: we changed int to long in num[] and we added a new lvector for
578: memory allocation. But we also truncated to 8 characters (left
579: truncation)
580: (Repository): No more line truncation errors.
581:
582: Revision 1.84 2003/06/13 21:44:43 brouard
583: * imach.c (Repository): Replace "freqsummary" at a correct
584: place. It differs from routine "prevalence" which may be called
585: many times. Probs is memory consuming and must be used with
586: parcimony.
587: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
588:
589: Revision 1.83 2003/06/10 13:39:11 lievre
590: *** empty log message ***
591:
592: Revision 1.82 2003/06/05 15:57:20 brouard
593: Add log in imach.c and fullversion number is now printed.
594:
595: */
596: /*
597: Interpolated Markov Chain
598:
599: Short summary of the programme:
600:
601: This program computes Healthy Life Expectancies from
602: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
603: first survey ("cross") where individuals from different ages are
604: interviewed on their health status or degree of disability (in the
605: case of a health survey which is our main interest) -2- at least a
606: second wave of interviews ("longitudinal") which measure each change
607: (if any) in individual health status. Health expectancies are
608: computed from the time spent in each health state according to a
609: model. More health states you consider, more time is necessary to reach the
610: Maximum Likelihood of the parameters involved in the model. The
611: simplest model is the multinomial logistic model where pij is the
612: probability to be observed in state j at the second wave
613: conditional to be observed in state i at the first wave. Therefore
614: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
615: 'age' is age and 'sex' is a covariate. If you want to have a more
616: complex model than "constant and age", you should modify the program
617: where the markup *Covariates have to be included here again* invites
618: you to do it. More covariates you add, slower the
619: convergence.
620:
621: The advantage of this computer programme, compared to a simple
622: multinomial logistic model, is clear when the delay between waves is not
623: identical for each individual. Also, if a individual missed an
624: intermediate interview, the information is lost, but taken into
625: account using an interpolation or extrapolation.
626:
627: hPijx is the probability to be observed in state i at age x+h
628: conditional to the observed state i at age x. The delay 'h' can be
629: split into an exact number (nh*stepm) of unobserved intermediate
630: states. This elementary transition (by month, quarter,
631: semester or year) is modelled as a multinomial logistic. The hPx
632: matrix is simply the matrix product of nh*stepm elementary matrices
633: and the contribution of each individual to the likelihood is simply
634: hPijx.
635:
636: Also this programme outputs the covariance matrix of the parameters but also
637: of the life expectancies. It also computes the period (stable) prevalence.
638:
639: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
640: Institut national d'études démographiques, Paris.
641: This software have been partly granted by Euro-REVES, a concerted action
642: from the European Union.
643: It is copyrighted identically to a GNU software product, ie programme and
644: software can be distributed freely for non commercial use. Latest version
645: can be accessed at http://euroreves.ined.fr/imach .
646:
647: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
648: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
649:
650: **********************************************************************/
651: /*
652: main
653: read parameterfile
654: read datafile
655: concatwav
656: freqsummary
657: if (mle >= 1)
658: mlikeli
659: print results files
660: if mle==1
661: computes hessian
662: read end of parameter file: agemin, agemax, bage, fage, estepm
663: begin-prev-date,...
664: open gnuplot file
665: open html file
666: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
667: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
668: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
669: freexexit2 possible for memory heap.
670:
671: h Pij x | pij_nom ficrestpij
672: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
673: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
674: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
675:
676: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
677: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
678: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
679: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
680: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
681:
682: forecasting if prevfcast==1 prevforecast call prevalence()
683: health expectancies
684: Variance-covariance of DFLE
685: prevalence()
686: movingaverage()
687: varevsij()
688: if popbased==1 varevsij(,popbased)
689: total life expectancies
690: Variance of period (stable) prevalence
691: end
692: */
693:
694: /* #define DEBUG */
695: /* #define DEBUGBRENT */
696: /* #define DEBUGLINMIN */
697: /* #define DEBUGHESS */
698: #define DEBUGHESSIJ
699: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
700: #define POWELL /* Instead of NLOPT */
701: #define POWELLF1F3 /* Skip test */
702: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
703: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
704:
705: #include <math.h>
706: #include <stdio.h>
707: #include <stdlib.h>
708: #include <string.h>
709:
710: #ifdef _WIN32
711: #include <io.h>
712: #include <windows.h>
713: #include <tchar.h>
714: #else
715: #include <unistd.h>
716: #endif
717:
718: #include <limits.h>
719: #include <sys/types.h>
720:
721: #if defined(__GNUC__)
722: #include <sys/utsname.h> /* Doesn't work on Windows */
723: #endif
724:
725: #include <sys/stat.h>
726: #include <errno.h>
727: /* extern int errno; */
728:
729: /* #ifdef LINUX */
730: /* #include <time.h> */
731: /* #include "timeval.h" */
732: /* #else */
733: /* #include <sys/time.h> */
734: /* #endif */
735:
736: #include <time.h>
737:
738: #ifdef GSL
739: #include <gsl/gsl_errno.h>
740: #include <gsl/gsl_multimin.h>
741: #endif
742:
743:
744: #ifdef NLOPT
745: #include <nlopt.h>
746: typedef struct {
747: double (* function)(double [] );
748: } myfunc_data ;
749: #endif
750:
751: /* #include <libintl.h> */
752: /* #define _(String) gettext (String) */
753:
754: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
755:
756: #define GNUPLOTPROGRAM "gnuplot"
757: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
758: #define FILENAMELENGTH 132
759:
760: #define GLOCK_ERROR_NOPATH -1 /* empty path */
761: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
762:
763: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
764: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
765:
766: #define NINTERVMAX 8
767: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
768: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
769: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
770: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
771: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
772: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
773: #define MAXN 20000
774: #define YEARM 12. /**< Number of months per year */
775: #define AGESUP 130
776: #define AGEBASE 40
777: #define AGEOVERFLOW 1.e20
778: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
779: #ifdef _WIN32
780: #define DIRSEPARATOR '\\'
781: #define CHARSEPARATOR "\\"
782: #define ODIRSEPARATOR '/'
783: #else
784: #define DIRSEPARATOR '/'
785: #define CHARSEPARATOR "/"
786: #define ODIRSEPARATOR '\\'
787: #endif
788:
789: /* $Id: imach.c,v 1.213 2015/12/11 18:22:17 brouard Exp $ */
790: /* $State: Exp $ */
791: #include "version.h"
792: char version[]=__IMACH_VERSION__;
793: 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";
794: char fullversion[]="$Revision: 1.213 $ $Date: 2015/12/11 18:22:17 $";
795: char strstart[80];
796: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
797: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
798: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
799: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
800: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
801: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
802: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
803: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
804: int cptcovprodnoage=0; /**< Number of covariate products without age */
805: int cptcoveff=0; /* Total number of covariates to vary for printing results */
806: int cptcov=0; /* Working variable */
807: int npar=NPARMAX;
808: int nlstate=2; /* Number of live states */
809: int ndeath=1; /* Number of dead states */
810: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
811: int popbased=0;
812:
813: int *wav; /* Number of waves for this individuual 0 is possible */
814: int maxwav=0; /* Maxim number of waves */
815: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
816: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
817: int gipmx=0, gsw=0; /* Global variables on the number of contributions
818: to the likelihood and the sum of weights (done by funcone)*/
819: int mle=1, weightopt=0;
820: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
821: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
822: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
823: * wave mi and wave mi+1 is not an exact multiple of stepm. */
824: int countcallfunc=0; /* Count the number of calls to func */
825: double jmean=1; /* Mean space between 2 waves */
826: double **matprod2(); /* test */
827: double **oldm, **newm, **savm; /* Working pointers to matrices */
828: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
829: /*FILE *fic ; */ /* Used in readdata only */
830: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
831: FILE *ficlog, *ficrespow;
832: int globpr=0; /* Global variable for printing or not */
833: double fretone; /* Only one call to likelihood */
834: long ipmx=0; /* Number of contributions */
835: double sw; /* Sum of weights */
836: char filerespow[FILENAMELENGTH];
837: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
838: FILE *ficresilk;
839: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
840: FILE *ficresprobmorprev;
841: FILE *fichtm, *fichtmcov; /* Html File */
842: FILE *ficreseij;
843: char filerese[FILENAMELENGTH];
844: FILE *ficresstdeij;
845: char fileresstde[FILENAMELENGTH];
846: FILE *ficrescveij;
847: char filerescve[FILENAMELENGTH];
848: FILE *ficresvij;
849: char fileresv[FILENAMELENGTH];
850: FILE *ficresvpl;
851: char fileresvpl[FILENAMELENGTH];
852: char title[MAXLINE];
853: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
854: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
855: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
856: char command[FILENAMELENGTH];
857: int outcmd=0;
858:
859: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
860: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
861: char filelog[FILENAMELENGTH]; /* Log file */
862: char filerest[FILENAMELENGTH];
863: char fileregp[FILENAMELENGTH];
864: char popfile[FILENAMELENGTH];
865:
866: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
867:
868: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
869: /* struct timezone tzp; */
870: /* extern int gettimeofday(); */
871: struct tm tml, *gmtime(), *localtime();
872:
873: extern time_t time();
874:
875: struct tm start_time, end_time, curr_time, last_time, forecast_time;
876: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
877: struct tm tm;
878:
879: char strcurr[80], strfor[80];
880:
881: char *endptr;
882: long lval;
883: double dval;
884:
885: #define NR_END 1
886: #define FREE_ARG char*
887: #define FTOL 1.0e-10
888:
889: #define NRANSI
890: #define ITMAX 200
891:
892: #define TOL 2.0e-4
893:
894: #define CGOLD 0.3819660
895: #define ZEPS 1.0e-10
896: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
897:
898: #define GOLD 1.618034
899: #define GLIMIT 100.0
900: #define TINY 1.0e-20
901:
902: static double maxarg1,maxarg2;
903: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
904: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
905:
906: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
907: #define rint(a) floor(a+0.5)
908: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
909: #define mytinydouble 1.0e-16
910: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
911: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
912: /* static double dsqrarg; */
913: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
914: static double sqrarg;
915: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
916: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
917: int agegomp= AGEGOMP;
918:
919: int imx;
920: int stepm=1;
921: /* Stepm, step in month: minimum step interpolation*/
922:
923: int estepm;
924: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
925:
926: int m,nb;
927: long *num;
928: int firstpass=0, lastpass=4,*cod, *cens;
929: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
930: covariate for which somebody answered excluding
931: undefined. Usually 2: 0 and 1. */
932: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
933: covariate for which somebody answered including
934: undefined. Usually 3: -1, 0 and 1. */
935: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
936: double **pmmij, ***probs;
937: double *ageexmed,*agecens;
938: double dateintmean=0;
939:
940: double *weight;
941: int **s; /* Status */
942: double *agedc;
943: double **covar; /**< covar[j,i], value of jth covariate for individual i,
944: * covar=matrix(0,NCOVMAX,1,n);
945: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
946: double idx;
947: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
948: int *Tage;
949: int *Ndum; /** Freq of modality (tricode */
950: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
951: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
952: double *lsurv, *lpop, *tpop;
953:
954: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
955: double ftolhess; /**< Tolerance for computing hessian */
956:
957: /**************** split *************************/
958: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
959: {
960: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
961: the name of the file (name), its extension only (ext) and its first part of the name (finame)
962: */
963: char *ss; /* pointer */
964: int l1=0, l2=0; /* length counters */
965:
966: l1 = strlen(path ); /* length of path */
967: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
968: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
969: if ( ss == NULL ) { /* no directory, so determine current directory */
970: strcpy( name, path ); /* we got the fullname name because no directory */
971: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
972: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
973: /* get current working directory */
974: /* extern char* getcwd ( char *buf , int len);*/
975: #ifdef WIN32
976: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
977: #else
978: if (getcwd(dirc, FILENAME_MAX) == NULL) {
979: #endif
980: return( GLOCK_ERROR_GETCWD );
981: }
982: /* got dirc from getcwd*/
983: printf(" DIRC = %s \n",dirc);
984: } else { /* strip directory from path */
985: ss++; /* after this, the filename */
986: l2 = strlen( ss ); /* length of filename */
987: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
988: strcpy( name, ss ); /* save file name */
989: strncpy( dirc, path, l1 - l2 ); /* now the directory */
990: dirc[l1-l2] = '\0'; /* add zero */
991: printf(" DIRC2 = %s \n",dirc);
992: }
993: /* We add a separator at the end of dirc if not exists */
994: l1 = strlen( dirc ); /* length of directory */
995: if( dirc[l1-1] != DIRSEPARATOR ){
996: dirc[l1] = DIRSEPARATOR;
997: dirc[l1+1] = 0;
998: printf(" DIRC3 = %s \n",dirc);
999: }
1000: ss = strrchr( name, '.' ); /* find last / */
1001: if (ss >0){
1002: ss++;
1003: strcpy(ext,ss); /* save extension */
1004: l1= strlen( name);
1005: l2= strlen(ss)+1;
1006: strncpy( finame, name, l1-l2);
1007: finame[l1-l2]= 0;
1008: }
1009:
1010: return( 0 ); /* we're done */
1011: }
1012:
1013:
1014: /******************************************/
1015:
1016: void replace_back_to_slash(char *s, char*t)
1017: {
1018: int i;
1019: int lg=0;
1020: i=0;
1021: lg=strlen(t);
1022: for(i=0; i<= lg; i++) {
1023: (s[i] = t[i]);
1024: if (t[i]== '\\') s[i]='/';
1025: }
1026: }
1027:
1028: char *trimbb(char *out, char *in)
1029: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1030: char *s;
1031: s=out;
1032: while (*in != '\0'){
1033: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1034: in++;
1035: }
1036: *out++ = *in++;
1037: }
1038: *out='\0';
1039: return s;
1040: }
1041:
1042: /* char *substrchaine(char *out, char *in, char *chain) */
1043: /* { */
1044: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1045: /* char *s, *t; */
1046: /* t=in;s=out; */
1047: /* while ((*in != *chain) && (*in != '\0')){ */
1048: /* *out++ = *in++; */
1049: /* } */
1050:
1051: /* /\* *in matches *chain *\/ */
1052: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1053: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1054: /* } */
1055: /* in--; chain--; */
1056: /* while ( (*in != '\0')){ */
1057: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1058: /* *out++ = *in++; */
1059: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1060: /* } */
1061: /* *out='\0'; */
1062: /* out=s; */
1063: /* return out; */
1064: /* } */
1065: char *substrchaine(char *out, char *in, char *chain)
1066: {
1067: /* Substract chain 'chain' from 'in', return and output 'out' */
1068: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1069:
1070: char *strloc;
1071:
1072: strcpy (out, in);
1073: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1074: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1075: if(strloc != NULL){
1076: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1077: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1078: /* strcpy (strloc, strloc +strlen(chain));*/
1079: }
1080: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1081: return out;
1082: }
1083:
1084:
1085: char *cutl(char *blocc, char *alocc, char *in, char occ)
1086: {
1087: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1088: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1089: gives blocc="abcdef" and alocc="ghi2j".
1090: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1091: */
1092: char *s, *t;
1093: t=in;s=in;
1094: while ((*in != occ) && (*in != '\0')){
1095: *alocc++ = *in++;
1096: }
1097: if( *in == occ){
1098: *(alocc)='\0';
1099: s=++in;
1100: }
1101:
1102: if (s == t) {/* occ not found */
1103: *(alocc-(in-s))='\0';
1104: in=s;
1105: }
1106: while ( *in != '\0'){
1107: *blocc++ = *in++;
1108: }
1109:
1110: *blocc='\0';
1111: return t;
1112: }
1113: char *cutv(char *blocc, char *alocc, char *in, char occ)
1114: {
1115: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1116: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1117: gives blocc="abcdef2ghi" and alocc="j".
1118: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1119: */
1120: char *s, *t;
1121: t=in;s=in;
1122: while (*in != '\0'){
1123: while( *in == occ){
1124: *blocc++ = *in++;
1125: s=in;
1126: }
1127: *blocc++ = *in++;
1128: }
1129: if (s == t) /* occ not found */
1130: *(blocc-(in-s))='\0';
1131: else
1132: *(blocc-(in-s)-1)='\0';
1133: in=s;
1134: while ( *in != '\0'){
1135: *alocc++ = *in++;
1136: }
1137:
1138: *alocc='\0';
1139: return s;
1140: }
1141:
1142: int nbocc(char *s, char occ)
1143: {
1144: int i,j=0;
1145: int lg=20;
1146: i=0;
1147: lg=strlen(s);
1148: for(i=0; i<= lg; i++) {
1149: if (s[i] == occ ) j++;
1150: }
1151: return j;
1152: }
1153:
1154: /* void cutv(char *u,char *v, char*t, char occ) */
1155: /* { */
1156: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1157: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1158: /* gives u="abcdef2ghi" and v="j" *\/ */
1159: /* int i,lg,j,p=0; */
1160: /* i=0; */
1161: /* lg=strlen(t); */
1162: /* for(j=0; j<=lg-1; j++) { */
1163: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1164: /* } */
1165:
1166: /* for(j=0; j<p; j++) { */
1167: /* (u[j] = t[j]); */
1168: /* } */
1169: /* u[p]='\0'; */
1170:
1171: /* for(j=0; j<= lg; j++) { */
1172: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1173: /* } */
1174: /* } */
1175:
1176: #ifdef _WIN32
1177: char * strsep(char **pp, const char *delim)
1178: {
1179: char *p, *q;
1180:
1181: if ((p = *pp) == NULL)
1182: return 0;
1183: if ((q = strpbrk (p, delim)) != NULL)
1184: {
1185: *pp = q + 1;
1186: *q = '\0';
1187: }
1188: else
1189: *pp = 0;
1190: return p;
1191: }
1192: #endif
1193:
1194: /********************** nrerror ********************/
1195:
1196: void nrerror(char error_text[])
1197: {
1198: fprintf(stderr,"ERREUR ...\n");
1199: fprintf(stderr,"%s\n",error_text);
1200: exit(EXIT_FAILURE);
1201: }
1202: /*********************** vector *******************/
1203: double *vector(int nl, int nh)
1204: {
1205: double *v;
1206: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1207: if (!v) nrerror("allocation failure in vector");
1208: return v-nl+NR_END;
1209: }
1210:
1211: /************************ free vector ******************/
1212: void free_vector(double*v, int nl, int nh)
1213: {
1214: free((FREE_ARG)(v+nl-NR_END));
1215: }
1216:
1217: /************************ivector *******************************/
1218: int *ivector(long nl,long nh)
1219: {
1220: int *v;
1221: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1222: if (!v) nrerror("allocation failure in ivector");
1223: return v-nl+NR_END;
1224: }
1225:
1226: /******************free ivector **************************/
1227: void free_ivector(int *v, long nl, long nh)
1228: {
1229: free((FREE_ARG)(v+nl-NR_END));
1230: }
1231:
1232: /************************lvector *******************************/
1233: long *lvector(long nl,long nh)
1234: {
1235: long *v;
1236: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1237: if (!v) nrerror("allocation failure in ivector");
1238: return v-nl+NR_END;
1239: }
1240:
1241: /******************free lvector **************************/
1242: void free_lvector(long *v, long nl, long nh)
1243: {
1244: free((FREE_ARG)(v+nl-NR_END));
1245: }
1246:
1247: /******************* imatrix *******************************/
1248: int **imatrix(long nrl, long nrh, long ncl, long nch)
1249: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1250: {
1251: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1252: int **m;
1253:
1254: /* allocate pointers to rows */
1255: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1256: if (!m) nrerror("allocation failure 1 in matrix()");
1257: m += NR_END;
1258: m -= nrl;
1259:
1260:
1261: /* allocate rows and set pointers to them */
1262: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1263: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1264: m[nrl] += NR_END;
1265: m[nrl] -= ncl;
1266:
1267: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1268:
1269: /* return pointer to array of pointers to rows */
1270: return m;
1271: }
1272:
1273: /****************** free_imatrix *************************/
1274: void free_imatrix(m,nrl,nrh,ncl,nch)
1275: int **m;
1276: long nch,ncl,nrh,nrl;
1277: /* free an int matrix allocated by imatrix() */
1278: {
1279: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1280: free((FREE_ARG) (m+nrl-NR_END));
1281: }
1282:
1283: /******************* matrix *******************************/
1284: double **matrix(long nrl, long nrh, long ncl, long nch)
1285: {
1286: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1287: double **m;
1288:
1289: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1290: if (!m) nrerror("allocation failure 1 in matrix()");
1291: m += NR_END;
1292: m -= nrl;
1293:
1294: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1295: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1296: m[nrl] += NR_END;
1297: m[nrl] -= ncl;
1298:
1299: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1300: return m;
1301: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1302: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1303: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1304: */
1305: }
1306:
1307: /*************************free matrix ************************/
1308: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1309: {
1310: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1311: free((FREE_ARG)(m+nrl-NR_END));
1312: }
1313:
1314: /******************* ma3x *******************************/
1315: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1316: {
1317: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1318: double ***m;
1319:
1320: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1321: if (!m) nrerror("allocation failure 1 in matrix()");
1322: m += NR_END;
1323: m -= nrl;
1324:
1325: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1326: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1327: m[nrl] += NR_END;
1328: m[nrl] -= ncl;
1329:
1330: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1331:
1332: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1333: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1334: m[nrl][ncl] += NR_END;
1335: m[nrl][ncl] -= nll;
1336: for (j=ncl+1; j<=nch; j++)
1337: m[nrl][j]=m[nrl][j-1]+nlay;
1338:
1339: for (i=nrl+1; i<=nrh; i++) {
1340: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1341: for (j=ncl+1; j<=nch; j++)
1342: m[i][j]=m[i][j-1]+nlay;
1343: }
1344: return m;
1345: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1346: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1347: */
1348: }
1349:
1350: /*************************free ma3x ************************/
1351: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1352: {
1353: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1354: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1355: free((FREE_ARG)(m+nrl-NR_END));
1356: }
1357:
1358: /*************** function subdirf ***********/
1359: char *subdirf(char fileres[])
1360: {
1361: /* Caution optionfilefiname is hidden */
1362: strcpy(tmpout,optionfilefiname);
1363: strcat(tmpout,"/"); /* Add to the right */
1364: strcat(tmpout,fileres);
1365: return tmpout;
1366: }
1367:
1368: /*************** function subdirf2 ***********/
1369: char *subdirf2(char fileres[], char *preop)
1370: {
1371:
1372: /* Caution optionfilefiname is hidden */
1373: strcpy(tmpout,optionfilefiname);
1374: strcat(tmpout,"/");
1375: strcat(tmpout,preop);
1376: strcat(tmpout,fileres);
1377: return tmpout;
1378: }
1379:
1380: /*************** function subdirf3 ***********/
1381: char *subdirf3(char fileres[], char *preop, char *preop2)
1382: {
1383:
1384: /* Caution optionfilefiname is hidden */
1385: strcpy(tmpout,optionfilefiname);
1386: strcat(tmpout,"/");
1387: strcat(tmpout,preop);
1388: strcat(tmpout,preop2);
1389: strcat(tmpout,fileres);
1390: return tmpout;
1391: }
1392:
1393: /*************** function subdirfext ***********/
1394: char *subdirfext(char fileres[], char *preop, char *postop)
1395: {
1396:
1397: strcpy(tmpout,preop);
1398: strcat(tmpout,fileres);
1399: strcat(tmpout,postop);
1400: return tmpout;
1401: }
1402:
1403: /*************** function subdirfext3 ***********/
1404: char *subdirfext3(char fileres[], char *preop, char *postop)
1405: {
1406:
1407: /* Caution optionfilefiname is hidden */
1408: strcpy(tmpout,optionfilefiname);
1409: strcat(tmpout,"/");
1410: strcat(tmpout,preop);
1411: strcat(tmpout,fileres);
1412: strcat(tmpout,postop);
1413: return tmpout;
1414: }
1415:
1416: char *asc_diff_time(long time_sec, char ascdiff[])
1417: {
1418: long sec_left, days, hours, minutes;
1419: days = (time_sec) / (60*60*24);
1420: sec_left = (time_sec) % (60*60*24);
1421: hours = (sec_left) / (60*60) ;
1422: sec_left = (sec_left) %(60*60);
1423: minutes = (sec_left) /60;
1424: sec_left = (sec_left) % (60);
1425: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1426: return ascdiff;
1427: }
1428:
1429: /***************** f1dim *************************/
1430: extern int ncom;
1431: extern double *pcom,*xicom;
1432: extern double (*nrfunc)(double []);
1433:
1434: double f1dim(double x)
1435: {
1436: int j;
1437: double f;
1438: double *xt;
1439:
1440: xt=vector(1,ncom);
1441: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1442: f=(*nrfunc)(xt);
1443: free_vector(xt,1,ncom);
1444: return f;
1445: }
1446:
1447: /*****************brent *************************/
1448: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1449: {
1450: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1451: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1452: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1453: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1454: * returned function value.
1455: */
1456: int iter;
1457: double a,b,d,etemp;
1458: double fu=0,fv,fw,fx;
1459: double ftemp=0.;
1460: double p,q,r,tol1,tol2,u,v,w,x,xm;
1461: double e=0.0;
1462:
1463: a=(ax < cx ? ax : cx);
1464: b=(ax > cx ? ax : cx);
1465: x=w=v=bx;
1466: fw=fv=fx=(*f)(x);
1467: for (iter=1;iter<=ITMAX;iter++) {
1468: xm=0.5*(a+b);
1469: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1470: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1471: printf(".");fflush(stdout);
1472: fprintf(ficlog,".");fflush(ficlog);
1473: #ifdef DEBUGBRENT
1474: 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);
1475: 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);
1476: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1477: #endif
1478: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1479: *xmin=x;
1480: return fx;
1481: }
1482: ftemp=fu;
1483: if (fabs(e) > tol1) {
1484: r=(x-w)*(fx-fv);
1485: q=(x-v)*(fx-fw);
1486: p=(x-v)*q-(x-w)*r;
1487: q=2.0*(q-r);
1488: if (q > 0.0) p = -p;
1489: q=fabs(q);
1490: etemp=e;
1491: e=d;
1492: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1493: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1494: else {
1495: d=p/q;
1496: u=x+d;
1497: if (u-a < tol2 || b-u < tol2)
1498: d=SIGN(tol1,xm-x);
1499: }
1500: } else {
1501: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1502: }
1503: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1504: fu=(*f)(u);
1505: if (fu <= fx) {
1506: if (u >= x) a=x; else b=x;
1507: SHFT(v,w,x,u)
1508: SHFT(fv,fw,fx,fu)
1509: } else {
1510: if (u < x) a=u; else b=u;
1511: if (fu <= fw || w == x) {
1512: v=w;
1513: w=u;
1514: fv=fw;
1515: fw=fu;
1516: } else if (fu <= fv || v == x || v == w) {
1517: v=u;
1518: fv=fu;
1519: }
1520: }
1521: }
1522: nrerror("Too many iterations in brent");
1523: *xmin=x;
1524: return fx;
1525: }
1526:
1527: /****************** mnbrak ***********************/
1528:
1529: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1530: double (*func)(double))
1531: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1532: the downhill direction (defined by the function as evaluated at the initial points) and returns
1533: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1534: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1535: */
1536: double ulim,u,r,q, dum;
1537: double fu;
1538:
1539: double scale=10.;
1540: int iterscale=0;
1541:
1542: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1543: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1544:
1545:
1546: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1547: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1548: /* *bx = *ax - (*ax - *bx)/scale; */
1549: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1550: /* } */
1551:
1552: if (*fb > *fa) {
1553: SHFT(dum,*ax,*bx,dum)
1554: SHFT(dum,*fb,*fa,dum)
1555: }
1556: *cx=(*bx)+GOLD*(*bx-*ax);
1557: *fc=(*func)(*cx);
1558: #ifdef DEBUG
1559: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1560: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1561: #endif
1562: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1563: r=(*bx-*ax)*(*fb-*fc);
1564: q=(*bx-*cx)*(*fb-*fa);
1565: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1566: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1567: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1568: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1569: fu=(*func)(u);
1570: #ifdef DEBUG
1571: /* f(x)=A(x-u)**2+f(u) */
1572: double A, fparabu;
1573: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1574: fparabu= *fa - A*(*ax-u)*(*ax-u);
1575: 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);
1576: 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);
1577: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1578: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1579: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1580: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1581: #endif
1582: #ifdef MNBRAKORIGINAL
1583: #else
1584: /* if (fu > *fc) { */
1585: /* #ifdef DEBUG */
1586: /* printf("mnbrak4 fu > fc \n"); */
1587: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1588: /* #endif */
1589: /* /\* 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 *\\/ *\/ */
1590: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1591: /* dum=u; /\* Shifting c and u *\/ */
1592: /* u = *cx; */
1593: /* *cx = dum; */
1594: /* dum = fu; */
1595: /* fu = *fc; */
1596: /* *fc =dum; */
1597: /* } else { /\* end *\/ */
1598: /* #ifdef DEBUG */
1599: /* printf("mnbrak3 fu < fc \n"); */
1600: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1601: /* #endif */
1602: /* dum=u; /\* Shifting c and u *\/ */
1603: /* u = *cx; */
1604: /* *cx = dum; */
1605: /* dum = fu; */
1606: /* fu = *fc; */
1607: /* *fc =dum; */
1608: /* } */
1609: #ifdef DEBUG
1610: printf("mnbrak34 fu < or >= fc \n");
1611: fprintf(ficlog, "mnbrak34 fu < fc\n");
1612: #endif
1613: dum=u; /* Shifting c and u */
1614: u = *cx;
1615: *cx = dum;
1616: dum = fu;
1617: fu = *fc;
1618: *fc =dum;
1619: #endif
1620: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1621: #ifdef DEBUG
1622: printf("mnbrak2 u after c but before ulim\n");
1623: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1624: #endif
1625: fu=(*func)(u);
1626: if (fu < *fc) {
1627: #ifdef DEBUG
1628: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1629: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1630: #endif
1631: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1632: SHFT(*fb,*fc,fu,(*func)(u))
1633: }
1634: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1635: #ifdef DEBUG
1636: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1637: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1638: #endif
1639: u=ulim;
1640: fu=(*func)(u);
1641: } else { /* u could be left to b (if r > q parabola has a maximum) */
1642: #ifdef DEBUG
1643: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1644: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1645: #endif
1646: u=(*cx)+GOLD*(*cx-*bx);
1647: fu=(*func)(u);
1648: } /* end tests */
1649: SHFT(*ax,*bx,*cx,u)
1650: SHFT(*fa,*fb,*fc,fu)
1651: #ifdef DEBUG
1652: 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);
1653: 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);
1654: #endif
1655: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1656: }
1657:
1658: /*************** linmin ************************/
1659: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1660: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1661: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1662: the value of func at the returned location p . This is actually all accomplished by calling the
1663: routines mnbrak and brent .*/
1664: int ncom;
1665: double *pcom,*xicom;
1666: double (*nrfunc)(double []);
1667:
1668: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1669: {
1670: double brent(double ax, double bx, double cx,
1671: double (*f)(double), double tol, double *xmin);
1672: double f1dim(double x);
1673: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1674: double *fc, double (*func)(double));
1675: int j;
1676: double xx,xmin,bx,ax;
1677: double fx,fb,fa;
1678:
1679: #ifdef LINMINORIGINAL
1680: #else
1681: double scale=10., axs, xxs; /* Scale added for infinity */
1682: #endif
1683:
1684: ncom=n;
1685: pcom=vector(1,n);
1686: xicom=vector(1,n);
1687: nrfunc=func;
1688: for (j=1;j<=n;j++) {
1689: pcom[j]=p[j];
1690: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1691: }
1692:
1693: #ifdef LINMINORIGINAL
1694: xx=1.;
1695: #else
1696: axs=0.0;
1697: xxs=1.;
1698: do{
1699: xx= xxs;
1700: #endif
1701: ax=0.;
1702: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1703: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1704: /* 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)) */
1705: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1706: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1707: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1708: /* 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]]*/
1709: #ifdef LINMINORIGINAL
1710: #else
1711: if (fx != fx){
1712: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1713: printf("|");
1714: fprintf(ficlog,"|");
1715: #ifdef DEBUGLINMIN
1716: 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);
1717: #endif
1718: }
1719: }while(fx != fx);
1720: #endif
1721:
1722: #ifdef DEBUGLINMIN
1723: 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);
1724: 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);
1725: #endif
1726: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1727: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1728: /* fmin = f(p[j] + xmin * xi[j]) */
1729: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1730: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1731: #ifdef DEBUG
1732: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1733: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1734: #endif
1735: #ifdef DEBUGLINMIN
1736: printf("linmin end ");
1737: fprintf(ficlog,"linmin end ");
1738: #endif
1739: for (j=1;j<=n;j++) {
1740: #ifdef LINMINORIGINAL
1741: xi[j] *= xmin;
1742: #else
1743: #ifdef DEBUGLINMIN
1744: if(xxs <1.0)
1745: printf(" before xi[%d]=%12.8f", j,xi[j]);
1746: #endif
1747: 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) */
1748: #ifdef DEBUGLINMIN
1749: if(xxs <1.0)
1750: 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 );
1751: #endif
1752: #endif
1753: p[j] += xi[j]; /* Parameters values are updated accordingly */
1754: }
1755: #ifdef DEBUGLINMIN
1756: printf("\n");
1757: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1758: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1759: for (j=1;j<=n;j++) {
1760: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1761: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1762: if(j % ncovmodel == 0){
1763: printf("\n");
1764: fprintf(ficlog,"\n");
1765: }
1766: }
1767: #else
1768: #endif
1769: free_vector(xicom,1,n);
1770: free_vector(pcom,1,n);
1771: }
1772:
1773:
1774: /*************** powell ************************/
1775: /*
1776: Minimization of a function func of n variables. Input consists of an initial starting point
1777: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1778: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1779: such that failure to decrease by more than this amount on one iteration signals doneness. On
1780: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1781: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1782: */
1783: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1784: double (*func)(double []))
1785: {
1786: void linmin(double p[], double xi[], int n, double *fret,
1787: double (*func)(double []));
1788: int i,ibig,j;
1789: double del,t,*pt,*ptt,*xit;
1790: double directest;
1791: double fp,fptt;
1792: double *xits;
1793: int niterf, itmp;
1794:
1795: pt=vector(1,n);
1796: ptt=vector(1,n);
1797: xit=vector(1,n);
1798: xits=vector(1,n);
1799: *fret=(*func)(p);
1800: for (j=1;j<=n;j++) pt[j]=p[j];
1801: rcurr_time = time(NULL);
1802: for (*iter=1;;++(*iter)) {
1803: fp=(*fret); /* From former iteration or initial value */
1804: ibig=0;
1805: del=0.0;
1806: rlast_time=rcurr_time;
1807: /* (void) gettimeofday(&curr_time,&tzp); */
1808: rcurr_time = time(NULL);
1809: curr_time = *localtime(&rcurr_time);
1810: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1811: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1812: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1813: for (i=1;i<=n;i++) {
1814: printf(" %d %.12f",i, p[i]);
1815: fprintf(ficlog," %d %.12lf",i, p[i]);
1816: fprintf(ficrespow," %.12lf", p[i]);
1817: }
1818: printf("\n");
1819: fprintf(ficlog,"\n");
1820: fprintf(ficrespow,"\n");fflush(ficrespow);
1821: if(*iter <=3){
1822: tml = *localtime(&rcurr_time);
1823: strcpy(strcurr,asctime(&tml));
1824: rforecast_time=rcurr_time;
1825: itmp = strlen(strcurr);
1826: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1827: strcurr[itmp-1]='\0';
1828: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1829: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1830: for(niterf=10;niterf<=30;niterf+=10){
1831: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1832: forecast_time = *localtime(&rforecast_time);
1833: strcpy(strfor,asctime(&forecast_time));
1834: itmp = strlen(strfor);
1835: if(strfor[itmp-1]=='\n')
1836: strfor[itmp-1]='\0';
1837: 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);
1838: 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);
1839: }
1840: }
1841: for (i=1;i<=n;i++) { /* For each direction i */
1842: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1843: fptt=(*fret);
1844: #ifdef DEBUG
1845: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1846: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1847: #endif
1848: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1849: fprintf(ficlog,"%d",i);fflush(ficlog);
1850: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1851: /* Outputs are fret(new point p) p is updated and xit rescaled */
1852: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1853: /* because that direction will be replaced unless the gain del is small */
1854: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1855: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1856: /* with the new direction. */
1857: del=fabs(fptt-(*fret));
1858: ibig=i;
1859: }
1860: #ifdef DEBUG
1861: printf("%d %.12e",i,(*fret));
1862: fprintf(ficlog,"%d %.12e",i,(*fret));
1863: for (j=1;j<=n;j++) {
1864: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1865: printf(" x(%d)=%.12e",j,xit[j]);
1866: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1867: }
1868: for(j=1;j<=n;j++) {
1869: printf(" p(%d)=%.12e",j,p[j]);
1870: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1871: }
1872: printf("\n");
1873: fprintf(ficlog,"\n");
1874: #endif
1875: } /* end loop on each direction i */
1876: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1877: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1878: /* New value of last point Pn is not computed, P(n-1) */
1879: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1880: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1881: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1882: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1883: /* decreased of more than 3.84 */
1884: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1885: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1886: /* By adding 10 parameters more the gain should be 18.31 */
1887:
1888: /* Starting the program with initial values given by a former maximization will simply change */
1889: /* the scales of the directions and the directions, because the are reset to canonical directions */
1890: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1891: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1892: #ifdef DEBUG
1893: int k[2],l;
1894: k[0]=1;
1895: k[1]=-1;
1896: printf("Max: %.12e",(*func)(p));
1897: fprintf(ficlog,"Max: %.12e",(*func)(p));
1898: for (j=1;j<=n;j++) {
1899: printf(" %.12e",p[j]);
1900: fprintf(ficlog," %.12e",p[j]);
1901: }
1902: printf("\n");
1903: fprintf(ficlog,"\n");
1904: for(l=0;l<=1;l++) {
1905: for (j=1;j<=n;j++) {
1906: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1907: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1908: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1909: }
1910: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1911: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1912: }
1913: #endif
1914:
1915:
1916: free_vector(xit,1,n);
1917: free_vector(xits,1,n);
1918: free_vector(ptt,1,n);
1919: free_vector(pt,1,n);
1920: return;
1921: } /* enough precision */
1922: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1923: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1924: ptt[j]=2.0*p[j]-pt[j];
1925: xit[j]=p[j]-pt[j];
1926: pt[j]=p[j];
1927: }
1928: fptt=(*func)(ptt); /* f_3 */
1929: #ifdef POWELLF1F3
1930: #else
1931: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1932: #endif
1933: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1934: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1935: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1936: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1937: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1938: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1939: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1940: #ifdef NRCORIGINAL
1941: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1942: #else
1943: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1944: t= t- del*SQR(fp-fptt);
1945: #endif
1946: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1947: #ifdef DEBUG
1948: 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);
1949: 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);
1950: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1951: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1952: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1953: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1954: 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);
1955: 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);
1956: #endif
1957: #ifdef POWELLORIGINAL
1958: if (t < 0.0) { /* Then we use it for new direction */
1959: #else
1960: if (directest*t < 0.0) { /* Contradiction between both tests */
1961: 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);
1962: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1963: 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);
1964: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1965: }
1966: if (directest < 0.0) { /* Then we use it for new direction */
1967: #endif
1968: #ifdef DEBUGLINMIN
1969: printf("Before linmin in direction P%d-P0\n",n);
1970: for (j=1;j<=n;j++) {
1971: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1972: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1973: if(j % ncovmodel == 0){
1974: printf("\n");
1975: fprintf(ficlog,"\n");
1976: }
1977: }
1978: #endif
1979: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1980: #ifdef DEBUGLINMIN
1981: for (j=1;j<=n;j++) {
1982: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1983: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1984: if(j % ncovmodel == 0){
1985: printf("\n");
1986: fprintf(ficlog,"\n");
1987: }
1988: }
1989: #endif
1990: for (j=1;j<=n;j++) {
1991: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1992: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1993: }
1994: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1995: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1996:
1997: #ifdef DEBUG
1998: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1999: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2000: for(j=1;j<=n;j++){
2001: printf(" %.12e",xit[j]);
2002: fprintf(ficlog," %.12e",xit[j]);
2003: }
2004: printf("\n");
2005: fprintf(ficlog,"\n");
2006: #endif
2007: } /* end of t or directest negative */
2008: #ifdef POWELLF1F3
2009: #else
2010: } /* end if (fptt < fp) */
2011: #endif
2012: } /* loop iteration */
2013: }
2014:
2015: /**** Prevalence limit (stable or period prevalence) ****************/
2016:
2017: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
2018: {
2019: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
2020: matrix by transitions matrix until convergence is reached with precision ftolpl */
2021: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2022: /* Wx is row vector: population in state 1, population in state 2, population dead */
2023: /* or prevalence in state 1, prevalence in state 2, 0 */
2024: /* newm is the matrix after multiplications, its rows are identical at a factor */
2025: /* Initial matrix pimij */
2026: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2027: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2028: /* 0, 0 , 1} */
2029: /*
2030: * and after some iteration: */
2031: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2032: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2033: /* 0, 0 , 1} */
2034: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2035: /* {0.51571254859325999, 0.4842874514067399, */
2036: /* 0.51326036147820708, 0.48673963852179264} */
2037: /* If we start from prlim again, prlim tends to a constant matrix */
2038:
2039: int i, ii,j,k;
2040: double *min, *max, *meandiff, maxmax,sumnew=0.;
2041: /* double **matprod2(); */ /* test */
2042: double **out, cov[NCOVMAX+1], **pmij();
2043: double **newm;
2044: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2045: int ncvloop=0;
2046:
2047: min=vector(1,nlstate);
2048: max=vector(1,nlstate);
2049: meandiff=vector(1,nlstate);
2050:
2051: for (ii=1;ii<=nlstate+ndeath;ii++)
2052: for (j=1;j<=nlstate+ndeath;j++){
2053: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2054: }
2055:
2056: cov[1]=1.;
2057:
2058: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2059: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2060: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2061: ncvloop++;
2062: newm=savm;
2063: /* Covariates have to be included here again */
2064: cov[2]=agefin;
2065: if(nagesqr==1)
2066: cov[3]= agefin*agefin;;
2067: for (k=1; k<=cptcovn;k++) {
2068: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2069: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2070: /* 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])]); */
2071: }
2072: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2073: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2074: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2075: for (k=1; k<=cptcovprod;k++) /* Useless */
2076: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2077: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2078:
2079: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2080: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2081: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2082: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2083: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2084: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2085:
2086: savm=oldm;
2087: oldm=newm;
2088:
2089: for(j=1; j<=nlstate; j++){
2090: max[j]=0.;
2091: min[j]=1.;
2092: }
2093: for(i=1;i<=nlstate;i++){
2094: sumnew=0;
2095: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2096: for(j=1; j<=nlstate; j++){
2097: prlim[i][j]= newm[i][j]/(1-sumnew);
2098: max[j]=FMAX(max[j],prlim[i][j]);
2099: min[j]=FMIN(min[j],prlim[i][j]);
2100: }
2101: }
2102:
2103: maxmax=0.;
2104: for(j=1; j<=nlstate; j++){
2105: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2106: maxmax=FMAX(maxmax,meandiff[j]);
2107: /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
2108: } /* j loop */
2109: *ncvyear= (int)age- (int)agefin;
2110: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2111: if(maxmax < ftolpl){
2112: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2113: free_vector(min,1,nlstate);
2114: free_vector(max,1,nlstate);
2115: free_vector(meandiff,1,nlstate);
2116: return prlim;
2117: }
2118: } /* age loop */
2119: /* After some age loop it doesn't converge */
2120: printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
2121: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
2122: /* 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); */
2123: free_vector(min,1,nlstate);
2124: free_vector(max,1,nlstate);
2125: free_vector(meandiff,1,nlstate);
2126:
2127: return prlim; /* should not reach here */
2128: }
2129:
2130: /*************** transition probabilities ***************/
2131:
2132: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2133: {
2134: /* According to parameters values stored in x and the covariate's values stored in cov,
2135: computes the probability to be observed in state j being in state i by appying the
2136: model to the ncovmodel covariates (including constant and age).
2137: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2138: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2139: ncth covariate in the global vector x is given by the formula:
2140: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2141: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2142: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2143: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2144: Outputs ps[i][j] the probability to be observed in j being in j according to
2145: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2146: */
2147: double s1, lnpijopii;
2148: /*double t34;*/
2149: int i,j, nc, ii, jj;
2150:
2151: for(i=1; i<= nlstate; i++){
2152: for(j=1; j<i;j++){
2153: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2154: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2155: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2156: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2157: }
2158: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2159: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2160: }
2161: for(j=i+1; j<=nlstate+ndeath;j++){
2162: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2163: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2164: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2165: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2166: }
2167: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2168: }
2169: }
2170:
2171: for(i=1; i<= nlstate; i++){
2172: s1=0;
2173: for(j=1; j<i; j++){
2174: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2175: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2176: }
2177: for(j=i+1; j<=nlstate+ndeath; j++){
2178: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2179: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2180: }
2181: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2182: ps[i][i]=1./(s1+1.);
2183: /* Computing other pijs */
2184: for(j=1; j<i; j++)
2185: ps[i][j]= exp(ps[i][j])*ps[i][i];
2186: for(j=i+1; j<=nlstate+ndeath; j++)
2187: ps[i][j]= exp(ps[i][j])*ps[i][i];
2188: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2189: } /* end i */
2190:
2191: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2192: for(jj=1; jj<= nlstate+ndeath; jj++){
2193: ps[ii][jj]=0;
2194: ps[ii][ii]=1;
2195: }
2196: }
2197:
2198:
2199: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2200: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2201: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2202: /* } */
2203: /* printf("\n "); */
2204: /* } */
2205: /* printf("\n ");printf("%lf ",cov[2]);*/
2206: /*
2207: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2208: goto end;*/
2209: return ps;
2210: }
2211:
2212: /**************** Product of 2 matrices ******************/
2213:
2214: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2215: {
2216: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2217: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2218: /* in, b, out are matrice of pointers which should have been initialized
2219: before: only the contents of out is modified. The function returns
2220: a pointer to pointers identical to out */
2221: int i, j, k;
2222: for(i=nrl; i<= nrh; i++)
2223: for(k=ncolol; k<=ncoloh; k++){
2224: out[i][k]=0.;
2225: for(j=ncl; j<=nch; j++)
2226: out[i][k] +=in[i][j]*b[j][k];
2227: }
2228: return out;
2229: }
2230:
2231:
2232: /************* Higher Matrix Product ***************/
2233:
2234: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2235: {
2236: /* Computes the transition matrix starting at age 'age' over
2237: 'nhstepm*hstepm*stepm' months (i.e. until
2238: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2239: nhstepm*hstepm matrices.
2240: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2241: (typically every 2 years instead of every month which is too big
2242: for the memory).
2243: Model is determined by parameters x and covariates have to be
2244: included manually here.
2245:
2246: */
2247:
2248: int i, j, d, h, k;
2249: double **out, cov[NCOVMAX+1];
2250: double **newm;
2251: double agexact;
2252:
2253: /* Hstepm could be zero and should return the unit matrix */
2254: for (i=1;i<=nlstate+ndeath;i++)
2255: for (j=1;j<=nlstate+ndeath;j++){
2256: oldm[i][j]=(i==j ? 1.0 : 0.0);
2257: po[i][j][0]=(i==j ? 1.0 : 0.0);
2258: }
2259: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2260: for(h=1; h <=nhstepm; h++){
2261: for(d=1; d <=hstepm; d++){
2262: newm=savm;
2263: /* Covariates have to be included here again */
2264: cov[1]=1.;
2265: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2266: cov[2]=agexact;
2267: if(nagesqr==1)
2268: cov[3]= agexact*agexact;
2269: for (k=1; k<=cptcovn;k++)
2270: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2271: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2272: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2273: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2274: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2275: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2276: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2277: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2278: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2279:
2280:
2281: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2282: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2283: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2284: pmij(pmmij,cov,ncovmodel,x,nlstate));
2285: savm=oldm;
2286: oldm=newm;
2287: }
2288: for(i=1; i<=nlstate+ndeath; i++)
2289: for(j=1;j<=nlstate+ndeath;j++) {
2290: po[i][j][h]=newm[i][j];
2291: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2292: }
2293: /*printf("h=%d ",h);*/
2294: } /* end h */
2295: /* printf("\n H=%d \n",h); */
2296: return po;
2297: }
2298:
2299: #ifdef NLOPT
2300: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2301: double fret;
2302: double *xt;
2303: int j;
2304: myfunc_data *d2 = (myfunc_data *) pd;
2305: /* xt = (p1-1); */
2306: xt=vector(1,n);
2307: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2308:
2309: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2310: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2311: printf("Function = %.12lf ",fret);
2312: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2313: printf("\n");
2314: free_vector(xt,1,n);
2315: return fret;
2316: }
2317: #endif
2318:
2319: /*************** log-likelihood *************/
2320: double func( double *x)
2321: {
2322: int i, ii, j, k, mi, d, kk;
2323: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2324: double **out;
2325: double sw; /* Sum of weights */
2326: double lli; /* Individual log likelihood */
2327: int s1, s2;
2328: double bbh, survp;
2329: long ipmx;
2330: double agexact;
2331: /*extern weight */
2332: /* We are differentiating ll according to initial status */
2333: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2334: /*for(i=1;i<imx;i++)
2335: printf(" %d\n",s[4][i]);
2336: */
2337:
2338: ++countcallfunc;
2339:
2340: cov[1]=1.;
2341:
2342: for(k=1; k<=nlstate; k++) ll[k]=0.;
2343:
2344: if(mle==1){
2345: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2346: /* Computes the values of the ncovmodel covariates of the model
2347: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2348: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2349: to be observed in j being in i according to the model.
2350: */
2351: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2352: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2353: }
2354: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2355: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2356: has been calculated etc */
2357: for(mi=1; mi<= wav[i]-1; mi++){
2358: for (ii=1;ii<=nlstate+ndeath;ii++)
2359: for (j=1;j<=nlstate+ndeath;j++){
2360: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2361: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2362: }
2363: for(d=0; d<dh[mi][i]; d++){
2364: newm=savm;
2365: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2366: cov[2]=agexact;
2367: if(nagesqr==1)
2368: cov[3]= agexact*agexact;
2369: for (kk=1; kk<=cptcovage;kk++) {
2370: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2371: }
2372: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2373: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2374: savm=oldm;
2375: oldm=newm;
2376: } /* end mult */
2377:
2378: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2379: /* But now since version 0.9 we anticipate for bias at large stepm.
2380: * If stepm is larger than one month (smallest stepm) and if the exact delay
2381: * (in months) between two waves is not a multiple of stepm, we rounded to
2382: * the nearest (and in case of equal distance, to the lowest) interval but now
2383: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2384: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2385: * probability in order to take into account the bias as a fraction of the way
2386: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2387: * -stepm/2 to stepm/2 .
2388: * For stepm=1 the results are the same as for previous versions of Imach.
2389: * For stepm > 1 the results are less biased than in previous versions.
2390: */
2391: s1=s[mw[mi][i]][i];
2392: s2=s[mw[mi+1][i]][i];
2393: bbh=(double)bh[mi][i]/(double)stepm;
2394: /* bias bh is positive if real duration
2395: * is higher than the multiple of stepm and negative otherwise.
2396: */
2397: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2398: if( s2 > nlstate){
2399: /* i.e. if s2 is a death state and if the date of death is known
2400: then the contribution to the likelihood is the probability to
2401: die between last step unit time and current step unit time,
2402: which is also equal to probability to die before dh
2403: minus probability to die before dh-stepm .
2404: In version up to 0.92 likelihood was computed
2405: as if date of death was unknown. Death was treated as any other
2406: health state: the date of the interview describes the actual state
2407: and not the date of a change in health state. The former idea was
2408: to consider that at each interview the state was recorded
2409: (healthy, disable or death) and IMaCh was corrected; but when we
2410: introduced the exact date of death then we should have modified
2411: the contribution of an exact death to the likelihood. This new
2412: contribution is smaller and very dependent of the step unit
2413: stepm. It is no more the probability to die between last interview
2414: and month of death but the probability to survive from last
2415: interview up to one month before death multiplied by the
2416: probability to die within a month. Thanks to Chris
2417: Jackson for correcting this bug. Former versions increased
2418: mortality artificially. The bad side is that we add another loop
2419: which slows down the processing. The difference can be up to 10%
2420: lower mortality.
2421: */
2422: /* If, at the beginning of the maximization mostly, the
2423: cumulative probability or probability to be dead is
2424: constant (ie = 1) over time d, the difference is equal to
2425: 0. out[s1][3] = savm[s1][3]: probability, being at state
2426: s1 at precedent wave, to be dead a month before current
2427: wave is equal to probability, being at state s1 at
2428: precedent wave, to be dead at mont of the current
2429: wave. Then the observed probability (that this person died)
2430: is null according to current estimated parameter. In fact,
2431: it should be very low but not zero otherwise the log go to
2432: infinity.
2433: */
2434: /* #ifdef INFINITYORIGINAL */
2435: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2436: /* #else */
2437: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2438: /* lli=log(mytinydouble); */
2439: /* else */
2440: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2441: /* #endif */
2442: lli=log(out[s1][s2] - savm[s1][s2]);
2443:
2444: } else if (s2==-2) {
2445: for (j=1,survp=0. ; j<=nlstate; j++)
2446: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2447: /*survp += out[s1][j]; */
2448: lli= log(survp);
2449: }
2450:
2451: else if (s2==-4) {
2452: for (j=3,survp=0. ; j<=nlstate; j++)
2453: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2454: lli= log(survp);
2455: }
2456:
2457: else if (s2==-5) {
2458: for (j=1,survp=0. ; j<=2; j++)
2459: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2460: lli= log(survp);
2461: }
2462:
2463: else{
2464: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2465: /* 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 */
2466: }
2467: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2468: /*if(lli ==000.0)*/
2469: /*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); */
2470: ipmx +=1;
2471: sw += weight[i];
2472: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2473: /* if (lli < log(mytinydouble)){ */
2474: /* 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); */
2475: /* 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]); */
2476: /* } */
2477: } /* end of wave */
2478: } /* end of individual */
2479: } else if(mle==2){
2480: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2481: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2482: for(mi=1; mi<= wav[i]-1; mi++){
2483: for (ii=1;ii<=nlstate+ndeath;ii++)
2484: for (j=1;j<=nlstate+ndeath;j++){
2485: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2486: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2487: }
2488: for(d=0; d<=dh[mi][i]; d++){
2489: newm=savm;
2490: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2491: cov[2]=agexact;
2492: if(nagesqr==1)
2493: cov[3]= agexact*agexact;
2494: for (kk=1; kk<=cptcovage;kk++) {
2495: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2496: }
2497: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2498: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2499: savm=oldm;
2500: oldm=newm;
2501: } /* end mult */
2502:
2503: s1=s[mw[mi][i]][i];
2504: s2=s[mw[mi+1][i]][i];
2505: bbh=(double)bh[mi][i]/(double)stepm;
2506: 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 */
2507: ipmx +=1;
2508: sw += weight[i];
2509: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2510: } /* end of wave */
2511: } /* end of individual */
2512: } else if(mle==3){ /* exponential inter-extrapolation */
2513: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2514: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2515: for(mi=1; mi<= wav[i]-1; mi++){
2516: for (ii=1;ii<=nlstate+ndeath;ii++)
2517: for (j=1;j<=nlstate+ndeath;j++){
2518: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2519: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2520: }
2521: for(d=0; d<dh[mi][i]; d++){
2522: newm=savm;
2523: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2524: cov[2]=agexact;
2525: if(nagesqr==1)
2526: cov[3]= agexact*agexact;
2527: for (kk=1; kk<=cptcovage;kk++) {
2528: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2529: }
2530: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2531: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2532: savm=oldm;
2533: oldm=newm;
2534: } /* end mult */
2535:
2536: s1=s[mw[mi][i]][i];
2537: s2=s[mw[mi+1][i]][i];
2538: bbh=(double)bh[mi][i]/(double)stepm;
2539: 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 */
2540: ipmx +=1;
2541: sw += weight[i];
2542: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2543: } /* end of wave */
2544: } /* end of individual */
2545: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2546: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2547: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2548: for(mi=1; mi<= wav[i]-1; mi++){
2549: for (ii=1;ii<=nlstate+ndeath;ii++)
2550: for (j=1;j<=nlstate+ndeath;j++){
2551: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2552: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2553: }
2554: for(d=0; d<dh[mi][i]; d++){
2555: newm=savm;
2556: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2557: cov[2]=agexact;
2558: if(nagesqr==1)
2559: cov[3]= agexact*agexact;
2560: for (kk=1; kk<=cptcovage;kk++) {
2561: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2562: }
2563:
2564: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2565: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2566: savm=oldm;
2567: oldm=newm;
2568: } /* end mult */
2569:
2570: s1=s[mw[mi][i]][i];
2571: s2=s[mw[mi+1][i]][i];
2572: if( s2 > nlstate){
2573: lli=log(out[s1][s2] - savm[s1][s2]);
2574: }else{
2575: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2576: }
2577: ipmx +=1;
2578: sw += weight[i];
2579: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2580: /* 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]); */
2581: } /* end of wave */
2582: } /* end of individual */
2583: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2584: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2585: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2586: for(mi=1; mi<= wav[i]-1; mi++){
2587: for (ii=1;ii<=nlstate+ndeath;ii++)
2588: for (j=1;j<=nlstate+ndeath;j++){
2589: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2590: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2591: }
2592: for(d=0; d<dh[mi][i]; d++){
2593: newm=savm;
2594: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2595: cov[2]=agexact;
2596: if(nagesqr==1)
2597: cov[3]= agexact*agexact;
2598: for (kk=1; kk<=cptcovage;kk++) {
2599: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2600: }
2601:
2602: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2603: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2604: savm=oldm;
2605: oldm=newm;
2606: } /* end mult */
2607:
2608: s1=s[mw[mi][i]][i];
2609: s2=s[mw[mi+1][i]][i];
2610: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2611: ipmx +=1;
2612: sw += weight[i];
2613: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2614: /*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]);*/
2615: } /* end of wave */
2616: } /* end of individual */
2617: } /* End of if */
2618: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2619: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2620: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2621: return -l;
2622: }
2623:
2624: /*************** log-likelihood *************/
2625: double funcone( double *x)
2626: {
2627: /* Same as likeli but slower because of a lot of printf and if */
2628: int i, ii, j, k, mi, d, kk;
2629: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2630: double **out;
2631: double lli; /* Individual log likelihood */
2632: double llt;
2633: int s1, s2;
2634: double bbh, survp;
2635: double agexact;
2636: /*extern weight */
2637: /* We are differentiating ll according to initial status */
2638: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2639: /*for(i=1;i<imx;i++)
2640: printf(" %d\n",s[4][i]);
2641: */
2642: cov[1]=1.;
2643:
2644: for(k=1; k<=nlstate; k++) ll[k]=0.;
2645:
2646: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2647: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2648: for(mi=1; mi<= wav[i]-1; mi++){
2649: for (ii=1;ii<=nlstate+ndeath;ii++)
2650: for (j=1;j<=nlstate+ndeath;j++){
2651: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2652: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2653: }
2654: for(d=0; d<dh[mi][i]; d++){
2655: newm=savm;
2656: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2657: cov[2]=agexact;
2658: if(nagesqr==1)
2659: cov[3]= agexact*agexact;
2660: for (kk=1; kk<=cptcovage;kk++) {
2661: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2662: }
2663:
2664: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2665: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2666: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2667: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2668: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2669: savm=oldm;
2670: oldm=newm;
2671: } /* end mult */
2672:
2673: s1=s[mw[mi][i]][i];
2674: s2=s[mw[mi+1][i]][i];
2675: bbh=(double)bh[mi][i]/(double)stepm;
2676: /* bias is positive if real duration
2677: * is higher than the multiple of stepm and negative otherwise.
2678: */
2679: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2680: lli=log(out[s1][s2] - savm[s1][s2]);
2681: } else if (s2==-2) {
2682: for (j=1,survp=0. ; j<=nlstate; j++)
2683: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2684: lli= log(survp);
2685: }else if (mle==1){
2686: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2687: } else if(mle==2){
2688: 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 */
2689: } else if(mle==3){ /* exponential inter-extrapolation */
2690: 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 */
2691: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2692: lli=log(out[s1][s2]); /* Original formula */
2693: } else{ /* mle=0 back to 1 */
2694: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2695: /*lli=log(out[s1][s2]); */ /* Original formula */
2696: } /* End of if */
2697: ipmx +=1;
2698: sw += weight[i];
2699: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2700: /*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]); */
2701: if(globpr){
2702: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2703: %11.6f %11.6f %11.6f ", \
2704: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2705: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2706: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2707: llt +=ll[k]*gipmx/gsw;
2708: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2709: }
2710: fprintf(ficresilk," %10.6f\n", -llt);
2711: }
2712: } /* end of wave */
2713: } /* end of individual */
2714: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2715: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2716: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2717: if(globpr==0){ /* First time we count the contributions and weights */
2718: gipmx=ipmx;
2719: gsw=sw;
2720: }
2721: return -l;
2722: }
2723:
2724:
2725: /*************** function likelione ***********/
2726: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2727: {
2728: /* This routine should help understanding what is done with
2729: the selection of individuals/waves and
2730: to check the exact contribution to the likelihood.
2731: Plotting could be done.
2732: */
2733: int k;
2734:
2735: if(*globpri !=0){ /* Just counts and sums, no printings */
2736: strcpy(fileresilk,"ILK_");
2737: strcat(fileresilk,fileresu);
2738: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2739: printf("Problem with resultfile: %s\n", fileresilk);
2740: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2741: }
2742: 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");
2743: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
2744: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2745: for(k=1; k<=nlstate; k++)
2746: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2747: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2748: }
2749:
2750: *fretone=(*funcone)(p);
2751: if(*globpri !=0){
2752: fclose(ficresilk);
2753: if (mle ==0)
2754: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2755: else if(mle >=1)
2756: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2757: 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));
2758:
2759:
2760: for (k=1; k<= nlstate ; k++) {
2761: fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
2762: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2763: }
2764: 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> \
2765: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2766: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2767: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2768: fflush(fichtm);
2769: }
2770: return;
2771: }
2772:
2773:
2774: /*********** Maximum Likelihood Estimation ***************/
2775:
2776: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2777: {
2778: int i,j, iter=0;
2779: double **xi;
2780: double fret;
2781: double fretone; /* Only one call to likelihood */
2782: /* char filerespow[FILENAMELENGTH];*/
2783:
2784: #ifdef NLOPT
2785: int creturn;
2786: nlopt_opt opt;
2787: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2788: double *lb;
2789: double minf; /* the minimum objective value, upon return */
2790: double * p1; /* Shifted parameters from 0 instead of 1 */
2791: myfunc_data dinst, *d = &dinst;
2792: #endif
2793:
2794:
2795: xi=matrix(1,npar,1,npar);
2796: for (i=1;i<=npar;i++)
2797: for (j=1;j<=npar;j++)
2798: xi[i][j]=(i==j ? 1.0 : 0.0);
2799: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2800: strcpy(filerespow,"POW_");
2801: strcat(filerespow,fileres);
2802: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2803: printf("Problem with resultfile: %s\n", filerespow);
2804: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2805: }
2806: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2807: for (i=1;i<=nlstate;i++)
2808: for(j=1;j<=nlstate+ndeath;j++)
2809: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2810: fprintf(ficrespow,"\n");
2811: #ifdef POWELL
2812: powell(p,xi,npar,ftol,&iter,&fret,func);
2813: #endif
2814:
2815: #ifdef NLOPT
2816: #ifdef NEWUOA
2817: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2818: #else
2819: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2820: #endif
2821: lb=vector(0,npar-1);
2822: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2823: nlopt_set_lower_bounds(opt, lb);
2824: nlopt_set_initial_step1(opt, 0.1);
2825:
2826: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2827: d->function = func;
2828: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2829: nlopt_set_min_objective(opt, myfunc, d);
2830: nlopt_set_xtol_rel(opt, ftol);
2831: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2832: printf("nlopt failed! %d\n",creturn);
2833: }
2834: else {
2835: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2836: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2837: iter=1; /* not equal */
2838: }
2839: nlopt_destroy(opt);
2840: #endif
2841: free_matrix(xi,1,npar,1,npar);
2842: fclose(ficrespow);
2843: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2844: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2845: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2846:
2847: }
2848:
2849: /**** Computes Hessian and covariance matrix ***/
2850: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2851: {
2852: double **a,**y,*x,pd;
2853: /* double **hess; */
2854: int i, j;
2855: int *indx;
2856:
2857: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2858: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2859: void lubksb(double **a, int npar, int *indx, double b[]) ;
2860: void ludcmp(double **a, int npar, int *indx, double *d) ;
2861: double gompertz(double p[]);
2862: /* hess=matrix(1,npar,1,npar); */
2863:
2864: printf("\nCalculation of the hessian matrix. Wait...\n");
2865: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2866: for (i=1;i<=npar;i++){
2867: printf("%d-",i);fflush(stdout);
2868: fprintf(ficlog,"%d-",i);fflush(ficlog);
2869:
2870: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2871:
2872: /* printf(" %f ",p[i]);
2873: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2874: }
2875:
2876: for (i=1;i<=npar;i++) {
2877: for (j=1;j<=npar;j++) {
2878: if (j>i) {
2879: printf(".%d-%d",i,j);fflush(stdout);
2880: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2881: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2882:
2883: hess[j][i]=hess[i][j];
2884: /*printf(" %lf ",hess[i][j]);*/
2885: }
2886: }
2887: }
2888: printf("\n");
2889: fprintf(ficlog,"\n");
2890:
2891: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2892: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2893:
2894: a=matrix(1,npar,1,npar);
2895: y=matrix(1,npar,1,npar);
2896: x=vector(1,npar);
2897: indx=ivector(1,npar);
2898: for (i=1;i<=npar;i++)
2899: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2900: ludcmp(a,npar,indx,&pd);
2901:
2902: for (j=1;j<=npar;j++) {
2903: for (i=1;i<=npar;i++) x[i]=0;
2904: x[j]=1;
2905: lubksb(a,npar,indx,x);
2906: for (i=1;i<=npar;i++){
2907: matcov[i][j]=x[i];
2908: }
2909: }
2910:
2911: printf("\n#Hessian matrix#\n");
2912: fprintf(ficlog,"\n#Hessian matrix#\n");
2913: for (i=1;i<=npar;i++) {
2914: for (j=1;j<=npar;j++) {
2915: printf("%.6e ",hess[i][j]);
2916: fprintf(ficlog,"%.6e ",hess[i][j]);
2917: }
2918: printf("\n");
2919: fprintf(ficlog,"\n");
2920: }
2921:
2922: /* printf("\n#Covariance matrix#\n"); */
2923: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2924: /* for (i=1;i<=npar;i++) { */
2925: /* for (j=1;j<=npar;j++) { */
2926: /* printf("%.6e ",matcov[i][j]); */
2927: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2928: /* } */
2929: /* printf("\n"); */
2930: /* fprintf(ficlog,"\n"); */
2931: /* } */
2932:
2933: /* Recompute Inverse */
2934: /* for (i=1;i<=npar;i++) */
2935: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2936: /* ludcmp(a,npar,indx,&pd); */
2937:
2938: /* printf("\n#Hessian matrix recomputed#\n"); */
2939:
2940: /* for (j=1;j<=npar;j++) { */
2941: /* for (i=1;i<=npar;i++) x[i]=0; */
2942: /* x[j]=1; */
2943: /* lubksb(a,npar,indx,x); */
2944: /* for (i=1;i<=npar;i++){ */
2945: /* y[i][j]=x[i]; */
2946: /* printf("%.3e ",y[i][j]); */
2947: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2948: /* } */
2949: /* printf("\n"); */
2950: /* fprintf(ficlog,"\n"); */
2951: /* } */
2952:
2953: /* Verifying the inverse matrix */
2954: #ifdef DEBUGHESS
2955: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2956:
2957: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2958: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2959:
2960: for (j=1;j<=npar;j++) {
2961: for (i=1;i<=npar;i++){
2962: printf("%.2f ",y[i][j]);
2963: fprintf(ficlog,"%.2f ",y[i][j]);
2964: }
2965: printf("\n");
2966: fprintf(ficlog,"\n");
2967: }
2968: #endif
2969:
2970: free_matrix(a,1,npar,1,npar);
2971: free_matrix(y,1,npar,1,npar);
2972: free_vector(x,1,npar);
2973: free_ivector(indx,1,npar);
2974: /* free_matrix(hess,1,npar,1,npar); */
2975:
2976:
2977: }
2978:
2979: /*************** hessian matrix ****************/
2980: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2981: { /* Around values of x, computes the function func and returns the scales delti and hessian */
2982: int i;
2983: int l=1, lmax=20;
2984: double k1,k2, res, fx;
2985: double p2[MAXPARM+1]; /* identical to x */
2986: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2987: int k=0,kmax=10;
2988: double l1;
2989:
2990: fx=func(x);
2991: for (i=1;i<=npar;i++) p2[i]=x[i];
2992: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2993: l1=pow(10,l);
2994: delts=delt;
2995: for(k=1 ; k <kmax; k=k+1){
2996: delt = delta*(l1*k);
2997: p2[theta]=x[theta] +delt;
2998: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2999: p2[theta]=x[theta]-delt;
3000: k2=func(p2)-fx;
3001: /*res= (k1-2.0*fx+k2)/delt/delt; */
3002: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
3003:
3004: #ifdef DEBUGHESSII
3005: 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);
3006: 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);
3007: #endif
3008: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3009: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3010: k=kmax;
3011: }
3012: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
3013: k=kmax; l=lmax*10;
3014: }
3015: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3016: delts=delt;
3017: }
3018: } /* End loop k */
3019: }
3020: delti[theta]=delts;
3021: return res;
3022:
3023: }
3024:
3025: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
3026: {
3027: int i;
3028: int l=1, lmax=20;
3029: double k1,k2,k3,k4,res,fx;
3030: double p2[MAXPARM+1];
3031: int k, kmax=1;
3032: double v1, v2, cv12, lc1, lc2;
3033:
3034: int firstime=0;
3035:
3036: fx=func(x);
3037: for (k=1; k<=kmax; k=k+10) {
3038: for (i=1;i<=npar;i++) p2[i]=x[i];
3039: p2[thetai]=x[thetai]+delti[thetai]*k;
3040: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3041: k1=func(p2)-fx;
3042:
3043: p2[thetai]=x[thetai]+delti[thetai]*k;
3044: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3045: k2=func(p2)-fx;
3046:
3047: p2[thetai]=x[thetai]-delti[thetai]*k;
3048: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3049: k3=func(p2)-fx;
3050:
3051: p2[thetai]=x[thetai]-delti[thetai]*k;
3052: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3053: k4=func(p2)-fx;
3054: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3055: if(k1*k2*k3*k4 <0.){
3056: firstime=1;
3057: kmax=kmax+10;
3058: }
3059: if(kmax >=10 || firstime ==1){
3060: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3061: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3062: 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);
3063: 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);
3064: }
3065: #ifdef DEBUGHESSIJ
3066: v1=hess[thetai][thetai];
3067: v2=hess[thetaj][thetaj];
3068: cv12=res;
3069: /* Computing eigen value of Hessian matrix */
3070: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3071: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3072: if ((lc2 <0) || (lc1 <0) ){
3073: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3074: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3075: 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);
3076: 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);
3077: }
3078: #endif
3079: }
3080: return res;
3081: }
3082:
3083: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3084: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3085: /* { */
3086: /* int i; */
3087: /* int l=1, lmax=20; */
3088: /* double k1,k2,k3,k4,res,fx; */
3089: /* double p2[MAXPARM+1]; */
3090: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3091: /* int k=0,kmax=10; */
3092: /* double l1; */
3093:
3094: /* fx=func(x); */
3095: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3096: /* l1=pow(10,l); */
3097: /* delts=delt; */
3098: /* for(k=1 ; k <kmax; k=k+1){ */
3099: /* delt = delti*(l1*k); */
3100: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3101: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3102: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3103: /* k1=func(p2)-fx; */
3104:
3105: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3106: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3107: /* k2=func(p2)-fx; */
3108:
3109: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3110: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3111: /* k3=func(p2)-fx; */
3112:
3113: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3114: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3115: /* k4=func(p2)-fx; */
3116: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3117: /* #ifdef DEBUGHESSIJ */
3118: /* 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); */
3119: /* 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); */
3120: /* #endif */
3121: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3122: /* k=kmax; */
3123: /* } */
3124: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3125: /* k=kmax; l=lmax*10; */
3126: /* } */
3127: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3128: /* delts=delt; */
3129: /* } */
3130: /* } /\* End loop k *\/ */
3131: /* } */
3132: /* delti[theta]=delts; */
3133: /* return res; */
3134: /* } */
3135:
3136:
3137: /************** Inverse of matrix **************/
3138: void ludcmp(double **a, int n, int *indx, double *d)
3139: {
3140: int i,imax,j,k;
3141: double big,dum,sum,temp;
3142: double *vv;
3143:
3144: vv=vector(1,n);
3145: *d=1.0;
3146: for (i=1;i<=n;i++) {
3147: big=0.0;
3148: for (j=1;j<=n;j++)
3149: if ((temp=fabs(a[i][j])) > big) big=temp;
3150: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3151: vv[i]=1.0/big;
3152: }
3153: for (j=1;j<=n;j++) {
3154: for (i=1;i<j;i++) {
3155: sum=a[i][j];
3156: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3157: a[i][j]=sum;
3158: }
3159: big=0.0;
3160: for (i=j;i<=n;i++) {
3161: sum=a[i][j];
3162: for (k=1;k<j;k++)
3163: sum -= a[i][k]*a[k][j];
3164: a[i][j]=sum;
3165: if ( (dum=vv[i]*fabs(sum)) >= big) {
3166: big=dum;
3167: imax=i;
3168: }
3169: }
3170: if (j != imax) {
3171: for (k=1;k<=n;k++) {
3172: dum=a[imax][k];
3173: a[imax][k]=a[j][k];
3174: a[j][k]=dum;
3175: }
3176: *d = -(*d);
3177: vv[imax]=vv[j];
3178: }
3179: indx[j]=imax;
3180: if (a[j][j] == 0.0) a[j][j]=TINY;
3181: if (j != n) {
3182: dum=1.0/(a[j][j]);
3183: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3184: }
3185: }
3186: free_vector(vv,1,n); /* Doesn't work */
3187: ;
3188: }
3189:
3190: void lubksb(double **a, int n, int *indx, double b[])
3191: {
3192: int i,ii=0,ip,j;
3193: double sum;
3194:
3195: for (i=1;i<=n;i++) {
3196: ip=indx[i];
3197: sum=b[ip];
3198: b[ip]=b[i];
3199: if (ii)
3200: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3201: else if (sum) ii=i;
3202: b[i]=sum;
3203: }
3204: for (i=n;i>=1;i--) {
3205: sum=b[i];
3206: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3207: b[i]=sum/a[i][i];
3208: }
3209: }
3210:
3211: void pstamp(FILE *fichier)
3212: {
3213: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3214: }
3215:
3216: /************ Frequencies ********************/
3217: 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[])
3218: { /* Some frequencies */
3219:
3220: int i, m, jk, j1, bool, z1,j;
3221: int first;
3222: double ***freq; /* Frequencies */
3223: double *pp, **prop;
3224: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3225: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH];
3226:
3227: pp=vector(1,nlstate);
3228: prop=matrix(1,nlstate,iagemin,iagemax+3);
3229: strcpy(fileresp,"P_");
3230: strcat(fileresp,fileresu);
3231: /*strcat(fileresphtm,fileresu);*/
3232: if((ficresp=fopen(fileresp,"w"))==NULL) {
3233: printf("Problem with prevalence resultfile: %s\n", fileresp);
3234: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3235: exit(0);
3236: }
3237: printf("Problem with prevalence resultfile: %s\n", fileresp);
3238: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
3239: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
3240: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3241: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3242: fflush(ficlog);
3243: exit(70);
3244: }
3245: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3246: j1=0;
3247:
3248: j=cptcoveff;
3249: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3250:
3251: first=1;
3252:
3253: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3254: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3255: /* j1++; */
3256: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
3257: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3258: scanf("%d", i);*/
3259: for (i=-5; i<=nlstate+ndeath; i++)
3260: for (jk=-5; jk<=nlstate+ndeath; jk++)
3261: for(m=iagemin; m <= iagemax+3; m++)
3262: freq[i][jk][m]=0;
3263:
3264: for (i=1; i<=nlstate; i++)
3265: for(m=iagemin; m <= iagemax+3; m++)
3266: prop[i][m]=0;
3267:
3268: dateintsum=0;
3269: k2cpt=0;
3270: for (i=1; i<=imx; i++) {
3271: bool=1;
3272: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3273: for (z1=1; z1<=cptcoveff; z1++)
3274: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3275: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3276: bool=0;
3277: /* 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",
3278: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3279: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3280: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3281: }
3282: } /* cptcovn > 0 */
3283:
3284: if (bool==1){
3285: for(m=firstpass; m<=lastpass; m++){
3286: k2=anint[m][i]+(mint[m][i]/12.);
3287: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3288: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3289: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3290: if (s[m][i]>0 && s[m][i]<=nlstate)
3291: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3292: if (m<lastpass) {
3293: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3294: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3295: }
3296:
3297: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
3298: dateintsum=dateintsum+k2;
3299: k2cpt++;
3300: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
3301: }
3302: /*}*/
3303: } /* end m */
3304: } /* end bool */
3305: } /* end i = 1 to imx */
3306:
3307: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3308: pstamp(ficresp);
3309: if (cptcovn>0) {
3310: fprintf(ficresp, "\n#********** Variable ");
3311: fprintf(ficresphtm, "\n<h3>********** Variable ");
3312: for (z1=1; z1<=cptcoveff; z1++){
3313: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3314: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3315: }
3316: fprintf(ficresp, "**********\n#");
3317: fprintf(ficresphtm, "**********</h3>\n#");
3318: fprintf(ficlog, "\n#********** Variable ");
3319: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3320: fprintf(ficlog, "**********\n#");
3321: }
3322: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\"><th></th>");
3323: for(i=1; i<=nlstate;i++) {
3324: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3325: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
3326: }
3327: fprintf(ficresp, "\n");
3328: fprintf(ficresphtm, "\n");
3329:
3330: for(i=iagemin; i <= iagemax+3; i++){
3331: fprintf(ficresphtm,"<tr>");
3332: if(i==iagemax+3){
3333: fprintf(ficlog,"Total");
3334: }else{
3335: if(first==1){
3336: first=0;
3337: printf("See log file for details...\n");
3338: }
3339: fprintf(ficlog,"Age %d", i);
3340: }
3341: for(jk=1; jk <=nlstate ; jk++){
3342: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3343: pp[jk] += freq[jk][m][i];
3344: }
3345: for(jk=1; jk <=nlstate ; jk++){
3346: for(m=-1, pos=0; m <=0 ; m++)
3347: pos += freq[jk][m][i];
3348: if(pp[jk]>=1.e-10){
3349: if(first==1){
3350: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3351: }
3352: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3353: }else{
3354: if(first==1)
3355: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3356: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3357: }
3358: }
3359:
3360: for(jk=1; jk <=nlstate ; jk++){
3361: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3362: pp[jk] += freq[jk][m][i];
3363: }
3364: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3365: pos += pp[jk];
3366: posprop += prop[jk][i];
3367: }
3368: for(jk=1; jk <=nlstate ; jk++){
3369: if(pos>=1.e-5){
3370: if(first==1)
3371: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3372: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3373: }else{
3374: if(first==1)
3375: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3376: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3377: }
3378: if( i <= iagemax){
3379: if(pos>=1.e-5){
3380: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3381: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3382: /*probs[i][jk][j1]= pp[jk]/pos;*/
3383: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3384: }
3385: else{
3386: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3387: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
3388: }
3389: }
3390: }
3391:
3392: for(jk=-1; jk <=nlstate+ndeath; jk++)
3393: for(m=-1; m <=nlstate+ndeath; m++)
3394: if(freq[jk][m][i] !=0 ) {
3395: if(first==1)
3396: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3397: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3398: }
3399: if(i <= iagemax){
3400: fprintf(ficresp,"\n");
3401: fprintf(ficresphtm,"</tr>\n");
3402: }
3403: if(first==1)
3404: printf("Others in log...\n");
3405: fprintf(ficlog,"\n");
3406: } /* end loop i */
3407: fprintf(ficresphtm,"</table>\n");
3408: /*}*/
3409: } /* end j1 */
3410: dateintmean=dateintsum/k2cpt;
3411:
3412: fclose(ficresp);
3413: fclose(ficresphtm);
3414: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3415: free_vector(pp,1,nlstate);
3416: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3417: /* End of Freq */
3418: }
3419:
3420: /************ Prevalence ********************/
3421: 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)
3422: {
3423: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3424: in each health status at the date of interview (if between dateprev1 and dateprev2).
3425: We still use firstpass and lastpass as another selection.
3426: */
3427:
3428: int i, m, jk, j1, bool, z1,j;
3429:
3430: double **prop;
3431: double posprop;
3432: double y2; /* in fractional years */
3433: int iagemin, iagemax;
3434: int first; /** to stop verbosity which is redirected to log file */
3435:
3436: iagemin= (int) agemin;
3437: iagemax= (int) agemax;
3438: /*pp=vector(1,nlstate);*/
3439: prop=matrix(1,nlstate,iagemin,iagemax+3);
3440: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3441: j1=0;
3442:
3443: /*j=cptcoveff;*/
3444: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3445:
3446: first=1;
3447: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3448: /*for(i1=1; i1<=ncodemax[k1];i1++){
3449: j1++;*/
3450:
3451: for (i=1; i<=nlstate; i++)
3452: for(m=iagemin; m <= iagemax+3; m++)
3453: prop[i][m]=0.0;
3454:
3455: for (i=1; i<=imx; i++) { /* Each individual */
3456: bool=1;
3457: if (cptcovn>0) {
3458: for (z1=1; z1<=cptcoveff; z1++)
3459: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3460: bool=0;
3461: }
3462: if (bool==1) {
3463: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3464: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3465: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3466: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3467: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3468: 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);
3469: if (s[m][i]>0 && s[m][i]<=nlstate) {
3470: /*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]]);*/
3471: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3472: prop[s[m][i]][iagemax+3] += weight[i];
3473: }
3474: }
3475: } /* end selection of waves */
3476: }
3477: }
3478: for(i=iagemin; i <= iagemax+3; i++){
3479: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3480: posprop += prop[jk][i];
3481: }
3482:
3483: for(jk=1; jk <=nlstate ; jk++){
3484: if( i <= iagemax){
3485: if(posprop>=1.e-5){
3486: probs[i][jk][j1]= prop[jk][i]/posprop;
3487: } else{
3488: if(first==1){
3489: first=0;
3490: 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]);
3491: }
3492: }
3493: }
3494: }/* end jk */
3495: }/* end i */
3496: /*} *//* end i1 */
3497: } /* end j1 */
3498:
3499: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3500: /*free_vector(pp,1,nlstate);*/
3501: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3502: } /* End of prevalence */
3503:
3504: /************* Waves Concatenation ***************/
3505:
3506: 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)
3507: {
3508: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3509: Death is a valid wave (if date is known).
3510: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3511: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3512: and mw[mi+1][i]. dh depends on stepm.
3513: */
3514:
3515: int i, mi, m;
3516: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3517: double sum=0., jmean=0.;*/
3518: int first;
3519: int j, k=0,jk, ju, jl;
3520: double sum=0.;
3521: first=0;
3522: jmin=100000;
3523: jmax=-1;
3524: jmean=0.;
3525: for(i=1; i<=imx; i++){
3526: mi=0;
3527: m=firstpass;
3528: while(s[m][i] <= nlstate){
3529: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3530: mw[++mi][i]=m;
3531: if(m >=lastpass)
3532: break;
3533: else
3534: m++;
3535: }/* end while */
3536: if (s[m][i] > nlstate){
3537: mi++; /* Death is another wave */
3538: /* if(mi==0) never been interviewed correctly before death */
3539: /* Only death is a correct wave */
3540: mw[mi][i]=m;
3541: }
3542:
3543: wav[i]=mi;
3544: if(mi==0){
3545: nbwarn++;
3546: if(first==0){
3547: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3548: first=1;
3549: }
3550: if(first==1){
3551: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3552: }
3553: } /* end mi==0 */
3554: } /* End individuals */
3555:
3556: for(i=1; i<=imx; i++){
3557: for(mi=1; mi<wav[i];mi++){
3558: if (stepm <=0)
3559: dh[mi][i]=1;
3560: else{
3561: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3562: if (agedc[i] < 2*AGESUP) {
3563: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3564: if(j==0) j=1; /* Survives at least one month after exam */
3565: else if(j<0){
3566: nberr++;
3567: 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]);
3568: j=1; /* Temporary Dangerous patch */
3569: 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);
3570: 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]);
3571: 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);
3572: }
3573: k=k+1;
3574: if (j >= jmax){
3575: jmax=j;
3576: ijmax=i;
3577: }
3578: if (j <= jmin){
3579: jmin=j;
3580: ijmin=i;
3581: }
3582: sum=sum+j;
3583: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3584: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3585: }
3586: }
3587: else{
3588: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3589: /* 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]); */
3590:
3591: k=k+1;
3592: if (j >= jmax) {
3593: jmax=j;
3594: ijmax=i;
3595: }
3596: else if (j <= jmin){
3597: jmin=j;
3598: ijmin=i;
3599: }
3600: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3601: /*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]);*/
3602: if(j<0){
3603: nberr++;
3604: 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]);
3605: 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]);
3606: }
3607: sum=sum+j;
3608: }
3609: jk= j/stepm;
3610: jl= j -jk*stepm;
3611: ju= j -(jk+1)*stepm;
3612: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3613: if(jl==0){
3614: dh[mi][i]=jk;
3615: bh[mi][i]=0;
3616: }else{ /* We want a negative bias in order to only have interpolation ie
3617: * to avoid the price of an extra matrix product in likelihood */
3618: dh[mi][i]=jk+1;
3619: bh[mi][i]=ju;
3620: }
3621: }else{
3622: if(jl <= -ju){
3623: dh[mi][i]=jk;
3624: bh[mi][i]=jl; /* bias is positive if real duration
3625: * is higher than the multiple of stepm and negative otherwise.
3626: */
3627: }
3628: else{
3629: dh[mi][i]=jk+1;
3630: bh[mi][i]=ju;
3631: }
3632: if(dh[mi][i]==0){
3633: dh[mi][i]=1; /* At least one step */
3634: bh[mi][i]=ju; /* At least one step */
3635: /* 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);*/
3636: }
3637: } /* end if mle */
3638: }
3639: } /* end wave */
3640: }
3641: jmean=sum/k;
3642: 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);
3643: 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);
3644: }
3645:
3646: /*********** Tricode ****************************/
3647: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3648: {
3649: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3650: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3651: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3652: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3653: * nbcode[Tvar[j]][1]=
3654: */
3655:
3656: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3657: int modmaxcovj=0; /* Modality max of covariates j */
3658: int cptcode=0; /* Modality max of covariates j */
3659: int modmincovj=0; /* Modality min of covariates j */
3660:
3661:
3662: cptcoveff=0;
3663:
3664: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3665:
3666: /* Loop on covariates without age and products */
3667: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3668: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3669: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3670: modality of this covariate Vj*/
3671: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3672: * If product of Vn*Vm, still boolean *:
3673: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3674: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3675: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3676: modality of the nth covariate of individual i. */
3677: if (ij > modmaxcovj)
3678: modmaxcovj=ij;
3679: else if (ij < modmincovj)
3680: modmincovj=ij;
3681: if ((ij < -1) && (ij > NCOVMAX)){
3682: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3683: exit(1);
3684: }else
3685: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3686: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3687: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3688: /* getting the maximum value of the modality of the covariate
3689: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3690: female is 1, then modmaxcovj=1.*/
3691: } /* end for loop on individuals i */
3692: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3693: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3694: cptcode=modmaxcovj;
3695: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3696: /*for (i=0; i<=cptcode; i++) {*/
3697: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3698: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3699: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3700: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3701: if( k != -1){
3702: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3703: covariate for which somebody answered excluding
3704: undefined. Usually 2: 0 and 1. */
3705: }
3706: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3707: covariate for which somebody answered including
3708: undefined. Usually 3: -1, 0 and 1. */
3709: }
3710: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3711: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3712: } /* Ndum[-1] number of undefined modalities */
3713:
3714: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3715: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3716: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3717: modmincovj=3; modmaxcovj = 7;
3718: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3719: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3720: defining two dummy variables: variables V1_1 and V1_2.
3721: nbcode[Tvar[j]][ij]=k;
3722: nbcode[Tvar[j]][1]=0;
3723: nbcode[Tvar[j]][2]=1;
3724: nbcode[Tvar[j]][3]=2;
3725: To be continued (not working yet).
3726: */
3727: ij=0; /* ij is similar to i but can jump over null modalities */
3728: 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*/
3729: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3730: break;
3731: }
3732: ij++;
3733: 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.*/
3734: cptcode = ij; /* New max modality for covar j */
3735: } /* end of loop on modality i=-1 to 1 or more */
3736:
3737: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3738: /* /\*recode from 0 *\/ */
3739: /* k is a modality. If we have model=V1+V1*sex */
3740: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3741: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3742: /* } */
3743: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3744: /* if (ij > ncodemax[j]) { */
3745: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3746: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3747: /* break; */
3748: /* } */
3749: /* } /\* end of loop on modality k *\/ */
3750: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3751:
3752: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3753:
3754: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3755: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3756: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3757: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3758: }
3759:
3760: ij=0;
3761: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3762: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3763: if((Ndum[i]!=0) && (i<=ncovcol)){
3764: ij++;
3765: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3766: Tvaraff[ij]=i; /*For printing (unclear) */
3767: }else{
3768: /* Tvaraff[ij]=0; */
3769: }
3770: }
3771: /* ij--; */
3772: cptcoveff=ij; /*Number of total covariates*/
3773:
3774: }
3775:
3776:
3777: /*********** Health Expectancies ****************/
3778:
3779: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3780:
3781: {
3782: /* Health expectancies, no variances */
3783: int i, j, nhstepm, hstepm, h, nstepm;
3784: int nhstepma, nstepma; /* Decreasing with age */
3785: double age, agelim, hf;
3786: double ***p3mat;
3787: double eip;
3788:
3789: pstamp(ficreseij);
3790: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3791: fprintf(ficreseij,"# Age");
3792: for(i=1; i<=nlstate;i++){
3793: for(j=1; j<=nlstate;j++){
3794: fprintf(ficreseij," e%1d%1d ",i,j);
3795: }
3796: fprintf(ficreseij," e%1d. ",i);
3797: }
3798: fprintf(ficreseij,"\n");
3799:
3800:
3801: if(estepm < stepm){
3802: printf ("Problem %d lower than %d\n",estepm, stepm);
3803: }
3804: else hstepm=estepm;
3805: /* We compute the life expectancy from trapezoids spaced every estepm months
3806: * This is mainly to measure the difference between two models: for example
3807: * if stepm=24 months pijx are given only every 2 years and by summing them
3808: * we are calculating an estimate of the Life Expectancy assuming a linear
3809: * progression in between and thus overestimating or underestimating according
3810: * to the curvature of the survival function. If, for the same date, we
3811: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3812: * to compare the new estimate of Life expectancy with the same linear
3813: * hypothesis. A more precise result, taking into account a more precise
3814: * curvature will be obtained if estepm is as small as stepm. */
3815:
3816: /* For example we decided to compute the life expectancy with the smallest unit */
3817: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3818: nhstepm is the number of hstepm from age to agelim
3819: nstepm is the number of stepm from age to agelin.
3820: Look at hpijx to understand the reason of that which relies in memory size
3821: and note for a fixed period like estepm months */
3822: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3823: survival function given by stepm (the optimization length). Unfortunately it
3824: means that if the survival funtion is printed only each two years of age and if
3825: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3826: results. So we changed our mind and took the option of the best precision.
3827: */
3828: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3829:
3830: agelim=AGESUP;
3831: /* If stepm=6 months */
3832: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3833: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3834:
3835: /* nhstepm age range expressed in number of stepm */
3836: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3837: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3838: /* if (stepm >= YEARM) hstepm=1;*/
3839: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3840: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3841:
3842: for (age=bage; age<=fage; age ++){
3843: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3844: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3845: /* if (stepm >= YEARM) hstepm=1;*/
3846: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3847:
3848: /* If stepm=6 months */
3849: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3850: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3851:
3852: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3853:
3854: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3855:
3856: printf("%d|",(int)age);fflush(stdout);
3857: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3858:
3859: /* Computing expectancies */
3860: for(i=1; i<=nlstate;i++)
3861: for(j=1; j<=nlstate;j++)
3862: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3863: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3864:
3865: /* 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]);*/
3866:
3867: }
3868:
3869: fprintf(ficreseij,"%3.0f",age );
3870: for(i=1; i<=nlstate;i++){
3871: eip=0;
3872: for(j=1; j<=nlstate;j++){
3873: eip +=eij[i][j][(int)age];
3874: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3875: }
3876: fprintf(ficreseij,"%9.4f", eip );
3877: }
3878: fprintf(ficreseij,"\n");
3879:
3880: }
3881: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3882: printf("\n");
3883: fprintf(ficlog,"\n");
3884:
3885: }
3886:
3887: 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[] )
3888:
3889: {
3890: /* Covariances of health expectancies eij and of total life expectancies according
3891: to initial status i, ei. .
3892: */
3893: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3894: int nhstepma, nstepma; /* Decreasing with age */
3895: double age, agelim, hf;
3896: double ***p3matp, ***p3matm, ***varhe;
3897: double **dnewm,**doldm;
3898: double *xp, *xm;
3899: double **gp, **gm;
3900: double ***gradg, ***trgradg;
3901: int theta;
3902:
3903: double eip, vip;
3904:
3905: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3906: xp=vector(1,npar);
3907: xm=vector(1,npar);
3908: dnewm=matrix(1,nlstate*nlstate,1,npar);
3909: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3910:
3911: pstamp(ficresstdeij);
3912: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3913: fprintf(ficresstdeij,"# Age");
3914: for(i=1; i<=nlstate;i++){
3915: for(j=1; j<=nlstate;j++)
3916: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3917: fprintf(ficresstdeij," e%1d. ",i);
3918: }
3919: fprintf(ficresstdeij,"\n");
3920:
3921: pstamp(ficrescveij);
3922: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3923: fprintf(ficrescveij,"# Age");
3924: for(i=1; i<=nlstate;i++)
3925: for(j=1; j<=nlstate;j++){
3926: cptj= (j-1)*nlstate+i;
3927: for(i2=1; i2<=nlstate;i2++)
3928: for(j2=1; j2<=nlstate;j2++){
3929: cptj2= (j2-1)*nlstate+i2;
3930: if(cptj2 <= cptj)
3931: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3932: }
3933: }
3934: fprintf(ficrescveij,"\n");
3935:
3936: if(estepm < stepm){
3937: printf ("Problem %d lower than %d\n",estepm, stepm);
3938: }
3939: else hstepm=estepm;
3940: /* We compute the life expectancy from trapezoids spaced every estepm months
3941: * This is mainly to measure the difference between two models: for example
3942: * if stepm=24 months pijx are given only every 2 years and by summing them
3943: * we are calculating an estimate of the Life Expectancy assuming a linear
3944: * progression in between and thus overestimating or underestimating according
3945: * to the curvature of the survival function. If, for the same date, we
3946: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3947: * to compare the new estimate of Life expectancy with the same linear
3948: * hypothesis. A more precise result, taking into account a more precise
3949: * curvature will be obtained if estepm is as small as stepm. */
3950:
3951: /* For example we decided to compute the life expectancy with the smallest unit */
3952: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3953: nhstepm is the number of hstepm from age to agelim
3954: nstepm is the number of stepm from age to agelin.
3955: Look at hpijx to understand the reason of that which relies in memory size
3956: and note for a fixed period like estepm months */
3957: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3958: survival function given by stepm (the optimization length). Unfortunately it
3959: means that if the survival funtion is printed only each two years of age and if
3960: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3961: results. So we changed our mind and took the option of the best precision.
3962: */
3963: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3964:
3965: /* If stepm=6 months */
3966: /* nhstepm age range expressed in number of stepm */
3967: agelim=AGESUP;
3968: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3969: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3970: /* if (stepm >= YEARM) hstepm=1;*/
3971: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3972:
3973: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3974: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3975: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3976: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3977: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3978: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3979:
3980: for (age=bage; age<=fage; age ++){
3981: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3982: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3983: /* if (stepm >= YEARM) hstepm=1;*/
3984: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3985:
3986: /* If stepm=6 months */
3987: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3988: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3989:
3990: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3991:
3992: /* Computing Variances of health expectancies */
3993: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3994: decrease memory allocation */
3995: for(theta=1; theta <=npar; theta++){
3996: for(i=1; i<=npar; i++){
3997: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3998: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3999: }
4000: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
4001: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
4002:
4003: for(j=1; j<= nlstate; j++){
4004: for(i=1; i<=nlstate; i++){
4005: for(h=0; h<=nhstepm-1; h++){
4006: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
4007: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
4008: }
4009: }
4010: }
4011:
4012: for(ij=1; ij<= nlstate*nlstate; ij++)
4013: for(h=0; h<=nhstepm-1; h++){
4014: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
4015: }
4016: }/* End theta */
4017:
4018:
4019: for(h=0; h<=nhstepm-1; h++)
4020: for(j=1; j<=nlstate*nlstate;j++)
4021: for(theta=1; theta <=npar; theta++)
4022: trgradg[h][j][theta]=gradg[h][theta][j];
4023:
4024:
4025: for(ij=1;ij<=nlstate*nlstate;ij++)
4026: for(ji=1;ji<=nlstate*nlstate;ji++)
4027: varhe[ij][ji][(int)age] =0.;
4028:
4029: printf("%d|",(int)age);fflush(stdout);
4030: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4031: for(h=0;h<=nhstepm-1;h++){
4032: for(k=0;k<=nhstepm-1;k++){
4033: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
4034: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
4035: for(ij=1;ij<=nlstate*nlstate;ij++)
4036: for(ji=1;ji<=nlstate*nlstate;ji++)
4037: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
4038: }
4039: }
4040:
4041: /* Computing expectancies */
4042: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4043: for(i=1; i<=nlstate;i++)
4044: for(j=1; j<=nlstate;j++)
4045: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4046: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
4047:
4048: /* 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]);*/
4049:
4050: }
4051:
4052: fprintf(ficresstdeij,"%3.0f",age );
4053: for(i=1; i<=nlstate;i++){
4054: eip=0.;
4055: vip=0.;
4056: for(j=1; j<=nlstate;j++){
4057: eip += eij[i][j][(int)age];
4058: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4059: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4060: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4061: }
4062: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4063: }
4064: fprintf(ficresstdeij,"\n");
4065:
4066: fprintf(ficrescveij,"%3.0f",age );
4067: for(i=1; i<=nlstate;i++)
4068: for(j=1; j<=nlstate;j++){
4069: cptj= (j-1)*nlstate+i;
4070: for(i2=1; i2<=nlstate;i2++)
4071: for(j2=1; j2<=nlstate;j2++){
4072: cptj2= (j2-1)*nlstate+i2;
4073: if(cptj2 <= cptj)
4074: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4075: }
4076: }
4077: fprintf(ficrescveij,"\n");
4078:
4079: }
4080: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4081: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4082: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4083: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4084: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4085: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4086: printf("\n");
4087: fprintf(ficlog,"\n");
4088:
4089: free_vector(xm,1,npar);
4090: free_vector(xp,1,npar);
4091: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4092: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4093: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4094: }
4095:
4096: /************ Variance ******************/
4097: 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 *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
4098: {
4099: /* Variance of health expectancies */
4100: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4101: /* double **newm;*/
4102: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4103:
4104: int movingaverage();
4105: double **dnewm,**doldm;
4106: double **dnewmp,**doldmp;
4107: int i, j, nhstepm, hstepm, h, nstepm ;
4108: int k;
4109: double *xp;
4110: double **gp, **gm; /* for var eij */
4111: double ***gradg, ***trgradg; /*for var eij */
4112: double **gradgp, **trgradgp; /* for var p point j */
4113: double *gpp, *gmp; /* for var p point j */
4114: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4115: double ***p3mat;
4116: double age,agelim, hf;
4117: double ***mobaverage;
4118: int theta;
4119: char digit[4];
4120: char digitp[25];
4121:
4122: char fileresprobmorprev[FILENAMELENGTH];
4123:
4124: if(popbased==1){
4125: if(mobilav!=0)
4126: strcpy(digitp,"-POPULBASED-MOBILAV_");
4127: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4128: }
4129: else
4130: strcpy(digitp,"-STABLBASED_");
4131:
4132: if (mobilav!=0) {
4133: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4134: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4135: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4136: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4137: }
4138: }
4139:
4140: strcpy(fileresprobmorprev,"PRMORPREV-");
4141: sprintf(digit,"%-d",ij);
4142: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4143: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4144: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4145: strcat(fileresprobmorprev,fileresu);
4146: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4147: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4148: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4149: }
4150: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4151: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4152: pstamp(ficresprobmorprev);
4153: 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);
4154: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4155: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4156: fprintf(ficresprobmorprev," p.%-d SE",j);
4157: for(i=1; i<=nlstate;i++)
4158: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4159: }
4160: fprintf(ficresprobmorprev,"\n");
4161:
4162: fprintf(ficgp,"\n# Routine varevsij");
4163: fprintf(ficgp,"\nunset title \n");
4164: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4165: 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");
4166: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4167: /* } */
4168: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4169: pstamp(ficresvij);
4170: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4171: if(popbased==1)
4172: 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);
4173: else
4174: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4175: fprintf(ficresvij,"# Age");
4176: for(i=1; i<=nlstate;i++)
4177: for(j=1; j<=nlstate;j++)
4178: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4179: fprintf(ficresvij,"\n");
4180:
4181: xp=vector(1,npar);
4182: dnewm=matrix(1,nlstate,1,npar);
4183: doldm=matrix(1,nlstate,1,nlstate);
4184: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4185: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4186:
4187: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4188: gpp=vector(nlstate+1,nlstate+ndeath);
4189: gmp=vector(nlstate+1,nlstate+ndeath);
4190: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4191:
4192: if(estepm < stepm){
4193: printf ("Problem %d lower than %d\n",estepm, stepm);
4194: }
4195: else hstepm=estepm;
4196: /* For example we decided to compute the life expectancy with the smallest unit */
4197: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4198: nhstepm is the number of hstepm from age to agelim
4199: nstepm is the number of stepm from age to agelim.
4200: Look at function hpijx to understand why because of memory size limitations,
4201: we decided (b) to get a life expectancy respecting the most precise curvature of the
4202: survival function given by stepm (the optimization length). Unfortunately it
4203: means that if the survival funtion is printed every two years of age and if
4204: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4205: results. So we changed our mind and took the option of the best precision.
4206: */
4207: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4208: agelim = AGESUP;
4209: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4210: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4211: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4212: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4213: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4214: gp=matrix(0,nhstepm,1,nlstate);
4215: gm=matrix(0,nhstepm,1,nlstate);
4216:
4217:
4218: for(theta=1; theta <=npar; theta++){
4219: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4220: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4221: }
4222:
4223: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4224:
4225: if (popbased==1) {
4226: if(mobilav ==0){
4227: for(i=1; i<=nlstate;i++)
4228: prlim[i][i]=probs[(int)age][i][ij];
4229: }else{ /* mobilav */
4230: for(i=1; i<=nlstate;i++)
4231: prlim[i][i]=mobaverage[(int)age][i][ij];
4232: }
4233: }
4234:
4235: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
4236: for(j=1; j<= nlstate; j++){
4237: for(h=0; h<=nhstepm; h++){
4238: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4239: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4240: }
4241: }
4242: /* Next for computing probability of death (h=1 means
4243: computed over hstepm matrices product = hstepm*stepm months)
4244: as a weighted average of prlim.
4245: */
4246: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4247: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4248: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4249: }
4250: /* end probability of death */
4251:
4252: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4253: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4254:
4255: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
4256:
4257: if (popbased==1) {
4258: if(mobilav ==0){
4259: for(i=1; i<=nlstate;i++)
4260: prlim[i][i]=probs[(int)age][i][ij];
4261: }else{ /* mobilav */
4262: for(i=1; i<=nlstate;i++)
4263: prlim[i][i]=mobaverage[(int)age][i][ij];
4264: }
4265: }
4266:
4267: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4268:
4269: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4270: for(h=0; h<=nhstepm; h++){
4271: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4272: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4273: }
4274: }
4275: /* This for computing probability of death (h=1 means
4276: computed over hstepm matrices product = hstepm*stepm months)
4277: as a weighted average of prlim.
4278: */
4279: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4280: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4281: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4282: }
4283: /* end probability of death */
4284:
4285: for(j=1; j<= nlstate; j++) /* vareij */
4286: for(h=0; h<=nhstepm; h++){
4287: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4288: }
4289:
4290: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4291: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4292: }
4293:
4294: } /* End theta */
4295:
4296: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4297:
4298: for(h=0; h<=nhstepm; h++) /* veij */
4299: for(j=1; j<=nlstate;j++)
4300: for(theta=1; theta <=npar; theta++)
4301: trgradg[h][j][theta]=gradg[h][theta][j];
4302:
4303: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4304: for(theta=1; theta <=npar; theta++)
4305: trgradgp[j][theta]=gradgp[theta][j];
4306:
4307:
4308: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4309: for(i=1;i<=nlstate;i++)
4310: for(j=1;j<=nlstate;j++)
4311: vareij[i][j][(int)age] =0.;
4312:
4313: for(h=0;h<=nhstepm;h++){
4314: for(k=0;k<=nhstepm;k++){
4315: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4316: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4317: for(i=1;i<=nlstate;i++)
4318: for(j=1;j<=nlstate;j++)
4319: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4320: }
4321: }
4322:
4323: /* pptj */
4324: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4325: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4326: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4327: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4328: varppt[j][i]=doldmp[j][i];
4329: /* end ppptj */
4330: /* x centered again */
4331:
4332: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
4333:
4334: if (popbased==1) {
4335: if(mobilav ==0){
4336: for(i=1; i<=nlstate;i++)
4337: prlim[i][i]=probs[(int)age][i][ij];
4338: }else{ /* mobilav */
4339: for(i=1; i<=nlstate;i++)
4340: prlim[i][i]=mobaverage[(int)age][i][ij];
4341: }
4342: }
4343:
4344: /* This for computing probability of death (h=1 means
4345: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4346: as a weighted average of prlim.
4347: */
4348: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4349: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4350: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4351: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4352: }
4353: /* end probability of death */
4354:
4355: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4356: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4357: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4358: for(i=1; i<=nlstate;i++){
4359: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4360: }
4361: }
4362: fprintf(ficresprobmorprev,"\n");
4363:
4364: fprintf(ficresvij,"%.0f ",age );
4365: for(i=1; i<=nlstate;i++)
4366: for(j=1; j<=nlstate;j++){
4367: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4368: }
4369: fprintf(ficresvij,"\n");
4370: free_matrix(gp,0,nhstepm,1,nlstate);
4371: free_matrix(gm,0,nhstepm,1,nlstate);
4372: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4373: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4374: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4375: } /* End age */
4376: free_vector(gpp,nlstate+1,nlstate+ndeath);
4377: free_vector(gmp,nlstate+1,nlstate+ndeath);
4378: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4379: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4380: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4381: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4382: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4383: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4384: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4385: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4386: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4387: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4388: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4389: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4390: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4391: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4392: 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);
4393: /* 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);
4394: */
4395: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4396: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4397:
4398: free_vector(xp,1,npar);
4399: free_matrix(doldm,1,nlstate,1,nlstate);
4400: free_matrix(dnewm,1,nlstate,1,npar);
4401: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4402: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4403: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4404: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4405: fclose(ficresprobmorprev);
4406: fflush(ficgp);
4407: fflush(fichtm);
4408: } /* end varevsij */
4409:
4410: /************ Variance of prevlim ******************/
4411: 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 *ncvyearp, int ij, char strstart[])
4412: {
4413: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4414: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4415:
4416: double **dnewm,**doldm;
4417: int i, j, nhstepm, hstepm;
4418: double *xp;
4419: double *gp, *gm;
4420: double **gradg, **trgradg;
4421: double **mgm, **mgp;
4422: double age,agelim;
4423: int theta;
4424:
4425: pstamp(ficresvpl);
4426: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4427: fprintf(ficresvpl,"# Age");
4428: for(i=1; i<=nlstate;i++)
4429: fprintf(ficresvpl," %1d-%1d",i,i);
4430: fprintf(ficresvpl,"\n");
4431:
4432: xp=vector(1,npar);
4433: dnewm=matrix(1,nlstate,1,npar);
4434: doldm=matrix(1,nlstate,1,nlstate);
4435:
4436: hstepm=1*YEARM; /* Every year of age */
4437: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4438: agelim = AGESUP;
4439: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4440: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4441: if (stepm >= YEARM) hstepm=1;
4442: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4443: gradg=matrix(1,npar,1,nlstate);
4444: mgp=matrix(1,npar,1,nlstate);
4445: mgm=matrix(1,npar,1,nlstate);
4446: gp=vector(1,nlstate);
4447: gm=vector(1,nlstate);
4448:
4449: for(theta=1; theta <=npar; theta++){
4450: for(i=1; i<=npar; i++){ /* Computes gradient */
4451: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4452: }
4453: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4454: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4455: else
4456: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4457: for(i=1;i<=nlstate;i++){
4458: gp[i] = prlim[i][i];
4459: mgp[theta][i] = prlim[i][i];
4460: }
4461: for(i=1; i<=npar; i++) /* Computes gradient */
4462: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4463: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4464: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4465: else
4466: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4467: for(i=1;i<=nlstate;i++){
4468: gm[i] = prlim[i][i];
4469: mgm[theta][i] = prlim[i][i];
4470: }
4471: for(i=1;i<=nlstate;i++)
4472: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4473: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
4474: } /* End theta */
4475:
4476: trgradg =matrix(1,nlstate,1,npar);
4477:
4478: for(j=1; j<=nlstate;j++)
4479: for(theta=1; theta <=npar; theta++)
4480: trgradg[j][theta]=gradg[theta][j];
4481: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4482: /* printf("\nmgm mgp %d ",(int)age); */
4483: /* for(j=1; j<=nlstate;j++){ */
4484: /* printf(" %d ",j); */
4485: /* for(theta=1; theta <=npar; theta++) */
4486: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4487: /* printf("\n "); */
4488: /* } */
4489: /* } */
4490: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4491: /* printf("\n gradg %d ",(int)age); */
4492: /* for(j=1; j<=nlstate;j++){ */
4493: /* printf("%d ",j); */
4494: /* for(theta=1; theta <=npar; theta++) */
4495: /* printf("%d %lf ",theta,gradg[theta][j]); */
4496: /* printf("\n "); */
4497: /* } */
4498: /* } */
4499:
4500: for(i=1;i<=nlstate;i++)
4501: varpl[i][(int)age] =0.;
4502: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
4503: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4504: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4505: }else{
4506: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4507: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4508: }
4509: for(i=1;i<=nlstate;i++)
4510: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4511:
4512: fprintf(ficresvpl,"%.0f ",age );
4513: for(i=1; i<=nlstate;i++)
4514: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4515: fprintf(ficresvpl,"\n");
4516: free_vector(gp,1,nlstate);
4517: free_vector(gm,1,nlstate);
4518: free_matrix(mgm,1,npar,1,nlstate);
4519: free_matrix(mgp,1,npar,1,nlstate);
4520: free_matrix(gradg,1,npar,1,nlstate);
4521: free_matrix(trgradg,1,nlstate,1,npar);
4522: } /* End age */
4523:
4524: free_vector(xp,1,npar);
4525: free_matrix(doldm,1,nlstate,1,npar);
4526: free_matrix(dnewm,1,nlstate,1,nlstate);
4527:
4528: }
4529:
4530: /************ Variance of one-step probabilities ******************/
4531: 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[])
4532: {
4533: int i, j=0, k1, l1, tj;
4534: int k2, l2, j1, z1;
4535: int k=0, l;
4536: int first=1, first1, first2;
4537: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4538: double **dnewm,**doldm;
4539: double *xp;
4540: double *gp, *gm;
4541: double **gradg, **trgradg;
4542: double **mu;
4543: double age, cov[NCOVMAX+1];
4544: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4545: int theta;
4546: char fileresprob[FILENAMELENGTH];
4547: char fileresprobcov[FILENAMELENGTH];
4548: char fileresprobcor[FILENAMELENGTH];
4549: double ***varpij;
4550:
4551: strcpy(fileresprob,"PROB_");
4552: strcat(fileresprob,fileres);
4553: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4554: printf("Problem with resultfile: %s\n", fileresprob);
4555: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4556: }
4557: strcpy(fileresprobcov,"PROBCOV_");
4558: strcat(fileresprobcov,fileresu);
4559: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4560: printf("Problem with resultfile: %s\n", fileresprobcov);
4561: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4562: }
4563: strcpy(fileresprobcor,"PROBCOR_");
4564: strcat(fileresprobcor,fileresu);
4565: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4566: printf("Problem with resultfile: %s\n", fileresprobcor);
4567: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4568: }
4569: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4570: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4571: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4572: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4573: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4574: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4575: pstamp(ficresprob);
4576: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4577: fprintf(ficresprob,"# Age");
4578: pstamp(ficresprobcov);
4579: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4580: fprintf(ficresprobcov,"# Age");
4581: pstamp(ficresprobcor);
4582: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4583: fprintf(ficresprobcor,"# Age");
4584:
4585:
4586: for(i=1; i<=nlstate;i++)
4587: for(j=1; j<=(nlstate+ndeath);j++){
4588: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4589: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4590: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4591: }
4592: /* fprintf(ficresprob,"\n");
4593: fprintf(ficresprobcov,"\n");
4594: fprintf(ficresprobcor,"\n");
4595: */
4596: xp=vector(1,npar);
4597: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4598: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4599: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4600: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4601: first=1;
4602: fprintf(ficgp,"\n# Routine varprob");
4603: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4604: fprintf(fichtm,"\n");
4605:
4606: 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);
4607: 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);
4608: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4609: and drawn. It helps understanding how is the covariance between two incidences.\
4610: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4611: 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. \
4612: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4613: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4614: standard deviations wide on each axis. <br>\
4615: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4616: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4617: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4618:
4619: cov[1]=1;
4620: /* tj=cptcoveff; */
4621: tj = (int) pow(2,cptcoveff);
4622: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4623: j1=0;
4624: for(j1=1; j1<=tj;j1++){
4625: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4626: /*j1++;*/
4627: if (cptcovn>0) {
4628: fprintf(ficresprob, "\n#********** Variable ");
4629: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4630: fprintf(ficresprob, "**********\n#\n");
4631: fprintf(ficresprobcov, "\n#********** Variable ");
4632: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4633: fprintf(ficresprobcov, "**********\n#\n");
4634:
4635: fprintf(ficgp, "\n#********** Variable ");
4636: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4637: fprintf(ficgp, "**********\n#\n");
4638:
4639:
4640: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4641: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4642: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4643:
4644: fprintf(ficresprobcor, "\n#********** Variable ");
4645: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4646: fprintf(ficresprobcor, "**********\n#");
4647: }
4648:
4649: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4650: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4651: gp=vector(1,(nlstate)*(nlstate+ndeath));
4652: gm=vector(1,(nlstate)*(nlstate+ndeath));
4653: for (age=bage; age<=fage; age ++){
4654: cov[2]=age;
4655: if(nagesqr==1)
4656: cov[3]= age*age;
4657: for (k=1; k<=cptcovn;k++) {
4658: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4659: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4660: * 1 1 1 1 1
4661: * 2 2 1 1 1
4662: * 3 1 2 1 1
4663: */
4664: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4665: }
4666: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4667: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4668: for (k=1; k<=cptcovprod;k++)
4669: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4670:
4671:
4672: for(theta=1; theta <=npar; theta++){
4673: for(i=1; i<=npar; i++)
4674: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4675:
4676: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4677:
4678: k=0;
4679: for(i=1; i<= (nlstate); i++){
4680: for(j=1; j<=(nlstate+ndeath);j++){
4681: k=k+1;
4682: gp[k]=pmmij[i][j];
4683: }
4684: }
4685:
4686: for(i=1; i<=npar; i++)
4687: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4688:
4689: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4690: k=0;
4691: for(i=1; i<=(nlstate); i++){
4692: for(j=1; j<=(nlstate+ndeath);j++){
4693: k=k+1;
4694: gm[k]=pmmij[i][j];
4695: }
4696: }
4697:
4698: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4699: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4700: }
4701:
4702: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4703: for(theta=1; theta <=npar; theta++)
4704: trgradg[j][theta]=gradg[theta][j];
4705:
4706: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4707: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4708:
4709: pmij(pmmij,cov,ncovmodel,x,nlstate);
4710:
4711: k=0;
4712: for(i=1; i<=(nlstate); i++){
4713: for(j=1; j<=(nlstate+ndeath);j++){
4714: k=k+1;
4715: mu[k][(int) age]=pmmij[i][j];
4716: }
4717: }
4718: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4719: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4720: varpij[i][j][(int)age] = doldm[i][j];
4721:
4722: /*printf("\n%d ",(int)age);
4723: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4724: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4725: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4726: }*/
4727:
4728: fprintf(ficresprob,"\n%d ",(int)age);
4729: fprintf(ficresprobcov,"\n%d ",(int)age);
4730: fprintf(ficresprobcor,"\n%d ",(int)age);
4731:
4732: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4733: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4734: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4735: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4736: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4737: }
4738: i=0;
4739: for (k=1; k<=(nlstate);k++){
4740: for (l=1; l<=(nlstate+ndeath);l++){
4741: i++;
4742: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4743: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4744: for (j=1; j<=i;j++){
4745: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4746: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4747: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4748: }
4749: }
4750: }/* end of loop for state */
4751: } /* end of loop for age */
4752: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4753: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4754: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4755: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4756:
4757: /* Confidence intervalle of pij */
4758: /*
4759: fprintf(ficgp,"\nunset parametric;unset label");
4760: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4761: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4762: 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);
4763: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4764: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4765: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4766: */
4767:
4768: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4769: first1=1;first2=2;
4770: for (k2=1; k2<=(nlstate);k2++){
4771: for (l2=1; l2<=(nlstate+ndeath);l2++){
4772: if(l2==k2) continue;
4773: j=(k2-1)*(nlstate+ndeath)+l2;
4774: for (k1=1; k1<=(nlstate);k1++){
4775: for (l1=1; l1<=(nlstate+ndeath);l1++){
4776: if(l1==k1) continue;
4777: i=(k1-1)*(nlstate+ndeath)+l1;
4778: if(i<=j) continue;
4779: for (age=bage; age<=fage; age ++){
4780: if ((int)age %5==0){
4781: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4782: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4783: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4784: mu1=mu[i][(int) age]/stepm*YEARM ;
4785: mu2=mu[j][(int) age]/stepm*YEARM;
4786: c12=cv12/sqrt(v1*v2);
4787: /* Computing eigen value of matrix of covariance */
4788: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4789: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4790: if ((lc2 <0) || (lc1 <0) ){
4791: if(first2==1){
4792: first1=0;
4793: 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);
4794: }
4795: 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);
4796: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4797: /* lc2=fabs(lc2); */
4798: }
4799:
4800: /* Eigen vectors */
4801: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4802: /*v21=sqrt(1.-v11*v11); *//* error */
4803: v21=(lc1-v1)/cv12*v11;
4804: v12=-v21;
4805: v22=v11;
4806: tnalp=v21/v11;
4807: if(first1==1){
4808: first1=0;
4809: 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);
4810: }
4811: 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);
4812: /*printf(fignu*/
4813: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4814: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4815: if(first==1){
4816: first=0;
4817: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4818: fprintf(ficgp,"\nset parametric;unset label");
4819: 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);
4820: fprintf(ficgp,"\nset ter svg size 640, 480");
4821: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4822: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4823: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4824: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4825: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4826: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4827: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4828: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4829: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4830: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4831: 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",\
4832: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4833: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4834: }else{
4835: first=0;
4836: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4837: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4838: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4839: 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",\
4840: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4841: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4842: }/* if first */
4843: } /* age mod 5 */
4844: } /* end loop age */
4845: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4846: first=1;
4847: } /*l12 */
4848: } /* k12 */
4849: } /*l1 */
4850: }/* k1 */
4851: /* } */ /* loop covariates */
4852: }
4853: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4854: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4855: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4856: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4857: free_vector(xp,1,npar);
4858: fclose(ficresprob);
4859: fclose(ficresprobcov);
4860: fclose(ficresprobcor);
4861: fflush(ficgp);
4862: fflush(fichtmcov);
4863: }
4864:
4865:
4866: /******************* Printing html file ***********/
4867: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4868: int lastpass, int stepm, int weightopt, char model[],\
4869: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4870: int popforecast, int prevfcast, int estepm , \
4871: double jprev1, double mprev1,double anprev1, double dateprev1, \
4872: double jprev2, double mprev2,double anprev2, double dateprev2){
4873: int jj1, k1, i1, cpt;
4874:
4875: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4876: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4877: </ul>");
4878: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4879: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
4880: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
4881: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
4882: fprintf(fichtm,"\
4883: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4884: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
4885: fprintf(fichtm,"\
4886: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4887: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
4888: fprintf(fichtm,"\
4889: - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . 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): \
4890: <a href=\"%s\">%s</a> <br>\n",
4891: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
4892: if(prevfcast==1){
4893: fprintf(fichtm,"\
4894: - Prevalence projections by age and states: \
4895: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
4896: }
4897:
4898: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4899:
4900: m=pow(2,cptcoveff);
4901: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4902:
4903: jj1=0;
4904: for(k1=1; k1<=m;k1++){
4905: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4906: jj1++;
4907: if (cptcovn > 0) {
4908: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4909: for (cpt=1; cpt<=cptcoveff;cpt++){
4910: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4911: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
4912: }
4913: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4914: }
4915: /* aij, bij */
4916: fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), 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> \
4917: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4918: /* Pij */
4919: fprintf(fichtm,"<br>\n- P<sub>ij</sub> 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> \
4920: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4921: /* Quasi-incidences */
4922: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4923: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
4924: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
4925: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
4926: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4927: /* Survival functions (period) in state j */
4928: for(cpt=1; cpt<=nlstate;cpt++){
4929: 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> \
4930: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4931: }
4932: /* State specific survival functions (period) */
4933: for(cpt=1; cpt<=nlstate;cpt++){
4934: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
4935: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4936: <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);
4937: }
4938: /* Period (stable) prevalence in each health state */
4939: for(cpt=1; cpt<=nlstate;cpt++){
4940: 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> \
4941: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4942: }
4943: if(prevfcast==1){
4944: /* Projection of prevalence up to period (stable) prevalence in each health state */
4945: for(cpt=1; cpt<=nlstate;cpt++){
4946: fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %f to %f) up 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> \
4947: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
4948: }
4949: }
4950:
4951: for(cpt=1; cpt<=nlstate;cpt++) {
4952: 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> \
4953: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
4954: }
4955: /* } /\* end i1 *\/ */
4956: }/* End k1 */
4957: fprintf(fichtm,"</ul>");
4958:
4959: fprintf(fichtm,"\
4960: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4961: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
4962: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
4963: But because parameters are usually highly correlated (a higher incidence of disability \
4964: and a higher incidence of recovery can give very close observed transition) it might \
4965: be very useful to look not only at linear confidence intervals estimated from the \
4966: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4967: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4968: covariance matrix of the one-step probabilities. \
4969: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
4970:
4971: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4972: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
4973: fprintf(fichtm,"\
4974: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4975: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
4976:
4977: fprintf(fichtm,"\
4978: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4979: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
4980: fprintf(fichtm,"\
4981: - 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): \
4982: <a href=\"%s\">%s</a> <br>\n</li>",
4983: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
4984: fprintf(fichtm,"\
4985: - (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): \
4986: <a href=\"%s\">%s</a> <br>\n</li>",
4987: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
4988: fprintf(fichtm,"\
4989: - 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",
4990: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
4991: fprintf(fichtm,"\
4992: - 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",
4993: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
4994: fprintf(fichtm,"\
4995: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4996: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
4997:
4998: /* if(popforecast==1) fprintf(fichtm,"\n */
4999: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
5000: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
5001: /* <br>",fileres,fileres,fileres,fileres); */
5002: /* else */
5003: /* 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); */
5004: fflush(fichtm);
5005: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
5006:
5007: m=pow(2,cptcoveff);
5008: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5009:
5010: jj1=0;
5011: for(k1=1; k1<=m;k1++){
5012: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5013: jj1++;
5014: if (cptcovn > 0) {
5015: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5016: for (cpt=1; cpt<=cptcoveff;cpt++)
5017: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5018: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5019: }
5020: for(cpt=1; cpt<=nlstate;cpt++) {
5021: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
5022: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
5023: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
5024: }
5025: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
5026: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
5027: true period expectancies (those weighted with period prevalences are also\
5028: drawn in addition to the population based expectancies computed using\
5029: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
5030: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
5031: /* } /\* end i1 *\/ */
5032: }/* End k1 */
5033: fprintf(fichtm,"</ul>");
5034: fflush(fichtm);
5035: }
5036:
5037: /******************* Gnuplot file **************/
5038: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
5039:
5040: char dirfileres[132],optfileres[132];
5041: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
5042: int lv=0, vlv=0, kl=0;
5043: int ng=0;
5044: int vpopbased;
5045: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
5046: /* printf("Problem with file %s",optionfilegnuplot); */
5047: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
5048: /* } */
5049:
5050: /*#ifdef windows */
5051: fprintf(ficgp,"cd \"%s\" \n",pathc);
5052: /*#endif */
5053: m=pow(2,cptcoveff);
5054:
5055: /* Contribution to likelihood */
5056: /* Plot the probability implied in the likelihood */
5057: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5058: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5059: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
5060: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
5061: /* nice for mle=4 plot by number of matrix products.
5062: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5063: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5064: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
5065: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
5066: 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));
5067: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
5068: 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));
5069: for (i=1; i<= nlstate ; i ++) {
5070: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
5071: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5072: 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);
5073: for (j=2; j<= nlstate+ndeath ; j ++) {
5074: 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);
5075: }
5076: fprintf(ficgp,";\nset out; unset ylabel;\n");
5077: }
5078: /* 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 */
5079: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5080: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
5081: fprintf(ficgp,"\nset out;unset log\n");
5082: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5083:
5084: strcpy(dirfileres,optionfilefiname);
5085: strcpy(optfileres,"vpl");
5086: /* 1eme*/
5087: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5088: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5089: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5090: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5091: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5092: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5093: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5094: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5095: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5096: vlv= nbcode[Tvaraff[lv]][lv];
5097: fprintf(ficgp," V%d=%d ",k,vlv);
5098: }
5099: fprintf(ficgp,"\n#\n");
5100:
5101: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5102: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5103: fprintf(ficgp,"set xlabel \"Age\" \n\
5104: set ylabel \"Probability\" \n\
5105: set ter svg size 640, 480\n\
5106: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5107:
5108: for (i=1; i<= nlstate ; i ++) {
5109: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5110: else fprintf(ficgp," %%*lf (%%*lf)");
5111: }
5112: 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);
5113: for (i=1; i<= nlstate ; i ++) {
5114: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5115: else fprintf(ficgp," %%*lf (%%*lf)");
5116: }
5117: 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);
5118: for (i=1; i<= nlstate ; i ++) {
5119: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5120: else fprintf(ficgp," %%*lf (%%*lf)");
5121: }
5122: 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));
5123: fprintf(ficgp,"\nset out \n");
5124: } /* k1 */
5125: } /* cpt */
5126: /*2 eme*/
5127: for (k1=1; k1<= m ; k1 ++) {
5128: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5129: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5130: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5131: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5132: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5133: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5134: vlv= nbcode[Tvaraff[lv]][lv];
5135: fprintf(ficgp," V%d=%d ",k,vlv);
5136: }
5137: fprintf(ficgp,"\n#\n");
5138:
5139: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5140: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5141: if(vpopbased==0)
5142: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5143: else
5144: fprintf(ficgp,"\nreplot ");
5145: for (i=1; i<= nlstate+1 ; i ++) {
5146: k=2*i;
5147: 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);
5148: for (j=1; j<= nlstate+1 ; j ++) {
5149: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5150: else fprintf(ficgp," %%*lf (%%*lf)");
5151: }
5152: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5153: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5154: 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);
5155: for (j=1; j<= nlstate+1 ; j ++) {
5156: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5157: else fprintf(ficgp," %%*lf (%%*lf)");
5158: }
5159: fprintf(ficgp,"\" t\"\" w l lt 0,");
5160: 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);
5161: for (j=1; j<= nlstate+1 ; j ++) {
5162: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5163: else fprintf(ficgp," %%*lf (%%*lf)");
5164: }
5165: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5166: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5167: } /* state */
5168: } /* vpopbased */
5169: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5170: } /* k1 */
5171:
5172:
5173: /*3eme*/
5174: for (k1=1; k1<= m ; k1 ++) {
5175: for (cpt=1; cpt<= nlstate ; cpt ++) {
5176: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5177: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5178: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5179: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5180: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5181: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5182: vlv= nbcode[Tvaraff[lv]][lv];
5183: fprintf(ficgp," V%d=%d ",k,vlv);
5184: }
5185: fprintf(ficgp,"\n#\n");
5186:
5187: /* k=2+nlstate*(2*cpt-2); */
5188: k=2+(nlstate+1)*(cpt-1);
5189: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5190: fprintf(ficgp,"set ter svg size 640, 480\n\
5191: 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);
5192: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5193: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5194: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5195: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5196: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5197: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5198:
5199: */
5200: for (i=1; i< nlstate ; i ++) {
5201: 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);
5202: /* 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);*/
5203:
5204: }
5205: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5206: }
5207: }
5208:
5209: /* Survival functions (period) from state i in state j by initial state i */
5210: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5211: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5212: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5213: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5214: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5215: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5216: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5217: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5218: vlv= nbcode[Tvaraff[lv]][lv];
5219: fprintf(ficgp," V%d=%d ",k,vlv);
5220: }
5221: fprintf(ficgp,"\n#\n");
5222:
5223: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5224: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5225: set ter svg size 640, 480\n\
5226: unset log y\n\
5227: plot [%.f:%.f] ", ageminpar, agemaxpar);
5228: k=3;
5229: for (i=1; i<= nlstate ; i ++){
5230: if(i==1)
5231: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5232: else
5233: fprintf(ficgp,", '' ");
5234: l=(nlstate+ndeath)*(i-1)+1;
5235: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5236: for (j=2; j<= nlstate+ndeath ; j ++)
5237: fprintf(ficgp,"+$%d",k+l+j-1);
5238: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5239: } /* nlstate */
5240: fprintf(ficgp,"\nset out\n");
5241: } /* end cpt state*/
5242: } /* end covariate */
5243:
5244: /* Survival functions (period) from state i in state j by final state j */
5245: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5246: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5247: 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);
5248: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5249: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5250: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5251: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5252: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5253: vlv= nbcode[Tvaraff[lv]][lv];
5254: fprintf(ficgp," V%d=%d ",k,vlv);
5255: }
5256: fprintf(ficgp,"\n#\n");
5257:
5258: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5259: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5260: set ter svg size 640, 480\n\
5261: unset log y\n\
5262: plot [%.f:%.f] ", ageminpar, agemaxpar);
5263: k=3;
5264: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5265: if(j==1)
5266: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5267: else
5268: fprintf(ficgp,", '' ");
5269: l=(nlstate+ndeath)*(cpt-1) +j;
5270: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5271: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5272: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5273: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5274: } /* nlstate */
5275: fprintf(ficgp,", '' ");
5276: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5277: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5278: l=(nlstate+ndeath)*(cpt-1) +j;
5279: if(j < nlstate)
5280: fprintf(ficgp,"$%d +",k+l);
5281: else
5282: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5283: }
5284: fprintf(ficgp,"\nset out\n");
5285: } /* end cpt state*/
5286: } /* end covariate */
5287:
5288: /* CV preval stable (period) for each covariate */
5289: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5290: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5291: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5292: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5293: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5294: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5295: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5296: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5297: vlv= nbcode[Tvaraff[lv]][lv];
5298: fprintf(ficgp," V%d=%d ",k,vlv);
5299: }
5300: fprintf(ficgp,"\n#\n");
5301:
5302: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5303: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5304: set ter svg size 640, 480\n\
5305: unset log y\n\
5306: plot [%.f:%.f] ", ageminpar, agemaxpar);
5307: k=3; /* Offset */
5308: for (i=1; i<= nlstate ; i ++){
5309: if(i==1)
5310: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5311: else
5312: fprintf(ficgp,", '' ");
5313: l=(nlstate+ndeath)*(i-1)+1;
5314: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5315: for (j=2; j<= nlstate ; j ++)
5316: fprintf(ficgp,"+$%d",k+l+j-1);
5317: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5318: } /* nlstate */
5319: fprintf(ficgp,"\nset out\n");
5320: } /* end cpt state*/
5321: } /* end covariate */
5322:
5323: if(prevfcast==1){
5324: /* Projection from cross-sectional to stable (period) for each covariate */
5325:
5326: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5327: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5328: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5329: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5330: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5331: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5332: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5333: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5334: vlv= nbcode[Tvaraff[lv]][lv];
5335: fprintf(ficgp," V%d=%d ",k,vlv);
5336: }
5337: fprintf(ficgp,"\n#\n");
5338:
5339: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
5340: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
5341: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
5342: set ter svg size 640, 480\n\
5343: unset log y\n\
5344: plot [%.f:%.f] ", ageminpar, agemaxpar);
5345: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
5346: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5347: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5348: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5349: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5350: if(i==1){
5351: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
5352: }else{
5353: fprintf(ficgp,",\\\n '' ");
5354: }
5355: if(cptcoveff ==0){ /* No covariate */
5356: fprintf(ficgp," u 2:("); /* Age is in 2 */
5357: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
5358: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
5359: if(i==nlstate+1)
5360: fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
5361: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,cpt );
5362: else
5363: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
5364: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5365: }else{
5366: fprintf(ficgp,"u 6:(("); /* Age is in 6 */
5367: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5368: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5369: kl=0;
5370: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
5371: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5372: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5373: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5374: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5375: vlv= nbcode[Tvaraff[lv]][lv];
5376: kl++;
5377: /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
5378: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5379: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5380: /* '' u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
5381: if(k==cptcoveff)
5382: if(i==nlstate+1)
5383: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5384: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,cpt );
5385: else
5386: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5387: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5388: else{
5389: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
5390: kl++;
5391: }
5392: } /* end covariate */
5393: } /* end if covariate */
5394: } /* nlstate */
5395: fprintf(ficgp,"\nset out\n");
5396: } /* end cpt state*/
5397: } /* end covariate */
5398: } /* End if prevfcast */
5399:
5400:
5401: /* proba elementaires */
5402: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5403: for(i=1,jk=1; i <=nlstate; i++){
5404: fprintf(ficgp,"# initial state %d\n",i);
5405: for(k=1; k <=(nlstate+ndeath); k++){
5406: if (k != i) {
5407: fprintf(ficgp,"# current state %d\n",k);
5408: for(j=1; j <=ncovmodel; j++){
5409: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5410: jk++;
5411: }
5412: fprintf(ficgp,"\n");
5413: }
5414: }
5415: }
5416: fprintf(ficgp,"##############\n#\n");
5417:
5418: /*goto avoid;*/
5419: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5420: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5421: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5422: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5423: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5424: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5425: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5426: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5427: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5428: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5429: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5430: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5431: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5432: fprintf(ficgp,"#\n");
5433: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5434: fprintf(ficgp,"# ng=%d\n",ng);
5435: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5436: for(jk=1; jk <=m; jk++) {
5437: fprintf(ficgp,"# jk=%d\n",jk);
5438: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5439: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5440: if (ng==1){
5441: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5442: fprintf(ficgp,"\nunset log y");
5443: }else if (ng==2){
5444: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5445: fprintf(ficgp,"\nset log y");
5446: }else if (ng==3){
5447: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5448: fprintf(ficgp,"\nset log y");
5449: }else
5450: fprintf(ficgp,"\nunset title ");
5451: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5452: i=1;
5453: for(k2=1; k2<=nlstate; k2++) {
5454: k3=i;
5455: for(k=1; k<=(nlstate+ndeath); k++) {
5456: if (k != k2){
5457: switch( ng) {
5458: case 1:
5459: if(nagesqr==0)
5460: fprintf(ficgp," p%d+p%d*x",i,i+1);
5461: else /* nagesqr =1 */
5462: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5463: break;
5464: case 2: /* ng=2 */
5465: if(nagesqr==0)
5466: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5467: else /* nagesqr =1 */
5468: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5469: break;
5470: case 3:
5471: if(nagesqr==0)
5472: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5473: else /* nagesqr =1 */
5474: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5475: break;
5476: }
5477: ij=1;/* To be checked else nbcode[0][0] wrong */
5478: for(j=3; j <=ncovmodel-nagesqr; j++) {
5479: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5480: if(ij <=cptcovage) { /* Bug valgrind */
5481: if((j-2)==Tage[ij]) { /* Bug valgrind */
5482: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5483: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5484: ij++;
5485: }
5486: }
5487: else
5488: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5489: }
5490: if(ng != 1){
5491: fprintf(ficgp,")/(1");
5492:
5493: for(k1=1; k1 <=nlstate; k1++){
5494: if(nagesqr==0)
5495: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5496: else /* nagesqr =1 */
5497: 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);
5498:
5499: ij=1;
5500: for(j=3; j <=ncovmodel-nagesqr; j++){
5501: if(ij <=cptcovage) { /* Bug valgrind */
5502: if((j-2)==Tage[ij]) { /* Bug valgrind */
5503: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5504: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5505: ij++;
5506: }
5507: }
5508: else
5509: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5510: }
5511: fprintf(ficgp,")");
5512: }
5513: fprintf(ficgp,")");
5514: if(ng ==2)
5515: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5516: else /* ng= 3 */
5517: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5518: }else{ /* end ng <> 1 */
5519: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5520: }
5521: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5522: i=i+ncovmodel;
5523: }
5524: } /* end k */
5525: } /* end k2 */
5526: fprintf(ficgp,"\n set out\n");
5527: } /* end jk */
5528: } /* end ng */
5529: /* avoid: */
5530: fflush(ficgp);
5531: } /* end gnuplot */
5532:
5533:
5534: /*************** Moving average **************/
5535: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5536:
5537: int i, cpt, cptcod;
5538: int modcovmax =1;
5539: int mobilavrange, mob;
5540: double age;
5541:
5542: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5543: a covariate has 2 modalities */
5544: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5545:
5546: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5547: if(mobilav==1) mobilavrange=5; /* default */
5548: else mobilavrange=mobilav;
5549: for (age=bage; age<=fage; age++)
5550: for (i=1; i<=nlstate;i++)
5551: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5552: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5553: /* We keep the original values on the extreme ages bage, fage and for
5554: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5555: we use a 5 terms etc. until the borders are no more concerned.
5556: */
5557: for (mob=3;mob <=mobilavrange;mob=mob+2){
5558: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5559: for (i=1; i<=nlstate;i++){
5560: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5561: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5562: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5563: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5564: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5565: }
5566: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5567: }
5568: }
5569: }/* end age */
5570: }/* end mob */
5571: }else return -1;
5572: return 0;
5573: }/* End movingaverage */
5574:
5575:
5576: /************** Forecasting ******************/
5577: 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){
5578: /* proj1, year, month, day of starting projection
5579: agemin, agemax range of age
5580: dateprev1 dateprev2 range of dates during which prevalence is computed
5581: anproj2 year of en of projection (same day and month as proj1).
5582: */
5583: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5584: double agec; /* generic age */
5585: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5586: double *popeffectif,*popcount;
5587: double ***p3mat;
5588: double ***mobaverage;
5589: char fileresf[FILENAMELENGTH];
5590:
5591: agelim=AGESUP;
5592: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
5593: in each health status at the date of interview (if between dateprev1 and dateprev2).
5594: We still use firstpass and lastpass as another selection.
5595: */
5596: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5597:
5598: strcpy(fileresf,"F_");
5599: strcat(fileresf,fileresu);
5600: if((ficresf=fopen(fileresf,"w"))==NULL) {
5601: printf("Problem with forecast resultfile: %s\n", fileresf);
5602: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5603: }
5604: printf("Computing forecasting: result on file '%s' \n", fileresf);
5605: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5606:
5607: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5608:
5609: if (mobilav!=0) {
5610: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5611: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5612: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5613: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5614: }
5615: }
5616:
5617: stepsize=(int) (stepm+YEARM-1)/YEARM;
5618: if (stepm<=12) stepsize=1;
5619: if(estepm < stepm){
5620: printf ("Problem %d lower than %d\n",estepm, stepm);
5621: }
5622: else hstepm=estepm;
5623:
5624: hstepm=hstepm/stepm;
5625: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5626: fractional in yp1 */
5627: anprojmean=yp;
5628: yp2=modf((yp1*12),&yp);
5629: mprojmean=yp;
5630: yp1=modf((yp2*30.5),&yp);
5631: jprojmean=yp;
5632: if(jprojmean==0) jprojmean=1;
5633: if(mprojmean==0) jprojmean=1;
5634:
5635: i1=cptcoveff;
5636: if (cptcovn < 1){i1=1;}
5637:
5638: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5639:
5640: fprintf(ficresf,"#****** Routine prevforecast **\n");
5641:
5642: /* if (h==(int)(YEARM*yearp)){ */
5643: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5644: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5645: k=k+1;
5646: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
5647: for(j=1;j<=cptcoveff;j++) {
5648: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5649: }
5650: fprintf(ficresf," yearproj age");
5651: for(j=1; j<=nlstate+ndeath;j++){
5652: for(i=1; i<=nlstate;i++)
5653: fprintf(ficresf," p%d%d",i,j);
5654: fprintf(ficresf," p.%d",j);
5655: }
5656: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5657: fprintf(ficresf,"\n");
5658: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5659:
5660: for (agec=fage; agec>=(ageminpar-1); agec--){
5661: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5662: nhstepm = nhstepm/hstepm;
5663: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5664: oldm=oldms;savm=savms;
5665: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5666:
5667: for (h=0; h<=nhstepm; h++){
5668: if (h*hstepm/YEARM*stepm ==yearp) {
5669: fprintf(ficresf,"\n");
5670: for(j=1;j<=cptcoveff;j++)
5671: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5672: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5673: }
5674: for(j=1; j<=nlstate+ndeath;j++) {
5675: ppij=0.;
5676: for(i=1; i<=nlstate;i++) {
5677: if (mobilav==1)
5678: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5679: else {
5680: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5681: }
5682: if (h*hstepm/YEARM*stepm== yearp) {
5683: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5684: }
5685: } /* end i */
5686: if (h*hstepm/YEARM*stepm==yearp) {
5687: fprintf(ficresf," %.3f", ppij);
5688: }
5689: }/* end j */
5690: } /* end h */
5691: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5692: } /* end agec */
5693: } /* end yearp */
5694: } /* end cptcod */
5695: } /* end cptcov */
5696:
5697: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5698:
5699: fclose(ficresf);
5700: }
5701:
5702: /************** Forecasting *****not tested NB*************/
5703: 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){
5704:
5705: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5706: int *popage;
5707: double calagedatem, agelim, kk1, kk2;
5708: double *popeffectif,*popcount;
5709: double ***p3mat,***tabpop,***tabpopprev;
5710: double ***mobaverage;
5711: char filerespop[FILENAMELENGTH];
5712:
5713: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5714: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5715: agelim=AGESUP;
5716: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5717:
5718: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5719:
5720:
5721: strcpy(filerespop,"POP_");
5722: strcat(filerespop,fileresu);
5723: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5724: printf("Problem with forecast resultfile: %s\n", filerespop);
5725: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5726: }
5727: printf("Computing forecasting: result on file '%s' \n", filerespop);
5728: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5729:
5730: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5731:
5732: if (mobilav!=0) {
5733: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5734: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5735: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5736: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5737: }
5738: }
5739:
5740: stepsize=(int) (stepm+YEARM-1)/YEARM;
5741: if (stepm<=12) stepsize=1;
5742:
5743: agelim=AGESUP;
5744:
5745: hstepm=1;
5746: hstepm=hstepm/stepm;
5747:
5748: if (popforecast==1) {
5749: if((ficpop=fopen(popfile,"r"))==NULL) {
5750: printf("Problem with population file : %s\n",popfile);exit(0);
5751: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5752: }
5753: popage=ivector(0,AGESUP);
5754: popeffectif=vector(0,AGESUP);
5755: popcount=vector(0,AGESUP);
5756:
5757: i=1;
5758: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5759:
5760: imx=i;
5761: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5762: }
5763:
5764: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5765: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5766: k=k+1;
5767: fprintf(ficrespop,"\n#******");
5768: for(j=1;j<=cptcoveff;j++) {
5769: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5770: }
5771: fprintf(ficrespop,"******\n");
5772: fprintf(ficrespop,"# Age");
5773: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5774: if (popforecast==1) fprintf(ficrespop," [Population]");
5775:
5776: for (cpt=0; cpt<=0;cpt++) {
5777: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5778:
5779: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5780: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5781: nhstepm = nhstepm/hstepm;
5782:
5783: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5784: oldm=oldms;savm=savms;
5785: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5786:
5787: for (h=0; h<=nhstepm; h++){
5788: if (h==(int) (calagedatem+YEARM*cpt)) {
5789: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5790: }
5791: for(j=1; j<=nlstate+ndeath;j++) {
5792: kk1=0.;kk2=0;
5793: for(i=1; i<=nlstate;i++) {
5794: if (mobilav==1)
5795: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5796: else {
5797: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5798: }
5799: }
5800: if (h==(int)(calagedatem+12*cpt)){
5801: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5802: /*fprintf(ficrespop," %.3f", kk1);
5803: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5804: }
5805: }
5806: for(i=1; i<=nlstate;i++){
5807: kk1=0.;
5808: for(j=1; j<=nlstate;j++){
5809: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5810: }
5811: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5812: }
5813:
5814: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5815: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5816: }
5817: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5818: }
5819: }
5820:
5821: /******/
5822:
5823: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5824: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5825: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5826: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5827: nhstepm = nhstepm/hstepm;
5828:
5829: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5830: oldm=oldms;savm=savms;
5831: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5832: for (h=0; h<=nhstepm; h++){
5833: if (h==(int) (calagedatem+YEARM*cpt)) {
5834: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5835: }
5836: for(j=1; j<=nlstate+ndeath;j++) {
5837: kk1=0.;kk2=0;
5838: for(i=1; i<=nlstate;i++) {
5839: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5840: }
5841: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5842: }
5843: }
5844: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5845: }
5846: }
5847: }
5848: }
5849:
5850: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5851:
5852: if (popforecast==1) {
5853: free_ivector(popage,0,AGESUP);
5854: free_vector(popeffectif,0,AGESUP);
5855: free_vector(popcount,0,AGESUP);
5856: }
5857: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5858: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5859: fclose(ficrespop);
5860: } /* End of popforecast */
5861:
5862: int fileappend(FILE *fichier, char *optionfich)
5863: {
5864: if((fichier=fopen(optionfich,"a"))==NULL) {
5865: printf("Problem with file: %s\n", optionfich);
5866: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5867: return (0);
5868: }
5869: fflush(fichier);
5870: return (1);
5871: }
5872:
5873:
5874: /**************** function prwizard **********************/
5875: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5876: {
5877:
5878: /* Wizard to print covariance matrix template */
5879:
5880: char ca[32], cb[32];
5881: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5882: int numlinepar;
5883:
5884: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5885: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5886: for(i=1; i <=nlstate; i++){
5887: jj=0;
5888: for(j=1; j <=nlstate+ndeath; j++){
5889: if(j==i) continue;
5890: jj++;
5891: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5892: printf("%1d%1d",i,j);
5893: fprintf(ficparo,"%1d%1d",i,j);
5894: for(k=1; k<=ncovmodel;k++){
5895: /* printf(" %lf",param[i][j][k]); */
5896: /* fprintf(ficparo," %lf",param[i][j][k]); */
5897: printf(" 0.");
5898: fprintf(ficparo," 0.");
5899: }
5900: printf("\n");
5901: fprintf(ficparo,"\n");
5902: }
5903: }
5904: printf("# Scales (for hessian or gradient estimation)\n");
5905: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5906: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5907: for(i=1; i <=nlstate; i++){
5908: jj=0;
5909: for(j=1; j <=nlstate+ndeath; j++){
5910: if(j==i) continue;
5911: jj++;
5912: fprintf(ficparo,"%1d%1d",i,j);
5913: printf("%1d%1d",i,j);
5914: fflush(stdout);
5915: for(k=1; k<=ncovmodel;k++){
5916: /* printf(" %le",delti3[i][j][k]); */
5917: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5918: printf(" 0.");
5919: fprintf(ficparo," 0.");
5920: }
5921: numlinepar++;
5922: printf("\n");
5923: fprintf(ficparo,"\n");
5924: }
5925: }
5926: printf("# Covariance matrix\n");
5927: /* # 121 Var(a12)\n\ */
5928: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5929: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5930: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5931: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5932: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5933: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5934: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5935: fflush(stdout);
5936: fprintf(ficparo,"# Covariance matrix\n");
5937: /* # 121 Var(a12)\n\ */
5938: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5939: /* # ...\n\ */
5940: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5941:
5942: for(itimes=1;itimes<=2;itimes++){
5943: jj=0;
5944: for(i=1; i <=nlstate; i++){
5945: for(j=1; j <=nlstate+ndeath; j++){
5946: if(j==i) continue;
5947: for(k=1; k<=ncovmodel;k++){
5948: jj++;
5949: ca[0]= k+'a'-1;ca[1]='\0';
5950: if(itimes==1){
5951: printf("#%1d%1d%d",i,j,k);
5952: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5953: }else{
5954: printf("%1d%1d%d",i,j,k);
5955: fprintf(ficparo,"%1d%1d%d",i,j,k);
5956: /* printf(" %.5le",matcov[i][j]); */
5957: }
5958: ll=0;
5959: for(li=1;li <=nlstate; li++){
5960: for(lj=1;lj <=nlstate+ndeath; lj++){
5961: if(lj==li) continue;
5962: for(lk=1;lk<=ncovmodel;lk++){
5963: ll++;
5964: if(ll<=jj){
5965: cb[0]= lk +'a'-1;cb[1]='\0';
5966: if(ll<jj){
5967: if(itimes==1){
5968: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5969: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5970: }else{
5971: printf(" 0.");
5972: fprintf(ficparo," 0.");
5973: }
5974: }else{
5975: if(itimes==1){
5976: printf(" Var(%s%1d%1d)",ca,i,j);
5977: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5978: }else{
5979: printf(" 0.");
5980: fprintf(ficparo," 0.");
5981: }
5982: }
5983: }
5984: } /* end lk */
5985: } /* end lj */
5986: } /* end li */
5987: printf("\n");
5988: fprintf(ficparo,"\n");
5989: numlinepar++;
5990: } /* end k*/
5991: } /*end j */
5992: } /* end i */
5993: } /* end itimes */
5994:
5995: } /* end of prwizard */
5996: /******************* Gompertz Likelihood ******************************/
5997: double gompertz(double x[])
5998: {
5999: double A,B,L=0.0,sump=0.,num=0.;
6000: int i,n=0; /* n is the size of the sample */
6001:
6002: for (i=0;i<=imx-1 ; i++) {
6003: sump=sump+weight[i];
6004: /* sump=sump+1;*/
6005: num=num+1;
6006: }
6007:
6008:
6009: /* for (i=0; i<=imx; i++)
6010: 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]);*/
6011:
6012: for (i=1;i<=imx ; i++)
6013: {
6014: if (cens[i] == 1 && wav[i]>1)
6015: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
6016:
6017: if (cens[i] == 0 && wav[i]>1)
6018: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
6019: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
6020:
6021: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6022: if (wav[i] > 1 ) { /* ??? */
6023: L=L+A*weight[i];
6024: /* 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]);*/
6025: }
6026: }
6027:
6028: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6029:
6030: return -2*L*num/sump;
6031: }
6032:
6033: #ifdef GSL
6034: /******************* Gompertz_f Likelihood ******************************/
6035: double gompertz_f(const gsl_vector *v, void *params)
6036: {
6037: double A,B,LL=0.0,sump=0.,num=0.;
6038: double *x= (double *) v->data;
6039: int i,n=0; /* n is the size of the sample */
6040:
6041: for (i=0;i<=imx-1 ; i++) {
6042: sump=sump+weight[i];
6043: /* sump=sump+1;*/
6044: num=num+1;
6045: }
6046:
6047:
6048: /* for (i=0; i<=imx; i++)
6049: 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]);*/
6050: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
6051: for (i=1;i<=imx ; i++)
6052: {
6053: if (cens[i] == 1 && wav[i]>1)
6054: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
6055:
6056: if (cens[i] == 0 && wav[i]>1)
6057: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6058: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6059:
6060: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6061: if (wav[i] > 1 ) { /* ??? */
6062: LL=LL+A*weight[i];
6063: /* 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]);*/
6064: }
6065: }
6066:
6067: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6068: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6069:
6070: return -2*LL*num/sump;
6071: }
6072: #endif
6073:
6074: /******************* Printing html file ***********/
6075: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
6076: int lastpass, int stepm, int weightopt, char model[],\
6077: int imx, double p[],double **matcov,double agemortsup){
6078: int i,k;
6079:
6080: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
6081: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
6082: for (i=1;i<=2;i++)
6083: 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]));
6084: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
6085: fprintf(fichtm,"</ul>");
6086:
6087: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
6088:
6089: 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>");
6090:
6091: for (k=agegomp;k<(agemortsup-2);k++)
6092: 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]);
6093:
6094:
6095: fflush(fichtm);
6096: }
6097:
6098: /******************* Gnuplot file **************/
6099: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
6100:
6101: char dirfileres[132],optfileres[132];
6102:
6103: int ng;
6104:
6105:
6106: /*#ifdef windows */
6107: fprintf(ficgp,"cd \"%s\" \n",pathc);
6108: /*#endif */
6109:
6110:
6111: strcpy(dirfileres,optionfilefiname);
6112: strcpy(optfileres,"vpl");
6113: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
6114: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
6115: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
6116: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
6117: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
6118:
6119: }
6120:
6121: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
6122: {
6123:
6124: /*-------- data file ----------*/
6125: FILE *fic;
6126: char dummy[]=" ";
6127: int i=0, j=0, n=0;
6128: int linei, month, year,iout;
6129: char line[MAXLINE], linetmp[MAXLINE];
6130: char stra[MAXLINE], strb[MAXLINE];
6131: char *stratrunc;
6132: int lstra;
6133:
6134:
6135: if((fic=fopen(datafile,"r"))==NULL) {
6136: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
6137: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
6138: }
6139:
6140: i=1;
6141: linei=0;
6142: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
6143: linei=linei+1;
6144: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
6145: if(line[j] == '\t')
6146: line[j] = ' ';
6147: }
6148: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
6149: ;
6150: };
6151: line[j+1]=0; /* Trims blanks at end of line */
6152: if(line[0]=='#'){
6153: fprintf(ficlog,"Comment line\n%s\n",line);
6154: printf("Comment line\n%s\n",line);
6155: continue;
6156: }
6157: trimbb(linetmp,line); /* Trims multiple blanks in line */
6158: strcpy(line, linetmp);
6159:
6160:
6161: for (j=maxwav;j>=1;j--){
6162: cutv(stra, strb, line, ' ');
6163: if(strb[0]=='.') { /* Missing status */
6164: lval=-1;
6165: }else{
6166: errno=0;
6167: lval=strtol(strb,&endptr,10);
6168: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
6169: if( strb[0]=='\0' || (*endptr != '\0')){
6170: 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);
6171: 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);
6172: return 1;
6173: }
6174: }
6175: s[j][i]=lval;
6176:
6177: strcpy(line,stra);
6178: cutv(stra, strb,line,' ');
6179: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6180: }
6181: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6182: month=99;
6183: year=9999;
6184: }else{
6185: 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);
6186: 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);
6187: return 1;
6188: }
6189: anint[j][i]= (double) year;
6190: mint[j][i]= (double)month;
6191: strcpy(line,stra);
6192: } /* ENd Waves */
6193:
6194: cutv(stra, strb,line,' ');
6195: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6196: }
6197: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6198: month=99;
6199: year=9999;
6200: }else{
6201: 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);
6202: 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);
6203: return 1;
6204: }
6205: andc[i]=(double) year;
6206: moisdc[i]=(double) month;
6207: strcpy(line,stra);
6208:
6209: cutv(stra, strb,line,' ');
6210: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6211: }
6212: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
6213: month=99;
6214: year=9999;
6215: }else{
6216: 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);
6217: 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);
6218: return 1;
6219: }
6220: if (year==9999) {
6221: 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);
6222: 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);
6223: return 1;
6224:
6225: }
6226: annais[i]=(double)(year);
6227: moisnais[i]=(double)(month);
6228: strcpy(line,stra);
6229:
6230: cutv(stra, strb,line,' ');
6231: errno=0;
6232: dval=strtod(strb,&endptr);
6233: if( strb[0]=='\0' || (*endptr != '\0')){
6234: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6235: 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);
6236: fflush(ficlog);
6237: return 1;
6238: }
6239: weight[i]=dval;
6240: strcpy(line,stra);
6241:
6242: for (j=ncovcol;j>=1;j--){
6243: cutv(stra, strb,line,' ');
6244: if(strb[0]=='.') { /* Missing status */
6245: lval=-1;
6246: }else{
6247: errno=0;
6248: lval=strtol(strb,&endptr,10);
6249: if( strb[0]=='\0' || (*endptr != '\0')){
6250: 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);
6251: 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);
6252: return 1;
6253: }
6254: }
6255: if(lval <-1 || lval >1){
6256: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6257: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6258: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6259: For example, for multinomial values like 1, 2 and 3,\n \
6260: build V1=0 V2=0 for the reference value (1),\n \
6261: V1=1 V2=0 for (2) \n \
6262: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6263: output of IMaCh is often meaningless.\n \
6264: Exiting.\n",lval,linei, i,line,j);
6265: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6266: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6267: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6268: For example, for multinomial values like 1, 2 and 3,\n \
6269: build V1=0 V2=0 for the reference value (1),\n \
6270: V1=1 V2=0 for (2) \n \
6271: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6272: output of IMaCh is often meaningless.\n \
6273: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6274: return 1;
6275: }
6276: covar[j][i]=(double)(lval);
6277: strcpy(line,stra);
6278: }
6279: lstra=strlen(stra);
6280:
6281: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6282: stratrunc = &(stra[lstra-9]);
6283: num[i]=atol(stratrunc);
6284: }
6285: else
6286: num[i]=atol(stra);
6287: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6288: 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;}*/
6289:
6290: i=i+1;
6291: } /* End loop reading data */
6292:
6293: *imax=i-1; /* Number of individuals */
6294: fclose(fic);
6295:
6296: return (0);
6297: /* endread: */
6298: printf("Exiting readdata: ");
6299: fclose(fic);
6300: return (1);
6301:
6302:
6303:
6304: }
6305: void removespace(char *str) {
6306: char *p1 = str, *p2 = str;
6307: do
6308: while (*p2 == ' ')
6309: p2++;
6310: while (*p1++ == *p2++);
6311: }
6312:
6313: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
6314: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6315: * - nagesqr = 1 if age*age in the model, otherwise 0.
6316: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6317: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6318: * - cptcovage number of covariates with age*products =2
6319: * - cptcovs number of simple covariates
6320: * - 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
6321: * which is a new column after the 9 (ncovcol) variables.
6322: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6323: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6324: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6325: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6326: */
6327: {
6328: int i, j, k, ks;
6329: int j1, k1, k2;
6330: char modelsav[80];
6331: char stra[80], strb[80], strc[80], strd[80],stre[80];
6332: char *strpt;
6333:
6334: /*removespace(model);*/
6335: if (strlen(model) >1){ /* If there is at least 1 covariate */
6336: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6337: if (strstr(model,"AGE") !=0){
6338: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6339: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6340: return 1;
6341: }
6342: if (strstr(model,"v") !=0){
6343: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6344: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6345: return 1;
6346: }
6347: strcpy(modelsav,model);
6348: if ((strpt=strstr(model,"age*age")) !=0){
6349: printf(" strpt=%s, model=%s\n",strpt, model);
6350: if(strpt != model){
6351: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6352: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6353: corresponding column of parameters.\n",model);
6354: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6355: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6356: corresponding column of parameters.\n",model); fflush(ficlog);
6357: return 1;
6358: }
6359:
6360: nagesqr=1;
6361: if (strstr(model,"+age*age") !=0)
6362: substrchaine(modelsav, model, "+age*age");
6363: else if (strstr(model,"age*age+") !=0)
6364: substrchaine(modelsav, model, "age*age+");
6365: else
6366: substrchaine(modelsav, model, "age*age");
6367: }else
6368: nagesqr=0;
6369: if (strlen(modelsav) >1){
6370: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6371: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6372: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6373: cptcovt= j+1; /* Number of total covariates in the model, not including
6374: * cst, age and age*age
6375: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6376: /* including age products which are counted in cptcovage.
6377: * but the covariates which are products must be treated
6378: * separately: ncovn=4- 2=2 (V1+V3). */
6379: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6380: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6381:
6382:
6383: /* Design
6384: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6385: * < ncovcol=8 >
6386: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6387: * k= 1 2 3 4 5 6 7 8
6388: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6389: * covar[k,i], value of kth covariate if not including age for individual i:
6390: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6391: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6392: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6393: * Tage[++cptcovage]=k
6394: * if products, new covar are created after ncovcol with k1
6395: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6396: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6397: * 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
6398: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6399: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6400: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6401: * < ncovcol=8 >
6402: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6403: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6404: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6405: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6406: * p Tprod[1]@2={ 6, 5}
6407: *p Tvard[1][1]@4= {7, 8, 5, 6}
6408: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6409: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6410: *How to reorganize?
6411: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6412: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6413: * {2, 1, 4, 8, 5, 6, 3, 7}
6414: * Struct []
6415: */
6416:
6417: /* This loop fills the array Tvar from the string 'model'.*/
6418: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6419: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6420: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6421: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6422: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6423: /* k=1 Tvar[1]=2 (from V2) */
6424: /* k=5 Tvar[5] */
6425: /* for (k=1; k<=cptcovn;k++) { */
6426: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6427: /* } */
6428: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6429: /*
6430: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6431: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6432: Tvar[k]=0;
6433: cptcovage=0;
6434: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6435: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6436: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6437: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6438: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6439: /*scanf("%d",i);*/
6440: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6441: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6442: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6443: /* covar is not filled and then is empty */
6444: cptcovprod--;
6445: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6446: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6447: cptcovage++; /* Sums the number of covariates which include age as a product */
6448: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6449: /*printf("stre=%s ", stre);*/
6450: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6451: cptcovprod--;
6452: cutl(stre,strb,strc,'V');
6453: Tvar[k]=atoi(stre);
6454: cptcovage++;
6455: Tage[cptcovage]=k;
6456: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6457: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6458: cptcovn++;
6459: cptcovprodnoage++;k1++;
6460: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6461: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6462: because this model-covariate is a construction we invent a new column
6463: ncovcol + k1
6464: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6465: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6466: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6467: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6468: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6469: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6470: k2=k2+2;
6471: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6472: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6473: for (i=1; i<=lastobs;i++){
6474: /* Computes the new covariate which is a product of
6475: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6476: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6477: }
6478: } /* End age is not in the model */
6479: } /* End if model includes a product */
6480: else { /* no more sum */
6481: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6482: /* scanf("%d",i);*/
6483: cutl(strd,strc,strb,'V');
6484: ks++; /**< Number of simple covariates */
6485: cptcovn++;
6486: Tvar[k]=atoi(strd);
6487: }
6488: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6489: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6490: scanf("%d",i);*/
6491: } /* end of loop + on total covariates */
6492: } /* end if strlen(modelsave == 0) age*age might exist */
6493: } /* end if strlen(model == 0) */
6494:
6495: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6496: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6497:
6498: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6499: printf("cptcovprod=%d ", cptcovprod);
6500: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6501:
6502: scanf("%d ",i);*/
6503:
6504:
6505: return (0); /* with covar[new additional covariate if product] and Tage if age */
6506: /*endread:*/
6507: printf("Exiting decodemodel: ");
6508: return (1);
6509: }
6510:
6511: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6512: {
6513: int i, m;
6514:
6515: for (i=1; i<=imx; i++) {
6516: for(m=2; (m<= maxwav); m++) {
6517: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6518: anint[m][i]=9999;
6519: s[m][i]=-1;
6520: }
6521: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6522: *nberr = *nberr + 1;
6523: 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);
6524: 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);
6525: s[m][i]=-1;
6526: }
6527: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6528: (*nberr)++;
6529: 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]);
6530: 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]);
6531: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6532: }
6533: }
6534: }
6535:
6536: for (i=1; i<=imx; i++) {
6537: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6538: for(m=firstpass; (m<= lastpass); m++){
6539: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6540: if (s[m][i] >= nlstate+1) {
6541: if(agedc[i]>0){
6542: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6543: agev[m][i]=agedc[i];
6544: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6545: }else {
6546: if ((int)andc[i]!=9999){
6547: nbwarn++;
6548: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6549: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6550: agev[m][i]=-1;
6551: }
6552: }
6553: } /* agedc > 0 */
6554: }
6555: else if(s[m][i] !=9){ /* Standard case, age in fractional
6556: years but with the precision of a month */
6557: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6558: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6559: agev[m][i]=1;
6560: else if(agev[m][i] < *agemin){
6561: *agemin=agev[m][i];
6562: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6563: }
6564: else if(agev[m][i] >*agemax){
6565: *agemax=agev[m][i];
6566: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6567: }
6568: /*agev[m][i]=anint[m][i]-annais[i];*/
6569: /* agev[m][i] = age[i]+2*m;*/
6570: }
6571: else { /* =9 */
6572: agev[m][i]=1;
6573: s[m][i]=-1;
6574: }
6575: }
6576: else /*= 0 Unknown */
6577: agev[m][i]=1;
6578: }
6579:
6580: }
6581: for (i=1; i<=imx; i++) {
6582: for(m=firstpass; (m<=lastpass); m++){
6583: if (s[m][i] > (nlstate+ndeath)) {
6584: (*nberr)++;
6585: 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);
6586: 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);
6587: return 1;
6588: }
6589: }
6590: }
6591:
6592: /*for (i=1; i<=imx; i++){
6593: for (m=firstpass; (m<lastpass); m++){
6594: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6595: }
6596:
6597: }*/
6598:
6599:
6600: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6601: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6602:
6603: return (0);
6604: /* endread:*/
6605: printf("Exiting calandcheckages: ");
6606: return (1);
6607: }
6608:
6609: #if defined(_MSC_VER)
6610: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6611: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6612: //#include "stdafx.h"
6613: //#include <stdio.h>
6614: //#include <tchar.h>
6615: //#include <windows.h>
6616: //#include <iostream>
6617: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6618:
6619: LPFN_ISWOW64PROCESS fnIsWow64Process;
6620:
6621: BOOL IsWow64()
6622: {
6623: BOOL bIsWow64 = FALSE;
6624:
6625: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6626: // (HANDLE, PBOOL);
6627:
6628: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6629:
6630: HMODULE module = GetModuleHandle(_T("kernel32"));
6631: const char funcName[] = "IsWow64Process";
6632: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6633: GetProcAddress(module, funcName);
6634:
6635: if (NULL != fnIsWow64Process)
6636: {
6637: if (!fnIsWow64Process(GetCurrentProcess(),
6638: &bIsWow64))
6639: //throw std::exception("Unknown error");
6640: printf("Unknown error\n");
6641: }
6642: return bIsWow64 != FALSE;
6643: }
6644: #endif
6645:
6646: void syscompilerinfo(int logged)
6647: {
6648: /* #include "syscompilerinfo.h"*/
6649: /* command line Intel compiler 32bit windows, XP compatible:*/
6650: /* /GS /W3 /Gy
6651: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6652: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6653: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6654: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6655: */
6656: /* 64 bits */
6657: /*
6658: /GS /W3 /Gy
6659: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6660: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6661: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6662: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6663: /* Optimization are useless and O3 is slower than O2 */
6664: /*
6665: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6666: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6667: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6668: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6669: */
6670: /* Link is */ /* /OUT:"visual studio
6671: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6672: /PDB:"visual studio
6673: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6674: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6675: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6676: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6677: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6678: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6679: uiAccess='false'"
6680: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6681: /NOLOGO /TLBID:1
6682: */
6683: #if defined __INTEL_COMPILER
6684: #if defined(__GNUC__)
6685: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6686: #endif
6687: #elif defined(__GNUC__)
6688: #ifndef __APPLE__
6689: #include <gnu/libc-version.h> /* Only on gnu */
6690: #endif
6691: struct utsname sysInfo;
6692: int cross = CROSS;
6693: if (cross){
6694: printf("Cross-");
6695: if(logged) fprintf(ficlog, "Cross-");
6696: }
6697: #endif
6698:
6699: #include <stdint.h>
6700:
6701: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6702: #if defined(__clang__)
6703: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6704: #endif
6705: #if defined(__ICC) || defined(__INTEL_COMPILER)
6706: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6707: #endif
6708: #if defined(__GNUC__) || defined(__GNUG__)
6709: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6710: #endif
6711: #if defined(__HP_cc) || defined(__HP_aCC)
6712: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6713: #endif
6714: #if defined(__IBMC__) || defined(__IBMCPP__)
6715: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6716: #endif
6717: #if defined(_MSC_VER)
6718: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6719: #endif
6720: #if defined(__PGI)
6721: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6722: #endif
6723: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6724: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6725: #endif
6726: printf(" for "); if (logged) fprintf(ficlog, " for ");
6727:
6728: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6729: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6730: // Windows (x64 and x86)
6731: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6732: #elif __unix__ // all unices, not all compilers
6733: // Unix
6734: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6735: #elif __linux__
6736: // linux
6737: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6738: #elif __APPLE__
6739: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6740: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6741: #endif
6742:
6743: /* __MINGW32__ */
6744: /* __CYGWIN__ */
6745: /* __MINGW64__ */
6746: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6747: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6748: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6749: /* _WIN64 // Defined for applications for Win64. */
6750: /* _M_X64 // Defined for compilations that target x64 processors. */
6751: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6752:
6753: #if UINTPTR_MAX == 0xffffffff
6754: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6755: #elif UINTPTR_MAX == 0xffffffffffffffff
6756: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6757: #else
6758: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6759: #endif
6760:
6761: #if defined(__GNUC__)
6762: # if defined(__GNUC_PATCHLEVEL__)
6763: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6764: + __GNUC_MINOR__ * 100 \
6765: + __GNUC_PATCHLEVEL__)
6766: # else
6767: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6768: + __GNUC_MINOR__ * 100)
6769: # endif
6770: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6771: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6772:
6773: if (uname(&sysInfo) != -1) {
6774: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6775: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6776: }
6777: else
6778: perror("uname() error");
6779: //#ifndef __INTEL_COMPILER
6780: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6781: printf("GNU libc version: %s\n", gnu_get_libc_version());
6782: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6783: #endif
6784: #endif
6785:
6786: // void main()
6787: // {
6788: #if defined(_MSC_VER)
6789: if (IsWow64()){
6790: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6791: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6792: }
6793: else{
6794: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6795: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6796: }
6797: // printf("\nPress Enter to continue...");
6798: // getchar();
6799: // }
6800:
6801: #endif
6802:
6803:
6804: }
6805:
6806: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
6807: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6808: int i, j, k, i1 ;
6809: /* double ftolpl = 1.e-10; */
6810: double age, agebase, agelim;
6811: double tot;
6812:
6813: strcpy(filerespl,"PL_");
6814: strcat(filerespl,fileresu);
6815: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6816: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6817: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6818: }
6819: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6820: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6821: pstamp(ficrespl);
6822: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6823: fprintf(ficrespl,"#Age ");
6824: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6825: fprintf(ficrespl,"\n");
6826:
6827: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6828:
6829: agebase=ageminpar;
6830: agelim=agemaxpar;
6831:
6832: i1=pow(2,cptcoveff);
6833: if (cptcovn < 1){i1=1;}
6834:
6835: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6836: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6837: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6838: k=k+1;
6839: /* to clean */
6840: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6841: fprintf(ficrespl,"#******");
6842: printf("#******");
6843: fprintf(ficlog,"#******");
6844: for(j=1;j<=cptcoveff;j++) {
6845: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6846: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6847: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6848: }
6849: fprintf(ficrespl,"******\n");
6850: printf("******\n");
6851: fprintf(ficlog,"******\n");
6852:
6853: fprintf(ficrespl,"#Age ");
6854: for(j=1;j<=cptcoveff;j++) {
6855: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6856: }
6857: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6858: fprintf(ficrespl,"Total Years_to_converge\n");
6859:
6860: for (age=agebase; age<=agelim; age++){
6861: /* for (age=agebase; age<=agebase; age++){ */
6862: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
6863: fprintf(ficrespl,"%.0f ",age );
6864: for(j=1;j<=cptcoveff;j++)
6865: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6866: tot=0.;
6867: for(i=1; i<=nlstate;i++){
6868: tot += prlim[i][i];
6869: fprintf(ficrespl," %.5f", prlim[i][i]);
6870: }
6871: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
6872: } /* Age */
6873: /* was end of cptcod */
6874: } /* cptcov */
6875: return 0;
6876: }
6877:
6878: int hPijx(double *p, int bage, int fage){
6879: /*------------- h Pij x at various ages ------------*/
6880:
6881: int stepsize;
6882: int agelim;
6883: int hstepm;
6884: int nhstepm;
6885: int h, i, i1, j, k;
6886:
6887: double agedeb;
6888: double ***p3mat;
6889:
6890: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
6891: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6892: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6893: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6894: }
6895: printf("Computing pij: result on file '%s' \n", filerespij);
6896: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6897:
6898: stepsize=(int) (stepm+YEARM-1)/YEARM;
6899: /*if (stepm<=24) stepsize=2;*/
6900:
6901: agelim=AGESUP;
6902: hstepm=stepsize*YEARM; /* Every year of age */
6903: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6904:
6905: /* hstepm=1; aff par mois*/
6906: pstamp(ficrespij);
6907: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6908: i1= pow(2,cptcoveff);
6909: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6910: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6911: /* k=k+1; */
6912: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6913: fprintf(ficrespij,"\n#****** ");
6914: for(j=1;j<=cptcoveff;j++)
6915: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6916: fprintf(ficrespij,"******\n");
6917:
6918: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6919: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6920: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6921:
6922: /* nhstepm=nhstepm*YEARM; aff par mois*/
6923:
6924: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6925: oldm=oldms;savm=savms;
6926: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6927: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6928: for(i=1; i<=nlstate;i++)
6929: for(j=1; j<=nlstate+ndeath;j++)
6930: fprintf(ficrespij," %1d-%1d",i,j);
6931: fprintf(ficrespij,"\n");
6932: for (h=0; h<=nhstepm; h++){
6933: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6934: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
6935: for(i=1; i<=nlstate;i++)
6936: for(j=1; j<=nlstate+ndeath;j++)
6937: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
6938: fprintf(ficrespij,"\n");
6939: }
6940: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6941: fprintf(ficrespij,"\n");
6942: }
6943: /*}*/
6944: }
6945: return 0;
6946: }
6947:
6948:
6949: /***********************************************/
6950: /**************** Main Program *****************/
6951: /***********************************************/
6952:
6953: int main(int argc, char *argv[])
6954: {
6955: #ifdef GSL
6956: const gsl_multimin_fminimizer_type *T;
6957: size_t iteri = 0, it;
6958: int rval = GSL_CONTINUE;
6959: int status = GSL_SUCCESS;
6960: double ssval;
6961: #endif
6962: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
6963: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6964: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
6965: int jj, ll, li, lj, lk;
6966: int numlinepar=0; /* Current linenumber of parameter file */
6967: int num_filled;
6968: int itimes;
6969: int NDIM=2;
6970: int vpopbased=0;
6971:
6972: char ca[32], cb[32];
6973: /* FILE *fichtm; *//* Html File */
6974: /* FILE *ficgp;*/ /*Gnuplot File */
6975: struct stat info;
6976: double agedeb=0.;
6977:
6978: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
6979:
6980: double fret;
6981: double dum=0.; /* Dummy variable */
6982: double ***p3mat;
6983: double ***mobaverage;
6984:
6985: char line[MAXLINE];
6986: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6987:
6988: char model[MAXLINE], modeltemp[MAXLINE];
6989: char pathr[MAXLINE], pathimach[MAXLINE];
6990: char *tok, *val; /* pathtot */
6991: int firstobs=1, lastobs=10;
6992: int c, h , cpt, c2;
6993: int jl=0;
6994: int i1, j1, jk, stepsize=0;
6995: int count=0;
6996:
6997: int *tab;
6998: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6999: int mobilav=0,popforecast=0;
7000: int hstepm=0, nhstepm=0;
7001: int agemortsup;
7002: float sumlpop=0.;
7003: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
7004: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
7005:
7006: double bage=0, fage=110., age, agelim=0., agebase=0.;
7007: double ftolpl=FTOL;
7008: double **prlim;
7009: double ***param; /* Matrix of parameters */
7010: double *p;
7011: double **matcov; /* Matrix of covariance */
7012: double **hess; /* Hessian matrix */
7013: double ***delti3; /* Scale */
7014: double *delti; /* Scale */
7015: double ***eij, ***vareij;
7016: double **varpl; /* Variances of prevalence limits by age */
7017: double *epj, vepp;
7018:
7019: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
7020: double **ximort;
7021: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
7022: int *dcwave;
7023:
7024: char z[1]="c";
7025:
7026: /*char *strt;*/
7027: char strtend[80];
7028:
7029:
7030: /* setlocale (LC_ALL, ""); */
7031: /* bindtextdomain (PACKAGE, LOCALEDIR); */
7032: /* textdomain (PACKAGE); */
7033: /* setlocale (LC_CTYPE, ""); */
7034: /* setlocale (LC_MESSAGES, ""); */
7035:
7036: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
7037: rstart_time = time(NULL);
7038: /* (void) gettimeofday(&start_time,&tzp);*/
7039: start_time = *localtime(&rstart_time);
7040: curr_time=start_time;
7041: /*tml = *localtime(&start_time.tm_sec);*/
7042: /* strcpy(strstart,asctime(&tml)); */
7043: strcpy(strstart,asctime(&start_time));
7044:
7045: /* printf("Localtime (at start)=%s",strstart); */
7046: /* tp.tm_sec = tp.tm_sec +86400; */
7047: /* tm = *localtime(&start_time.tm_sec); */
7048: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
7049: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
7050: /* tmg.tm_hour=tmg.tm_hour + 1; */
7051: /* tp.tm_sec = mktime(&tmg); */
7052: /* strt=asctime(&tmg); */
7053: /* printf("Time(after) =%s",strstart); */
7054: /* (void) time (&time_value);
7055: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
7056: * tm = *localtime(&time_value);
7057: * strstart=asctime(&tm);
7058: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
7059: */
7060:
7061: nberr=0; /* Number of errors and warnings */
7062: nbwarn=0;
7063: #ifdef WIN32
7064: _getcwd(pathcd, size);
7065: #else
7066: getcwd(pathcd, size);
7067: #endif
7068: syscompilerinfo(0);
7069: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
7070: if(argc <=1){
7071: printf("\nEnter the parameter file name: ");
7072: if(!fgets(pathr,FILENAMELENGTH,stdin)){
7073: printf("ERROR Empty parameter file name\n");
7074: goto end;
7075: }
7076: i=strlen(pathr);
7077: if(pathr[i-1]=='\n')
7078: pathr[i-1]='\0';
7079: i=strlen(pathr);
7080: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
7081: pathr[i-1]='\0';
7082: }
7083: i=strlen(pathr);
7084: if( i==0 ){
7085: printf("ERROR Empty parameter file name\n");
7086: goto end;
7087: }
7088: for (tok = pathr; tok != NULL; ){
7089: printf("Pathr |%s|\n",pathr);
7090: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
7091: printf("val= |%s| pathr=%s\n",val,pathr);
7092: strcpy (pathtot, val);
7093: if(pathr[0] == '\0') break; /* Dirty */
7094: }
7095: }
7096: else{
7097: strcpy(pathtot,argv[1]);
7098: }
7099: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
7100: /*cygwin_split_path(pathtot,path,optionfile);
7101: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
7102: /* cutv(path,optionfile,pathtot,'\\');*/
7103:
7104: /* Split argv[0], imach program to get pathimach */
7105: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
7106: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7107: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7108: /* strcpy(pathimach,argv[0]); */
7109: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
7110: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
7111: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
7112: #ifdef WIN32
7113: _chdir(path); /* Can be a relative path */
7114: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
7115: #else
7116: chdir(path); /* Can be a relative path */
7117: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
7118: #endif
7119: printf("Current directory %s!\n",pathcd);
7120: strcpy(command,"mkdir ");
7121: strcat(command,optionfilefiname);
7122: if((outcmd=system(command)) != 0){
7123: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
7124: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
7125: /* fclose(ficlog); */
7126: /* exit(1); */
7127: }
7128: /* if((imk=mkdir(optionfilefiname))<0){ */
7129: /* perror("mkdir"); */
7130: /* } */
7131:
7132: /*-------- arguments in the command line --------*/
7133:
7134: /* Main Log file */
7135: strcat(filelog, optionfilefiname);
7136: strcat(filelog,".log"); /* */
7137: if((ficlog=fopen(filelog,"w"))==NULL) {
7138: printf("Problem with logfile %s\n",filelog);
7139: goto end;
7140: }
7141: fprintf(ficlog,"Log filename:%s\n",filelog);
7142: fprintf(ficlog,"Version %s %s",version,fullversion);
7143: fprintf(ficlog,"\nEnter the parameter file name: \n");
7144: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
7145: path=%s \n\
7146: optionfile=%s\n\
7147: optionfilext=%s\n\
7148: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
7149:
7150: syscompilerinfo(1);
7151:
7152: printf("Local time (at start):%s",strstart);
7153: fprintf(ficlog,"Local time (at start): %s",strstart);
7154: fflush(ficlog);
7155: /* (void) gettimeofday(&curr_time,&tzp); */
7156: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
7157:
7158: /* */
7159: strcpy(fileres,"r");
7160: strcat(fileres, optionfilefiname);
7161: strcat(fileresu, optionfilefiname); /* Without r in front */
7162: strcat(fileres,".txt"); /* Other files have txt extension */
7163: strcat(fileresu,".txt"); /* Other files have txt extension */
7164:
7165: /* Main ---------arguments file --------*/
7166:
7167: if((ficpar=fopen(optionfile,"r"))==NULL) {
7168: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7169: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7170: fflush(ficlog);
7171: /* goto end; */
7172: exit(70);
7173: }
7174:
7175:
7176:
7177: strcpy(filereso,"o");
7178: strcat(filereso,fileresu);
7179: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
7180: printf("Problem with Output resultfile: %s\n", filereso);
7181: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
7182: fflush(ficlog);
7183: goto end;
7184: }
7185:
7186: /* Reads comments: lines beginning with '#' */
7187: numlinepar=0;
7188:
7189: /* First parameter line */
7190: while(fgets(line, MAXLINE, ficpar)) {
7191: /* If line starts with a # it is a comment */
7192: if (line[0] == '#') {
7193: numlinepar++;
7194: fputs(line,stdout);
7195: fputs(line,ficparo);
7196: fputs(line,ficlog);
7197: continue;
7198: }else
7199: break;
7200: }
7201: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
7202: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
7203: if (num_filled != 5) {
7204: printf("Should be 5 parameters\n");
7205: }
7206: numlinepar++;
7207: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
7208: }
7209: /* Second parameter line */
7210: while(fgets(line, MAXLINE, ficpar)) {
7211: /* If line starts with a # it is a comment */
7212: if (line[0] == '#') {
7213: numlinepar++;
7214: fputs(line,stdout);
7215: fputs(line,ficparo);
7216: fputs(line,ficlog);
7217: continue;
7218: }else
7219: break;
7220: }
7221: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
7222: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7223: if (num_filled != 8) {
7224: printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
7225: printf("but line=%s\n",line);
7226: }
7227: 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);
7228: }
7229: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
7230: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
7231: /* Third parameter line */
7232: while(fgets(line, MAXLINE, ficpar)) {
7233: /* If line starts with a # it is a comment */
7234: if (line[0] == '#') {
7235: numlinepar++;
7236: fputs(line,stdout);
7237: fputs(line,ficparo);
7238: fputs(line,ficlog);
7239: continue;
7240: }else
7241: break;
7242: }
7243: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7244: if (num_filled == 0)
7245: model[0]='\0';
7246: else if (num_filled != 1){
7247: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7248: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7249: model[0]='\0';
7250: goto end;
7251: }
7252: else{
7253: if (model[0]=='+'){
7254: for(i=1; i<=strlen(model);i++)
7255: modeltemp[i-1]=model[i];
7256: strcpy(model,modeltemp);
7257: }
7258: }
7259: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
7260: printf("model=1+age+%s\n",model);fflush(stdout);
7261: }
7262: /* 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); */
7263: /* numlinepar=numlinepar+3; /\* In general *\/ */
7264: /* 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); */
7265: 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);
7266: 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);
7267: fflush(ficlog);
7268: /* if(model[0]=='#'|| model[0]== '\0'){ */
7269: if(model[0]=='#'){
7270: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7271: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7272: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7273: if(mle != -1){
7274: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7275: exit(1);
7276: }
7277: }
7278: while((c=getc(ficpar))=='#' && c!= EOF){
7279: ungetc(c,ficpar);
7280: fgets(line, MAXLINE, ficpar);
7281: numlinepar++;
7282: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7283: z[0]=line[1];
7284: }
7285: /* printf("****line [1] = %c \n",line[1]); */
7286: fputs(line, stdout);
7287: //puts(line);
7288: fputs(line,ficparo);
7289: fputs(line,ficlog);
7290: }
7291: ungetc(c,ficpar);
7292:
7293:
7294: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
7295: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7296: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7297: v1+v2*age+v2*v3 makes cptcovn = 3
7298: */
7299: if (strlen(model)>1)
7300: 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*/
7301: else
7302: ncovmodel=2; /* Constant and age */
7303: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7304: npar= nforce*ncovmodel; /* Number of parameters like aij*/
7305: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7306: 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);
7307: 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);
7308: fflush(stdout);
7309: fclose (ficlog);
7310: goto end;
7311: }
7312: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7313: delti=delti3[1][1];
7314: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7315: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7316: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7317: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7318: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7319: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7320: fclose (ficparo);
7321: fclose (ficlog);
7322: goto end;
7323: exit(0);
7324: }
7325: else if(mle==-3) { /* Main Wizard */
7326: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7327: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7328: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7329: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7330: matcov=matrix(1,npar,1,npar);
7331: hess=matrix(1,npar,1,npar);
7332: }
7333: else{
7334: /* Read guessed parameters */
7335: /* Reads comments: lines beginning with '#' */
7336: while((c=getc(ficpar))=='#' && c!= EOF){
7337: ungetc(c,ficpar);
7338: fgets(line, MAXLINE, ficpar);
7339: numlinepar++;
7340: fputs(line,stdout);
7341: fputs(line,ficparo);
7342: fputs(line,ficlog);
7343: }
7344: ungetc(c,ficpar);
7345:
7346: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7347: for(i=1; i <=nlstate; i++){
7348: j=0;
7349: for(jj=1; jj <=nlstate+ndeath; jj++){
7350: if(jj==i) continue;
7351: j++;
7352: fscanf(ficpar,"%1d%1d",&i1,&j1);
7353: if ((i1 != i) || (j1 != jj)){
7354: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7355: It might be a problem of design; if ncovcol and the model are correct\n \
7356: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7357: exit(1);
7358: }
7359: fprintf(ficparo,"%1d%1d",i1,j1);
7360: if(mle==1)
7361: printf("%1d%1d",i,jj);
7362: fprintf(ficlog,"%1d%1d",i,jj);
7363: for(k=1; k<=ncovmodel;k++){
7364: fscanf(ficpar," %lf",¶m[i][j][k]);
7365: if(mle==1){
7366: printf(" %lf",param[i][j][k]);
7367: fprintf(ficlog," %lf",param[i][j][k]);
7368: }
7369: else
7370: fprintf(ficlog," %lf",param[i][j][k]);
7371: fprintf(ficparo," %lf",param[i][j][k]);
7372: }
7373: fscanf(ficpar,"\n");
7374: numlinepar++;
7375: if(mle==1)
7376: printf("\n");
7377: fprintf(ficlog,"\n");
7378: fprintf(ficparo,"\n");
7379: }
7380: }
7381: fflush(ficlog);
7382:
7383: /* Reads scales values */
7384: p=param[1][1];
7385:
7386: /* Reads comments: lines beginning with '#' */
7387: while((c=getc(ficpar))=='#' && c!= EOF){
7388: ungetc(c,ficpar);
7389: fgets(line, MAXLINE, ficpar);
7390: numlinepar++;
7391: fputs(line,stdout);
7392: fputs(line,ficparo);
7393: fputs(line,ficlog);
7394: }
7395: ungetc(c,ficpar);
7396:
7397: for(i=1; i <=nlstate; i++){
7398: for(j=1; j <=nlstate+ndeath-1; j++){
7399: fscanf(ficpar,"%1d%1d",&i1,&j1);
7400: if ( (i1-i) * (j1-j) != 0){
7401: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7402: exit(1);
7403: }
7404: printf("%1d%1d",i,j);
7405: fprintf(ficparo,"%1d%1d",i1,j1);
7406: fprintf(ficlog,"%1d%1d",i1,j1);
7407: for(k=1; k<=ncovmodel;k++){
7408: fscanf(ficpar,"%le",&delti3[i][j][k]);
7409: printf(" %le",delti3[i][j][k]);
7410: fprintf(ficparo," %le",delti3[i][j][k]);
7411: fprintf(ficlog," %le",delti3[i][j][k]);
7412: }
7413: fscanf(ficpar,"\n");
7414: numlinepar++;
7415: printf("\n");
7416: fprintf(ficparo,"\n");
7417: fprintf(ficlog,"\n");
7418: }
7419: }
7420: fflush(ficlog);
7421:
7422: /* Reads covariance matrix */
7423: delti=delti3[1][1];
7424:
7425:
7426: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7427:
7428: /* Reads comments: lines beginning with '#' */
7429: while((c=getc(ficpar))=='#' && c!= EOF){
7430: ungetc(c,ficpar);
7431: fgets(line, MAXLINE, ficpar);
7432: numlinepar++;
7433: fputs(line,stdout);
7434: fputs(line,ficparo);
7435: fputs(line,ficlog);
7436: }
7437: ungetc(c,ficpar);
7438:
7439: matcov=matrix(1,npar,1,npar);
7440: hess=matrix(1,npar,1,npar);
7441: for(i=1; i <=npar; i++)
7442: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7443:
7444: /* Scans npar lines */
7445: for(i=1; i <=npar; i++){
7446: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7447: if(count != 3){
7448: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7449: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7450: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7451: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7452: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7453: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7454: exit(1);
7455: }else
7456: if(mle==1)
7457: printf("%1d%1d%1d",i1,j1,jk);
7458: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7459: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7460: for(j=1; j <=i; j++){
7461: fscanf(ficpar," %le",&matcov[i][j]);
7462: if(mle==1){
7463: printf(" %.5le",matcov[i][j]);
7464: }
7465: fprintf(ficlog," %.5le",matcov[i][j]);
7466: fprintf(ficparo," %.5le",matcov[i][j]);
7467: }
7468: fscanf(ficpar,"\n");
7469: numlinepar++;
7470: if(mle==1)
7471: printf("\n");
7472: fprintf(ficlog,"\n");
7473: fprintf(ficparo,"\n");
7474: }
7475: /* End of read covariance matrix npar lines */
7476: for(i=1; i <=npar; i++)
7477: for(j=i+1;j<=npar;j++)
7478: matcov[i][j]=matcov[j][i];
7479:
7480: if(mle==1)
7481: printf("\n");
7482: fprintf(ficlog,"\n");
7483:
7484: fflush(ficlog);
7485:
7486: /*-------- Rewriting parameter file ----------*/
7487: strcpy(rfileres,"r"); /* "Rparameterfile */
7488: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7489: strcat(rfileres,"."); /* */
7490: strcat(rfileres,optionfilext); /* Other files have txt extension */
7491: if((ficres =fopen(rfileres,"w"))==NULL) {
7492: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7493: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7494: }
7495: fprintf(ficres,"#%s\n",version);
7496: } /* End of mle != -3 */
7497:
7498: /* Main data
7499: */
7500: n= lastobs;
7501: num=lvector(1,n);
7502: moisnais=vector(1,n);
7503: annais=vector(1,n);
7504: moisdc=vector(1,n);
7505: andc=vector(1,n);
7506: agedc=vector(1,n);
7507: cod=ivector(1,n);
7508: weight=vector(1,n);
7509: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7510: mint=matrix(1,maxwav,1,n);
7511: anint=matrix(1,maxwav,1,n);
7512: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7513: tab=ivector(1,NCOVMAX);
7514: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7515: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7516:
7517: /* Reads data from file datafile */
7518: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7519: goto end;
7520:
7521: /* Calculation of the number of parameters from char model */
7522: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7523: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7524: k=3 V4 Tvar[k=3]= 4 (from V4)
7525: k=2 V1 Tvar[k=2]= 1 (from V1)
7526: k=1 Tvar[1]=2 (from V2)
7527: */
7528: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7529: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7530: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7531: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7532: */
7533: /* For model-covariate k tells which data-covariate to use but
7534: because this model-covariate is a construction we invent a new column
7535: ncovcol + k1
7536: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7537: Tvar[3=V1*V4]=4+1 etc */
7538: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7539: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7540: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7541: */
7542: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7543: 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
7544: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7545: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7546: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7547: 4 covariates (3 plus signs)
7548: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7549: */
7550:
7551: /* Main decodemodel */
7552:
7553:
7554: if(decodemodel(model, lastobs) == 1)
7555: goto end;
7556:
7557: if((double)(lastobs-imx)/(double)imx > 1.10){
7558: nbwarn++;
7559: 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);
7560: 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);
7561: }
7562: /* if(mle==1){*/
7563: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7564: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7565: }
7566:
7567: /*-calculation of age at interview from date of interview and age at death -*/
7568: agev=matrix(1,maxwav,1,imx);
7569:
7570: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7571: goto end;
7572:
7573:
7574: agegomp=(int)agemin;
7575: free_vector(moisnais,1,n);
7576: free_vector(annais,1,n);
7577: /* free_matrix(mint,1,maxwav,1,n);
7578: free_matrix(anint,1,maxwav,1,n);*/
7579: free_vector(moisdc,1,n);
7580: free_vector(andc,1,n);
7581: /* */
7582:
7583: wav=ivector(1,imx);
7584: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7585: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7586: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7587:
7588: /* Concatenates waves */
7589: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7590: /* */
7591:
7592: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7593:
7594: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7595: ncodemax[1]=1;
7596: Ndum =ivector(-1,NCOVMAX);
7597: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7598: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7599: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
7600: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7601: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
7602:
7603: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7604: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7605: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7606: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
7607: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
7608: * (currently 0 or 1) in the data.
7609: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
7610: * corresponding modality (h,j).
7611: */
7612:
7613: h=0;
7614:
7615:
7616: /*if (cptcovn > 0) */
7617:
7618:
7619: m=pow(2,cptcoveff);
7620:
7621: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7622: * For k=4 covariates, h goes from 1 to m=2**k
7623: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
7624: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7625: * h\k 1 2 3 4
7626: *______________________________
7627: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7628: * 2 2 1 1 1
7629: * 3 i=2 1 2 1 1
7630: * 4 2 2 1 1
7631: * 5 i=3 1 i=2 1 2 1
7632: * 6 2 1 2 1
7633: * 7 i=4 1 2 2 1
7634: * 8 2 2 2 1
7635: * 9 i=5 1 i=3 1 i=2 1 2
7636: * 10 2 1 1 2
7637: * 11 i=6 1 2 1 2
7638: * 12 2 2 1 2
7639: * 13 i=7 1 i=4 1 2 2
7640: * 14 2 1 2 2
7641: * 15 i=8 1 2 2 2
7642: * 16 2 2 2 2
7643: */
7644: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
7645: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
7646: * and the value of each covariate?
7647: * V1=1, V2=1, V3=2, V4=1 ?
7648: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
7649: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
7650: * In order to get the real value in the data, we use nbcode
7651: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
7652: * We are keeping this crazy system in order to be able (in the future?)
7653: * to have more than 2 values (0 or 1) for a covariate.
7654: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7655: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
7656: * bbbbbbbb
7657: * 76543210
7658: * h-1 00000101 (6-1=5)
7659: *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
7660: * &
7661: * 1 00000001 (1)
7662: * 00000001 = 1 & ((h-1) >> (k-1))
7663: * +1= 00000010 =2
7664: *
7665: * h=14, k=3 => h'=h-1=13, k'=k-1=2
7666: * h' 1101 =2^3+2^2+0x2^1+2^0
7667: * >>k' 11
7668: * & 00000001
7669: * = 00000001
7670: * +1 = 00000010=2 = codtabm(14,3)
7671: * Reverse h=6 and m=16?
7672: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
7673: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
7674: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
7675: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
7676: * V3=decodtabm(14,3,2**4)=2
7677: * h'=13 1101 =2^3+2^2+0x2^1+2^0
7678: *(h-1) >> (j-1) 0011 =13 >> 2
7679: * &1 000000001
7680: * = 000000001
7681: * +1= 000000010 =2
7682: * 2211
7683: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
7684: * V3=2
7685: */
7686:
7687: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7688: /* /\* printf("h=%2d ", h); *\/ */
7689: /* /\* for(k=1; k <=10; k++){ *\/ */
7690: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7691: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7692: /* /\* } *\/ */
7693: /* /\* printf("\n"); *\/ */
7694: /* } */
7695: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7696: /* 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 *\/ */
7697: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7698: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7699: /* h++; */
7700: /* if (h>m) */
7701: /* h=1; */
7702: /* codtab[h][k]=j; */
7703: /* /\* codtab[12][3]=1; *\/ */
7704: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7705: /* /\* 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]]); *\/ */
7706: /* } */
7707: /* } */
7708: /* } */
7709: /* } */
7710: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7711: codtab[1][2]=1;codtab[2][2]=2; */
7712: /* for(i=1; i <=m ;i++){ */
7713: /* for(k=1; k <=cptcovn; k++){ */
7714: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7715: /* } */
7716: /* printf("\n"); */
7717: /* } */
7718: /* scanf("%d",i);*/
7719:
7720: free_ivector(Ndum,-1,NCOVMAX);
7721:
7722:
7723:
7724: /* Initialisation of ----------- gnuplot -------------*/
7725: strcpy(optionfilegnuplot,optionfilefiname);
7726: if(mle==-3)
7727: strcat(optionfilegnuplot,"-MORT_");
7728: strcat(optionfilegnuplot,".gp");
7729:
7730: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7731: printf("Problem with file %s",optionfilegnuplot);
7732: }
7733: else{
7734: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7735: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7736: //fprintf(ficgp,"set missing 'NaNq'\n");
7737: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7738: }
7739: /* fclose(ficgp);*/
7740:
7741:
7742: /* Initialisation of --------- index.htm --------*/
7743:
7744: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7745: if(mle==-3)
7746: strcat(optionfilehtm,"-MORT_");
7747: strcat(optionfilehtm,".htm");
7748: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7749: printf("Problem with %s \n",optionfilehtm);
7750: exit(0);
7751: }
7752:
7753: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7754: strcat(optionfilehtmcov,"-cov.htm");
7755: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7756: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7757: }
7758: else{
7759: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7760: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7761: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7762: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7763: }
7764:
7765: 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é-2013-2016-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-2018</a></font><br> \
7766: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7767: <font size=\"2\">IMaCh-%s <br> %s</font> \
7768: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7769: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7770: \n\
7771: <hr size=\"2\" color=\"#EC5E5E\">\
7772: <ul><li><h4>Parameter files</h4>\n\
7773: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7774: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7775: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7776: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7777: - Date and time at start: %s</ul>\n",\
7778: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7779: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7780: fileres,fileres,\
7781: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7782: fflush(fichtm);
7783:
7784: strcpy(pathr,path);
7785: strcat(pathr,optionfilefiname);
7786: #ifdef WIN32
7787: _chdir(optionfilefiname); /* Move to directory named optionfile */
7788: #else
7789: chdir(optionfilefiname); /* Move to directory named optionfile */
7790: #endif
7791:
7792:
7793: /* Calculates basic frequencies. Computes observed prevalence at single age
7794: and prints on file fileres'p'. */
7795: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7796:
7797: fprintf(fichtm,"\n");
7798: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7799: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7800: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7801: imx,agemin,agemax,jmin,jmax,jmean);
7802: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7803: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7804: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7805: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7806: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7807:
7808:
7809: /* For Powell, parameters are in a vector p[] starting at p[1]
7810: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7811: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7812:
7813: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7814: /* For mortality only */
7815: if (mle==-3){
7816: ximort=matrix(1,NDIM,1,NDIM);
7817: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7818: cens=ivector(1,n);
7819: ageexmed=vector(1,n);
7820: agecens=vector(1,n);
7821: dcwave=ivector(1,n);
7822:
7823: for (i=1; i<=imx; i++){
7824: dcwave[i]=-1;
7825: for (m=firstpass; m<=lastpass; m++)
7826: if (s[m][i]>nlstate) {
7827: dcwave[i]=m;
7828: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7829: break;
7830: }
7831: }
7832:
7833: for (i=1; i<=imx; i++) {
7834: if (wav[i]>0){
7835: ageexmed[i]=agev[mw[1][i]][i];
7836: j=wav[i];
7837: agecens[i]=1.;
7838:
7839: if (ageexmed[i]> 1 && wav[i] > 0){
7840: agecens[i]=agev[mw[j][i]][i];
7841: cens[i]= 1;
7842: }else if (ageexmed[i]< 1)
7843: cens[i]= -1;
7844: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7845: cens[i]=0 ;
7846: }
7847: else cens[i]=-1;
7848: }
7849:
7850: for (i=1;i<=NDIM;i++) {
7851: for (j=1;j<=NDIM;j++)
7852: ximort[i][j]=(i == j ? 1.0 : 0.0);
7853: }
7854:
7855: /*p[1]=0.0268; p[NDIM]=0.083;*/
7856: /*printf("%lf %lf", p[1], p[2]);*/
7857:
7858:
7859: #ifdef GSL
7860: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
7861: #else
7862: printf("Powell\n"); fprintf(ficlog,"Powell\n");
7863: #endif
7864: strcpy(filerespow,"POW-MORT_");
7865: strcat(filerespow,fileresu);
7866: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7867: printf("Problem with resultfile: %s\n", filerespow);
7868: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7869: }
7870: #ifdef GSL
7871: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
7872: #else
7873: fprintf(ficrespow,"# Powell\n# iter -2*LL");
7874: #endif
7875: /* for (i=1;i<=nlstate;i++)
7876: for(j=1;j<=nlstate+ndeath;j++)
7877: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7878: */
7879: fprintf(ficrespow,"\n");
7880: #ifdef GSL
7881: /* gsl starts here */
7882: T = gsl_multimin_fminimizer_nmsimplex;
7883: gsl_multimin_fminimizer *sfm = NULL;
7884: gsl_vector *ss, *x;
7885: gsl_multimin_function minex_func;
7886:
7887: /* Initial vertex size vector */
7888: ss = gsl_vector_alloc (NDIM);
7889:
7890: if (ss == NULL){
7891: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7892: }
7893: /* Set all step sizes to 1 */
7894: gsl_vector_set_all (ss, 0.001);
7895:
7896: /* Starting point */
7897:
7898: x = gsl_vector_alloc (NDIM);
7899:
7900: if (x == NULL){
7901: gsl_vector_free(ss);
7902: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7903: }
7904:
7905: /* Initialize method and iterate */
7906: /* p[1]=0.0268; p[NDIM]=0.083; */
7907: /* gsl_vector_set(x, 0, 0.0268); */
7908: /* gsl_vector_set(x, 1, 0.083); */
7909: gsl_vector_set(x, 0, p[1]);
7910: gsl_vector_set(x, 1, p[2]);
7911:
7912: minex_func.f = &gompertz_f;
7913: minex_func.n = NDIM;
7914: minex_func.params = (void *)&p; /* ??? */
7915:
7916: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7917: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7918:
7919: printf("Iterations beginning .....\n\n");
7920: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7921:
7922: iteri=0;
7923: while (rval == GSL_CONTINUE){
7924: iteri++;
7925: status = gsl_multimin_fminimizer_iterate(sfm);
7926:
7927: if (status) printf("error: %s\n", gsl_strerror (status));
7928: fflush(0);
7929:
7930: if (status)
7931: break;
7932:
7933: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7934: ssval = gsl_multimin_fminimizer_size (sfm);
7935:
7936: if (rval == GSL_SUCCESS)
7937: printf ("converged to a local maximum at\n");
7938:
7939: printf("%5d ", iteri);
7940: for (it = 0; it < NDIM; it++){
7941: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7942: }
7943: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7944: }
7945:
7946: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7947:
7948: gsl_vector_free(x); /* initial values */
7949: gsl_vector_free(ss); /* inital step size */
7950: for (it=0; it<NDIM; it++){
7951: p[it+1]=gsl_vector_get(sfm->x,it);
7952: fprintf(ficrespow," %.12lf", p[it]);
7953: }
7954: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7955: #endif
7956: #ifdef POWELL
7957: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7958: #endif
7959: fclose(ficrespow);
7960:
7961: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
7962:
7963: for(i=1; i <=NDIM; i++)
7964: for(j=i+1;j<=NDIM;j++)
7965: matcov[i][j]=matcov[j][i];
7966:
7967: printf("\nCovariance matrix\n ");
7968: fprintf(ficlog,"\nCovariance matrix\n ");
7969: for(i=1; i <=NDIM; i++) {
7970: for(j=1;j<=NDIM;j++){
7971: printf("%f ",matcov[i][j]);
7972: fprintf(ficlog,"%f ",matcov[i][j]);
7973: }
7974: printf("\n "); fprintf(ficlog,"\n ");
7975: }
7976:
7977: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7978: for (i=1;i<=NDIM;i++) {
7979: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7980: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7981: }
7982: lsurv=vector(1,AGESUP);
7983: lpop=vector(1,AGESUP);
7984: tpop=vector(1,AGESUP);
7985: lsurv[agegomp]=100000;
7986:
7987: for (k=agegomp;k<=AGESUP;k++) {
7988: agemortsup=k;
7989: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7990: }
7991:
7992: for (k=agegomp;k<agemortsup;k++)
7993: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7994:
7995: for (k=agegomp;k<agemortsup;k++){
7996: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7997: sumlpop=sumlpop+lpop[k];
7998: }
7999:
8000: tpop[agegomp]=sumlpop;
8001: for (k=agegomp;k<(agemortsup-3);k++){
8002: /* tpop[k+1]=2;*/
8003: tpop[k+1]=tpop[k]-lpop[k];
8004: }
8005:
8006:
8007: printf("\nAge lx qx dx Lx Tx e(x)\n");
8008: for (k=agegomp;k<(agemortsup-2);k++)
8009: 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]);
8010:
8011:
8012: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8013: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
8014: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8015: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8016: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8017: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8018: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8019: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8020: }else
8021: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8022: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
8023: stepm, weightopt,\
8024: model,imx,p,matcov,agemortsup);
8025:
8026: free_vector(lsurv,1,AGESUP);
8027: free_vector(lpop,1,AGESUP);
8028: free_vector(tpop,1,AGESUP);
8029: #ifdef GSL
8030: free_ivector(cens,1,n);
8031: free_vector(agecens,1,n);
8032: free_ivector(dcwave,1,n);
8033: free_matrix(ximort,1,NDIM,1,NDIM);
8034: #endif
8035: } /* Endof if mle==-3 mortality only */
8036: /* Standard */
8037: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
8038: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8039: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8040: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8041: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8042: for (k=1; k<=npar;k++)
8043: printf(" %d %8.5f",k,p[k]);
8044: printf("\n");
8045: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
8046: /* mlikeli uses func not funcone */
8047: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
8048: }
8049: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
8050: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8051: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8052: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8053: }
8054: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
8055: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8056: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8057: for (k=1; k<=npar;k++)
8058: printf(" %d %8.5f",k,p[k]);
8059: printf("\n");
8060:
8061: /*--------- results files --------------*/
8062: 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);
8063:
8064:
8065: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8066: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8067: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8068: for(i=1,jk=1; i <=nlstate; i++){
8069: for(k=1; k <=(nlstate+ndeath); k++){
8070: if (k != i) {
8071: printf("%d%d ",i,k);
8072: fprintf(ficlog,"%d%d ",i,k);
8073: fprintf(ficres,"%1d%1d ",i,k);
8074: for(j=1; j <=ncovmodel; j++){
8075: printf("%12.7f ",p[jk]);
8076: fprintf(ficlog,"%12.7f ",p[jk]);
8077: fprintf(ficres,"%12.7f ",p[jk]);
8078: jk++;
8079: }
8080: printf("\n");
8081: fprintf(ficlog,"\n");
8082: fprintf(ficres,"\n");
8083: }
8084: }
8085: }
8086: if(mle != 0){
8087: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
8088: ftolhess=ftol; /* Usually correct */
8089: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
8090: 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");
8091: 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");
8092: for(i=1,jk=1; i <=nlstate; i++){
8093: for(k=1; k <=(nlstate+ndeath); k++){
8094: if (k != i) {
8095: printf("%d%d ",i,k);
8096: fprintf(ficlog,"%d%d ",i,k);
8097: for(j=1; j <=ncovmodel; j++){
8098: 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]));
8099: 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]));
8100: jk++;
8101: }
8102: printf("\n");
8103: fprintf(ficlog,"\n");
8104: }
8105: }
8106: }
8107: } /* end of hesscov and Wald tests */
8108:
8109: /* */
8110: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
8111: printf("# Scales (for hessian or gradient estimation)\n");
8112: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
8113: for(i=1,jk=1; i <=nlstate; i++){
8114: for(j=1; j <=nlstate+ndeath; j++){
8115: if (j!=i) {
8116: fprintf(ficres,"%1d%1d",i,j);
8117: printf("%1d%1d",i,j);
8118: fprintf(ficlog,"%1d%1d",i,j);
8119: for(k=1; k<=ncovmodel;k++){
8120: printf(" %.5e",delti[jk]);
8121: fprintf(ficlog," %.5e",delti[jk]);
8122: fprintf(ficres," %.5e",delti[jk]);
8123: jk++;
8124: }
8125: printf("\n");
8126: fprintf(ficlog,"\n");
8127: fprintf(ficres,"\n");
8128: }
8129: }
8130: }
8131:
8132: 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");
8133: if(mle >= 1) /* To big for the screen */
8134: 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");
8135: 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");
8136: /* # 121 Var(a12)\n\ */
8137: /* # 122 Cov(b12,a12) Var(b12)\n\ */
8138: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
8139: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
8140: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
8141: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
8142: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
8143: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
8144:
8145:
8146: /* Just to have a covariance matrix which will be more understandable
8147: even is we still don't want to manage dictionary of variables
8148: */
8149: for(itimes=1;itimes<=2;itimes++){
8150: jj=0;
8151: for(i=1; i <=nlstate; i++){
8152: for(j=1; j <=nlstate+ndeath; j++){
8153: if(j==i) continue;
8154: for(k=1; k<=ncovmodel;k++){
8155: jj++;
8156: ca[0]= k+'a'-1;ca[1]='\0';
8157: if(itimes==1){
8158: if(mle>=1)
8159: printf("#%1d%1d%d",i,j,k);
8160: fprintf(ficlog,"#%1d%1d%d",i,j,k);
8161: fprintf(ficres,"#%1d%1d%d",i,j,k);
8162: }else{
8163: if(mle>=1)
8164: printf("%1d%1d%d",i,j,k);
8165: fprintf(ficlog,"%1d%1d%d",i,j,k);
8166: fprintf(ficres,"%1d%1d%d",i,j,k);
8167: }
8168: ll=0;
8169: for(li=1;li <=nlstate; li++){
8170: for(lj=1;lj <=nlstate+ndeath; lj++){
8171: if(lj==li) continue;
8172: for(lk=1;lk<=ncovmodel;lk++){
8173: ll++;
8174: if(ll<=jj){
8175: cb[0]= lk +'a'-1;cb[1]='\0';
8176: if(ll<jj){
8177: if(itimes==1){
8178: if(mle>=1)
8179: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8180: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8181: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8182: }else{
8183: if(mle>=1)
8184: printf(" %.5e",matcov[jj][ll]);
8185: fprintf(ficlog," %.5e",matcov[jj][ll]);
8186: fprintf(ficres," %.5e",matcov[jj][ll]);
8187: }
8188: }else{
8189: if(itimes==1){
8190: if(mle>=1)
8191: printf(" Var(%s%1d%1d)",ca,i,j);
8192: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
8193: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
8194: }else{
8195: if(mle>=1)
8196: printf(" %.7e",matcov[jj][ll]);
8197: fprintf(ficlog," %.7e",matcov[jj][ll]);
8198: fprintf(ficres," %.7e",matcov[jj][ll]);
8199: }
8200: }
8201: }
8202: } /* end lk */
8203: } /* end lj */
8204: } /* end li */
8205: if(mle>=1)
8206: printf("\n");
8207: fprintf(ficlog,"\n");
8208: fprintf(ficres,"\n");
8209: numlinepar++;
8210: } /* end k*/
8211: } /*end j */
8212: } /* end i */
8213: } /* end itimes */
8214:
8215: fflush(ficlog);
8216: fflush(ficres);
8217: while(fgets(line, MAXLINE, ficpar)) {
8218: /* If line starts with a # it is a comment */
8219: if (line[0] == '#') {
8220: numlinepar++;
8221: fputs(line,stdout);
8222: fputs(line,ficparo);
8223: fputs(line,ficlog);
8224: continue;
8225: }else
8226: break;
8227: }
8228:
8229: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
8230: /* ungetc(c,ficpar); */
8231: /* fgets(line, MAXLINE, ficpar); */
8232: /* fputs(line,stdout); */
8233: /* fputs(line,ficparo); */
8234: /* } */
8235: /* ungetc(c,ficpar); */
8236:
8237: estepm=0;
8238: if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
8239:
8240: if (num_filled != 6) {
8241: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
8242: printf("but line=%s\n",line);
8243: goto end;
8244: }
8245: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
8246: }
8247: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8248: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8249:
8250: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
8251: if (estepm==0 || estepm < stepm) estepm=stepm;
8252: if (fage <= 2) {
8253: bage = ageminpar;
8254: fage = agemaxpar;
8255: }
8256:
8257: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
8258: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8259: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8260:
8261: /* Other stuffs, more or less useful */
8262: while((c=getc(ficpar))=='#' && c!= EOF){
8263: ungetc(c,ficpar);
8264: fgets(line, MAXLINE, ficpar);
8265: fputs(line,stdout);
8266: fputs(line,ficparo);
8267: }
8268: ungetc(c,ficpar);
8269:
8270: 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);
8271: 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);
8272: 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);
8273: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8274: 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);
8275:
8276: while((c=getc(ficpar))=='#' && c!= EOF){
8277: ungetc(c,ficpar);
8278: fgets(line, MAXLINE, ficpar);
8279: fputs(line,stdout);
8280: fputs(line,ficparo);
8281: }
8282: ungetc(c,ficpar);
8283:
8284:
8285: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8286: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8287:
8288: fscanf(ficpar,"pop_based=%d\n",&popbased);
8289: fprintf(ficlog,"pop_based=%d\n",popbased);
8290: fprintf(ficparo,"pop_based=%d\n",popbased);
8291: fprintf(ficres,"pop_based=%d\n",popbased);
8292:
8293: while((c=getc(ficpar))=='#' && c!= EOF){
8294: ungetc(c,ficpar);
8295: fgets(line, MAXLINE, ficpar);
8296: fputs(line,stdout);
8297: fputs(line,ficparo);
8298: }
8299: ungetc(c,ficpar);
8300:
8301: 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);
8302: 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);
8303: 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);
8304: 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);
8305: 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);
8306: /* day and month of proj2 are not used but only year anproj2.*/
8307:
8308:
8309:
8310: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8311: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
8312:
8313: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8314: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8315: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8316: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8317: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8318: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8319: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8320: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8321: }else
8322: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
8323:
8324: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
8325: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
8326: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
8327:
8328: /*------------ free_vector -------------*/
8329: /* chdir(path); */
8330:
8331: free_ivector(wav,1,imx);
8332: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
8333: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
8334: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
8335: free_lvector(num,1,n);
8336: free_vector(agedc,1,n);
8337: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8338: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8339: fclose(ficparo);
8340: fclose(ficres);
8341:
8342:
8343: /* Other results (useful)*/
8344:
8345:
8346: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
8347: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8348: prlim=matrix(1,nlstate,1,nlstate);
8349: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
8350: fclose(ficrespl);
8351:
8352: #ifdef FREEEXIT2
8353: #include "freeexit2.h"
8354: #endif
8355:
8356: /*------------- h Pij x at various ages ------------*/
8357: /*#include "hpijx.h"*/
8358: hPijx(p, bage, fage);
8359: fclose(ficrespij);
8360:
8361: /*-------------- Variance of one-step probabilities---*/
8362: k=1;
8363: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8364:
8365:
8366: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8367: for(i=1;i<=AGESUP;i++)
8368: for(j=1;j<=NCOVMAX;j++)
8369: for(k=1;k<=NCOVMAX;k++)
8370: probs[i][j][k]=0.;
8371:
8372: /*---------- Forecasting ------------------*/
8373: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8374: if(prevfcast==1){
8375: /* if(stepm ==1){*/
8376: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
8377: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8378: /* } */
8379: /* else{ */
8380: /* erreur=108; */
8381: /* 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); */
8382: /* 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); */
8383: /* } */
8384: }
8385:
8386: /* ------ Other prevalence ratios------------ */
8387:
8388: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8389:
8390: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8391: /* 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",\
8392: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8393: */
8394:
8395: if (mobilav!=0) {
8396: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8397: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8398: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8399: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8400: }
8401: }
8402:
8403:
8404: /*---------- Health expectancies, no variances ------------*/
8405:
8406: strcpy(filerese,"E_");
8407: strcat(filerese,fileresu);
8408: if((ficreseij=fopen(filerese,"w"))==NULL) {
8409: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8410: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8411: }
8412: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8413: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
8414: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8415: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8416:
8417: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8418: fprintf(ficreseij,"\n#****** ");
8419: for(j=1;j<=cptcoveff;j++) {
8420: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8421: }
8422: fprintf(ficreseij,"******\n");
8423:
8424: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8425: oldm=oldms;savm=savms;
8426: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8427:
8428: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8429: /*}*/
8430: }
8431: fclose(ficreseij);
8432: printf("done evsij\n");fflush(stdout);
8433: fprintf(ficlog,"done evsij\n");fflush(ficlog);
8434:
8435: /*---------- Health expectancies and variances ------------*/
8436:
8437:
8438: strcpy(filerest,"T_");
8439: strcat(filerest,fileresu);
8440: if((ficrest=fopen(filerest,"w"))==NULL) {
8441: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8442: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8443: }
8444: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8445: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
8446:
8447:
8448: strcpy(fileresstde,"STDE_");
8449: strcat(fileresstde,fileresu);
8450: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8451: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8452: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8453: }
8454: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8455: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8456:
8457: strcpy(filerescve,"CVE_");
8458: strcat(filerescve,fileresu);
8459: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8460: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8461: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8462: }
8463: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8464: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8465:
8466: strcpy(fileresv,"V_");
8467: strcat(fileresv,fileresu);
8468: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8469: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8470: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8471: }
8472: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8473: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
8474:
8475: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8476: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8477:
8478: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8479: fprintf(ficrest,"\n#****** ");
8480: for(j=1;j<=cptcoveff;j++)
8481: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8482: fprintf(ficrest,"******\n");
8483:
8484: fprintf(ficresstdeij,"\n#****** ");
8485: fprintf(ficrescveij,"\n#****** ");
8486: for(j=1;j<=cptcoveff;j++) {
8487: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8488: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8489: }
8490: fprintf(ficresstdeij,"******\n");
8491: fprintf(ficrescveij,"******\n");
8492:
8493: fprintf(ficresvij,"\n#****** ");
8494: for(j=1;j<=cptcoveff;j++)
8495: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8496: fprintf(ficresvij,"******\n");
8497:
8498: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8499: oldm=oldms;savm=savms;
8500: printf(" cvevsij %d, ",k);
8501: fprintf(ficlog, " cvevsij %d, ",k);
8502: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8503: printf(" end cvevsij \n ");
8504: fprintf(ficlog, " end cvevsij \n ");
8505:
8506: /*
8507: */
8508: /* goto endfree; */
8509:
8510: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8511: pstamp(ficrest);
8512:
8513:
8514: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8515: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8516: cptcod= 0; /* To be deleted */
8517: printf("varevsij %d \n",vpopbased);
8518: fprintf(ficlog, "varevsij %d \n",vpopbased);
8519: 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 */
8520: 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 ");
8521: if(vpopbased==1)
8522: 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);
8523: else
8524: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8525: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8526: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8527: fprintf(ficrest,"\n");
8528: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8529: epj=vector(1,nlstate+1);
8530: printf("Computing age specific period (stable) prevalences in each health state \n");
8531: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8532: for(age=bage; age <=fage ;age++){
8533: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
8534: if (vpopbased==1) {
8535: if(mobilav ==0){
8536: for(i=1; i<=nlstate;i++)
8537: prlim[i][i]=probs[(int)age][i][k];
8538: }else{ /* mobilav */
8539: for(i=1; i<=nlstate;i++)
8540: prlim[i][i]=mobaverage[(int)age][i][k];
8541: }
8542: }
8543:
8544: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8545: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8546: /* printf(" age %4.0f ",age); */
8547: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8548: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8549: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8550: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8551: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8552: }
8553: epj[nlstate+1] +=epj[j];
8554: }
8555: /* printf(" age %4.0f \n",age); */
8556:
8557: for(i=1, vepp=0.;i <=nlstate;i++)
8558: for(j=1;j <=nlstate;j++)
8559: vepp += vareij[i][j][(int)age];
8560: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8561: for(j=1;j <=nlstate;j++){
8562: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8563: }
8564: fprintf(ficrest,"\n");
8565: }
8566: } /* End vpopbased */
8567: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8568: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8569: free_vector(epj,1,nlstate+1);
8570: printf("done \n");fflush(stdout);
8571: fprintf(ficlog,"done\n");fflush(ficlog);
8572:
8573: /*}*/
8574: } /* End k */
8575: free_vector(weight,1,n);
8576: free_imatrix(Tvard,1,NCOVMAX,1,2);
8577: free_imatrix(s,1,maxwav+1,1,n);
8578: free_matrix(anint,1,maxwav,1,n);
8579: free_matrix(mint,1,maxwav,1,n);
8580: free_ivector(cod,1,n);
8581: free_ivector(tab,1,NCOVMAX);
8582: fclose(ficresstdeij);
8583: fclose(ficrescveij);
8584: fclose(ficresvij);
8585: fclose(ficrest);
8586: printf("done Health expectancies\n");fflush(stdout);
8587: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
8588: fclose(ficpar);
8589:
8590: /*------- Variance of period (stable) prevalence------*/
8591:
8592: strcpy(fileresvpl,"VPL_");
8593: strcat(fileresvpl,fileresu);
8594: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8595: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8596: exit(0);
8597: }
8598: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8599: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
8600:
8601: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8602: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8603:
8604: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8605: fprintf(ficresvpl,"\n#****** ");
8606: for(j=1;j<=cptcoveff;j++)
8607: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8608: fprintf(ficresvpl,"******\n");
8609:
8610: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8611: oldm=oldms;savm=savms;
8612: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
8613: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8614: /*}*/
8615: }
8616:
8617: fclose(ficresvpl);
8618: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8619: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
8620:
8621: /*---------- End : free ----------------*/
8622: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8623: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8624: } /* mle==-3 arrives here for freeing */
8625: /* endfree:*/
8626: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8627: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8628: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8629: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8630: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8631: free_matrix(covar,0,NCOVMAX,1,n);
8632: free_matrix(matcov,1,npar,1,npar);
8633: free_matrix(hess,1,npar,1,npar);
8634: /*free_vector(delti,1,npar);*/
8635: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8636: free_matrix(agev,1,maxwav,1,imx);
8637: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8638:
8639: free_ivector(ncodemax,1,NCOVMAX);
8640: free_ivector(ncodemaxwundef,1,NCOVMAX);
8641: free_ivector(Tvar,1,NCOVMAX);
8642: free_ivector(Tprod,1,NCOVMAX);
8643: free_ivector(Tvaraff,1,NCOVMAX);
8644: free_ivector(Tage,1,NCOVMAX);
8645:
8646: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8647: /* free_imatrix(codtab,1,100,1,10); */
8648: fflush(fichtm);
8649: fflush(ficgp);
8650:
8651:
8652: if((nberr >0) || (nbwarn>0)){
8653: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8654: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8655: }else{
8656: printf("End of Imach\n");
8657: fprintf(ficlog,"End of Imach\n");
8658: }
8659: printf("See log file on %s\n",filelog);
8660: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8661: /*(void) gettimeofday(&end_time,&tzp);*/
8662: rend_time = time(NULL);
8663: end_time = *localtime(&rend_time);
8664: /* tml = *localtime(&end_time.tm_sec); */
8665: strcpy(strtend,asctime(&end_time));
8666: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8667: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8668: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8669:
8670: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8671: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8672: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8673: /* printf("Total time was %d uSec.\n", total_usecs);*/
8674: /* if(fileappend(fichtm,optionfilehtm)){ */
8675: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8676: fclose(fichtm);
8677: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8678: fclose(fichtmcov);
8679: fclose(ficgp);
8680: fclose(ficlog);
8681: /*------ End -----------*/
8682:
8683:
8684: printf("Before Current directory %s!\n",pathcd);
8685: #ifdef WIN32
8686: if (_chdir(pathcd) != 0)
8687: printf("Can't move to directory %s!\n",path);
8688: if(_getcwd(pathcd,MAXLINE) > 0)
8689: #else
8690: if(chdir(pathcd) != 0)
8691: printf("Can't move to directory %s!\n", path);
8692: if (getcwd(pathcd, MAXLINE) > 0)
8693: #endif
8694: printf("Current directory %s!\n",pathcd);
8695: /*strcat(plotcmd,CHARSEPARATOR);*/
8696: sprintf(plotcmd,"gnuplot");
8697: #ifdef _WIN32
8698: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8699: #endif
8700: if(!stat(plotcmd,&info)){
8701: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8702: if(!stat(getenv("GNUPLOTBIN"),&info)){
8703: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8704: }else
8705: strcpy(pplotcmd,plotcmd);
8706: #ifdef __unix
8707: strcpy(plotcmd,GNUPLOTPROGRAM);
8708: if(!stat(plotcmd,&info)){
8709: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8710: }else
8711: strcpy(pplotcmd,plotcmd);
8712: #endif
8713: }else
8714: strcpy(pplotcmd,plotcmd);
8715:
8716: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8717: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8718:
8719: if((outcmd=system(plotcmd)) != 0){
8720: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8721: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8722: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8723: if((outcmd=system(plotcmd)) != 0)
8724: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8725: }
8726: printf(" Successful, please wait...");
8727: while (z[0] != 'q') {
8728: /* chdir(path); */
8729: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8730: scanf("%s",z);
8731: /* if (z[0] == 'c') system("./imach"); */
8732: if (z[0] == 'e') {
8733: #ifdef __APPLE__
8734: sprintf(pplotcmd, "open %s", optionfilehtm);
8735: #elif __linux
8736: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8737: #else
8738: sprintf(pplotcmd, "%s", optionfilehtm);
8739: #endif
8740: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8741: system(pplotcmd);
8742: }
8743: else if (z[0] == 'g') system(plotcmd);
8744: else if (z[0] == 'q') exit(0);
8745: }
8746: end:
8747: while (z[0] != 'q') {
8748: printf("\nType q for exiting: "); fflush(stdout);
8749: scanf("%s",z);
8750: }
8751: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>