1: /* $Id: imach.c,v 1.208 2015/11/17 14:31:57 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.208 2015/11/17 14:31:57 brouard
5: Summary: temporary
6:
7: Revision 1.207 2015/10/27 17:36:57 brouard
8: *** empty log message ***
9:
10: Revision 1.206 2015/10/24 07:14:11 brouard
11: *** empty log message ***
12:
13: Revision 1.205 2015/10/23 15:50:53 brouard
14: Summary: 0.98r3 some clarification for graphs on likelihood contributions
15:
16: Revision 1.204 2015/10/01 16:20:26 brouard
17: Summary: Some new graphs of contribution to likelihood
18:
19: Revision 1.203 2015/09/30 17:45:14 brouard
20: Summary: looking at better estimation of the hessian
21:
22: Also a better criteria for convergence to the period prevalence And
23: therefore adding the number of years needed to converge. (The
24: prevalence in any alive state shold sum to one
25:
26: Revision 1.202 2015/09/22 19:45:16 brouard
27: Summary: Adding some overall graph on contribution to likelihood. Might change
28:
29: Revision 1.201 2015/09/15 17:34:58 brouard
30: Summary: 0.98r0
31:
32: - Some new graphs like suvival functions
33: - Some bugs fixed like model=1+age+V2.
34:
35: Revision 1.200 2015/09/09 16:53:55 brouard
36: Summary: Big bug thanks to Flavia
37:
38: Even model=1+age+V2. did not work anymore
39:
40: Revision 1.199 2015/09/07 14:09:23 brouard
41: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
42:
43: Revision 1.198 2015/09/03 07:14:39 brouard
44: Summary: 0.98q5 Flavia
45:
46: Revision 1.197 2015/09/01 18:24:39 brouard
47: *** empty log message ***
48:
49: Revision 1.196 2015/08/18 23:17:52 brouard
50: Summary: 0.98q5
51:
52: Revision 1.195 2015/08/18 16:28:39 brouard
53: Summary: Adding a hack for testing purpose
54:
55: After reading the title, ftol and model lines, if the comment line has
56: a q, starting with #q, the answer at the end of the run is quit. It
57: permits to run test files in batch with ctest. The former workaround was
58: $ echo q | imach foo.imach
59:
60: Revision 1.194 2015/08/18 13:32:00 brouard
61: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
62:
63: Revision 1.193 2015/08/04 07:17:42 brouard
64: Summary: 0.98q4
65:
66: Revision 1.192 2015/07/16 16:49:02 brouard
67: Summary: Fixing some outputs
68:
69: Revision 1.191 2015/07/14 10:00:33 brouard
70: Summary: Some fixes
71:
72: Revision 1.190 2015/05/05 08:51:13 brouard
73: Summary: Adding digits in output parameters (7 digits instead of 6)
74:
75: Fix 1+age+.
76:
77: Revision 1.189 2015/04/30 14:45:16 brouard
78: Summary: 0.98q2
79:
80: Revision 1.188 2015/04/30 08:27:53 brouard
81: *** empty log message ***
82:
83: Revision 1.187 2015/04/29 09:11:15 brouard
84: *** empty log message ***
85:
86: Revision 1.186 2015/04/23 12:01:52 brouard
87: Summary: V1*age is working now, version 0.98q1
88:
89: Some codes had been disabled in order to simplify and Vn*age was
90: working in the optimization phase, ie, giving correct MLE parameters,
91: but, as usual, outputs were not correct and program core dumped.
92:
93: Revision 1.185 2015/03/11 13:26:42 brouard
94: Summary: Inclusion of compile and links command line for Intel Compiler
95:
96: Revision 1.184 2015/03/11 11:52:39 brouard
97: Summary: Back from Windows 8. Intel Compiler
98:
99: Revision 1.183 2015/03/10 20:34:32 brouard
100: Summary: 0.98q0, trying with directest, mnbrak fixed
101:
102: We use directest instead of original Powell test; probably no
103: incidence on the results, but better justifications;
104: We fixed Numerical Recipes mnbrak routine which was wrong and gave
105: wrong results.
106:
107: Revision 1.182 2015/02/12 08:19:57 brouard
108: Summary: Trying to keep directest which seems simpler and more general
109: Author: Nicolas Brouard
110:
111: Revision 1.181 2015/02/11 23:22:24 brouard
112: Summary: Comments on Powell added
113:
114: Author:
115:
116: Revision 1.180 2015/02/11 17:33:45 brouard
117: Summary: Finishing move from main to function (hpijx and prevalence_limit)
118:
119: Revision 1.179 2015/01/04 09:57:06 brouard
120: Summary: back to OS/X
121:
122: Revision 1.178 2015/01/04 09:35:48 brouard
123: *** empty log message ***
124:
125: Revision 1.177 2015/01/03 18:40:56 brouard
126: Summary: Still testing ilc32 on OSX
127:
128: Revision 1.176 2015/01/03 16:45:04 brouard
129: *** empty log message ***
130:
131: Revision 1.175 2015/01/03 16:33:42 brouard
132: *** empty log message ***
133:
134: Revision 1.174 2015/01/03 16:15:49 brouard
135: Summary: Still in cross-compilation
136:
137: Revision 1.173 2015/01/03 12:06:26 brouard
138: Summary: trying to detect cross-compilation
139:
140: Revision 1.172 2014/12/27 12:07:47 brouard
141: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
142:
143: Revision 1.171 2014/12/23 13:26:59 brouard
144: Summary: Back from Visual C
145:
146: Still problem with utsname.h on Windows
147:
148: Revision 1.170 2014/12/23 11:17:12 brouard
149: Summary: Cleaning some \%% back to %%
150:
151: The escape was mandatory for a specific compiler (which one?), but too many warnings.
152:
153: Revision 1.169 2014/12/22 23:08:31 brouard
154: Summary: 0.98p
155:
156: Outputs some informations on compiler used, OS etc. Testing on different platforms.
157:
158: Revision 1.168 2014/12/22 15:17:42 brouard
159: Summary: update
160:
161: Revision 1.167 2014/12/22 13:50:56 brouard
162: Summary: Testing uname and compiler version and if compiled 32 or 64
163:
164: Testing on Linux 64
165:
166: Revision 1.166 2014/12/22 11:40:47 brouard
167: *** empty log message ***
168:
169: Revision 1.165 2014/12/16 11:20:36 brouard
170: Summary: After compiling on Visual C
171:
172: * imach.c (Module): Merging 1.61 to 1.162
173:
174: Revision 1.164 2014/12/16 10:52:11 brouard
175: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
176:
177: * imach.c (Module): Merging 1.61 to 1.162
178:
179: Revision 1.163 2014/12/16 10:30:11 brouard
180: * imach.c (Module): Merging 1.61 to 1.162
181:
182: Revision 1.162 2014/09/25 11:43:39 brouard
183: Summary: temporary backup 0.99!
184:
185: Revision 1.1 2014/09/16 11:06:58 brouard
186: Summary: With some code (wrong) for nlopt
187:
188: Author:
189:
190: Revision 1.161 2014/09/15 20:41:41 brouard
191: Summary: Problem with macro SQR on Intel compiler
192:
193: Revision 1.160 2014/09/02 09:24:05 brouard
194: *** empty log message ***
195:
196: Revision 1.159 2014/09/01 10:34:10 brouard
197: Summary: WIN32
198: Author: Brouard
199:
200: Revision 1.158 2014/08/27 17:11:51 brouard
201: *** empty log message ***
202:
203: Revision 1.157 2014/08/27 16:26:55 brouard
204: Summary: Preparing windows Visual studio version
205: Author: Brouard
206:
207: In order to compile on Visual studio, time.h is now correct and time_t
208: and tm struct should be used. difftime should be used but sometimes I
209: just make the differences in raw time format (time(&now).
210: Trying to suppress #ifdef LINUX
211: Add xdg-open for __linux in order to open default browser.
212:
213: Revision 1.156 2014/08/25 20:10:10 brouard
214: *** empty log message ***
215:
216: Revision 1.155 2014/08/25 18:32:34 brouard
217: Summary: New compile, minor changes
218: Author: Brouard
219:
220: Revision 1.154 2014/06/20 17:32:08 brouard
221: Summary: Outputs now all graphs of convergence to period prevalence
222:
223: Revision 1.153 2014/06/20 16:45:46 brouard
224: Summary: If 3 live state, convergence to period prevalence on same graph
225: Author: Brouard
226:
227: Revision 1.152 2014/06/18 17:54:09 brouard
228: Summary: open browser, use gnuplot on same dir than imach if not found in the path
229:
230: Revision 1.151 2014/06/18 16:43:30 brouard
231: *** empty log message ***
232:
233: Revision 1.150 2014/06/18 16:42:35 brouard
234: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
235: Author: brouard
236:
237: Revision 1.149 2014/06/18 15:51:14 brouard
238: Summary: Some fixes in parameter files errors
239: Author: Nicolas Brouard
240:
241: Revision 1.148 2014/06/17 17:38:48 brouard
242: Summary: Nothing new
243: Author: Brouard
244:
245: Just a new packaging for OS/X version 0.98nS
246:
247: Revision 1.147 2014/06/16 10:33:11 brouard
248: *** empty log message ***
249:
250: Revision 1.146 2014/06/16 10:20:28 brouard
251: Summary: Merge
252: Author: Brouard
253:
254: Merge, before building revised version.
255:
256: Revision 1.145 2014/06/10 21:23:15 brouard
257: Summary: Debugging with valgrind
258: Author: Nicolas Brouard
259:
260: Lot of changes in order to output the results with some covariates
261: After the Edimburgh REVES conference 2014, it seems mandatory to
262: improve the code.
263: No more memory valgrind error but a lot has to be done in order to
264: continue the work of splitting the code into subroutines.
265: Also, decodemodel has been improved. Tricode is still not
266: optimal. nbcode should be improved. Documentation has been added in
267: the source code.
268:
269: Revision 1.143 2014/01/26 09:45:38 brouard
270: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
271:
272: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
273: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
274:
275: Revision 1.142 2014/01/26 03:57:36 brouard
276: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
277:
278: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
279:
280: Revision 1.141 2014/01/26 02:42:01 brouard
281: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
282:
283: Revision 1.140 2011/09/02 10:37:54 brouard
284: Summary: times.h is ok with mingw32 now.
285:
286: Revision 1.139 2010/06/14 07:50:17 brouard
287: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
288: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
289:
290: Revision 1.138 2010/04/30 18:19:40 brouard
291: *** empty log message ***
292:
293: Revision 1.137 2010/04/29 18:11:38 brouard
294: (Module): Checking covariates for more complex models
295: than V1+V2. A lot of change to be done. Unstable.
296:
297: Revision 1.136 2010/04/26 20:30:53 brouard
298: (Module): merging some libgsl code. Fixing computation
299: of likelione (using inter/intrapolation if mle = 0) in order to
300: get same likelihood as if mle=1.
301: Some cleaning of code and comments added.
302:
303: Revision 1.135 2009/10/29 15:33:14 brouard
304: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
305:
306: Revision 1.134 2009/10/29 13:18:53 brouard
307: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
308:
309: Revision 1.133 2009/07/06 10:21:25 brouard
310: just nforces
311:
312: Revision 1.132 2009/07/06 08:22:05 brouard
313: Many tings
314:
315: Revision 1.131 2009/06/20 16:22:47 brouard
316: Some dimensions resccaled
317:
318: Revision 1.130 2009/05/26 06:44:34 brouard
319: (Module): Max Covariate is now set to 20 instead of 8. A
320: lot of cleaning with variables initialized to 0. Trying to make
321: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
322:
323: Revision 1.129 2007/08/31 13:49:27 lievre
324: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
325:
326: Revision 1.128 2006/06/30 13:02:05 brouard
327: (Module): Clarifications on computing e.j
328:
329: Revision 1.127 2006/04/28 18:11:50 brouard
330: (Module): Yes the sum of survivors was wrong since
331: imach-114 because nhstepm was no more computed in the age
332: loop. Now we define nhstepma in the age loop.
333: (Module): In order to speed up (in case of numerous covariates) we
334: compute health expectancies (without variances) in a first step
335: and then all the health expectancies with variances or standard
336: deviation (needs data from the Hessian matrices) which slows the
337: computation.
338: In the future we should be able to stop the program is only health
339: expectancies and graph are needed without standard deviations.
340:
341: Revision 1.126 2006/04/28 17:23:28 brouard
342: (Module): Yes the sum of survivors was wrong since
343: imach-114 because nhstepm was no more computed in the age
344: loop. Now we define nhstepma in the age loop.
345: Version 0.98h
346:
347: Revision 1.125 2006/04/04 15:20:31 lievre
348: Errors in calculation of health expectancies. Age was not initialized.
349: Forecasting file added.
350:
351: Revision 1.124 2006/03/22 17:13:53 lievre
352: Parameters are printed with %lf instead of %f (more numbers after the comma).
353: The log-likelihood is printed in the log file
354:
355: Revision 1.123 2006/03/20 10:52:43 brouard
356: * imach.c (Module): <title> changed, corresponds to .htm file
357: name. <head> headers where missing.
358:
359: * imach.c (Module): Weights can have a decimal point as for
360: English (a comma might work with a correct LC_NUMERIC environment,
361: otherwise the weight is truncated).
362: Modification of warning when the covariates values are not 0 or
363: 1.
364: Version 0.98g
365:
366: Revision 1.122 2006/03/20 09:45:41 brouard
367: (Module): Weights can have a decimal point as for
368: English (a comma might work with a correct LC_NUMERIC environment,
369: otherwise the weight is truncated).
370: Modification of warning when the covariates values are not 0 or
371: 1.
372: Version 0.98g
373:
374: Revision 1.121 2006/03/16 17:45:01 lievre
375: * imach.c (Module): Comments concerning covariates added
376:
377: * imach.c (Module): refinements in the computation of lli if
378: status=-2 in order to have more reliable computation if stepm is
379: not 1 month. Version 0.98f
380:
381: Revision 1.120 2006/03/16 15:10:38 lievre
382: (Module): refinements in the computation of lli if
383: status=-2 in order to have more reliable computation if stepm is
384: not 1 month. Version 0.98f
385:
386: Revision 1.119 2006/03/15 17:42:26 brouard
387: (Module): Bug if status = -2, the loglikelihood was
388: computed as likelihood omitting the logarithm. Version O.98e
389:
390: Revision 1.118 2006/03/14 18:20:07 brouard
391: (Module): varevsij Comments added explaining the second
392: table of variances if popbased=1 .
393: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
394: (Module): Function pstamp added
395: (Module): Version 0.98d
396:
397: Revision 1.117 2006/03/14 17:16:22 brouard
398: (Module): varevsij Comments added explaining the second
399: table of variances if popbased=1 .
400: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
401: (Module): Function pstamp added
402: (Module): Version 0.98d
403:
404: Revision 1.116 2006/03/06 10:29:27 brouard
405: (Module): Variance-covariance wrong links and
406: varian-covariance of ej. is needed (Saito).
407:
408: Revision 1.115 2006/02/27 12:17:45 brouard
409: (Module): One freematrix added in mlikeli! 0.98c
410:
411: Revision 1.114 2006/02/26 12:57:58 brouard
412: (Module): Some improvements in processing parameter
413: filename with strsep.
414:
415: Revision 1.113 2006/02/24 14:20:24 brouard
416: (Module): Memory leaks checks with valgrind and:
417: datafile was not closed, some imatrix were not freed and on matrix
418: allocation too.
419:
420: Revision 1.112 2006/01/30 09:55:26 brouard
421: (Module): Back to gnuplot.exe instead of wgnuplot.exe
422:
423: Revision 1.111 2006/01/25 20:38:18 brouard
424: (Module): Lots of cleaning and bugs added (Gompertz)
425: (Module): Comments can be added in data file. Missing date values
426: can be a simple dot '.'.
427:
428: Revision 1.110 2006/01/25 00:51:50 brouard
429: (Module): Lots of cleaning and bugs added (Gompertz)
430:
431: Revision 1.109 2006/01/24 19:37:15 brouard
432: (Module): Comments (lines starting with a #) are allowed in data.
433:
434: Revision 1.108 2006/01/19 18:05:42 lievre
435: Gnuplot problem appeared...
436: To be fixed
437:
438: Revision 1.107 2006/01/19 16:20:37 brouard
439: Test existence of gnuplot in imach path
440:
441: Revision 1.106 2006/01/19 13:24:36 brouard
442: Some cleaning and links added in html output
443:
444: Revision 1.105 2006/01/05 20:23:19 lievre
445: *** empty log message ***
446:
447: Revision 1.104 2005/09/30 16:11:43 lievre
448: (Module): sump fixed, loop imx fixed, and simplifications.
449: (Module): If the status is missing at the last wave but we know
450: that the person is alive, then we can code his/her status as -2
451: (instead of missing=-1 in earlier versions) and his/her
452: contributions to the likelihood is 1 - Prob of dying from last
453: health status (= 1-p13= p11+p12 in the easiest case of somebody in
454: the healthy state at last known wave). Version is 0.98
455:
456: Revision 1.103 2005/09/30 15:54:49 lievre
457: (Module): sump fixed, loop imx fixed, and simplifications.
458:
459: Revision 1.102 2004/09/15 17:31:30 brouard
460: Add the possibility to read data file including tab characters.
461:
462: Revision 1.101 2004/09/15 10:38:38 brouard
463: Fix on curr_time
464:
465: Revision 1.100 2004/07/12 18:29:06 brouard
466: Add version for Mac OS X. Just define UNIX in Makefile
467:
468: Revision 1.99 2004/06/05 08:57:40 brouard
469: *** empty log message ***
470:
471: Revision 1.98 2004/05/16 15:05:56 brouard
472: New version 0.97 . First attempt to estimate force of mortality
473: directly from the data i.e. without the need of knowing the health
474: state at each age, but using a Gompertz model: log u =a + b*age .
475: This is the basic analysis of mortality and should be done before any
476: other analysis, in order to test if the mortality estimated from the
477: cross-longitudinal survey is different from the mortality estimated
478: from other sources like vital statistic data.
479:
480: The same imach parameter file can be used but the option for mle should be -3.
481:
482: Agnès, who wrote this part of the code, tried to keep most of the
483: former routines in order to include the new code within the former code.
484:
485: The output is very simple: only an estimate of the intercept and of
486: the slope with 95% confident intervals.
487:
488: Current limitations:
489: A) Even if you enter covariates, i.e. with the
490: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
491: B) There is no computation of Life Expectancy nor Life Table.
492:
493: Revision 1.97 2004/02/20 13:25:42 lievre
494: Version 0.96d. Population forecasting command line is (temporarily)
495: suppressed.
496:
497: Revision 1.96 2003/07/15 15:38:55 brouard
498: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
499: rewritten within the same printf. Workaround: many printfs.
500:
501: Revision 1.95 2003/07/08 07:54:34 brouard
502: * imach.c (Repository):
503: (Repository): Using imachwizard code to output a more meaningful covariance
504: matrix (cov(a12,c31) instead of numbers.
505:
506: Revision 1.94 2003/06/27 13:00:02 brouard
507: Just cleaning
508:
509: Revision 1.93 2003/06/25 16:33:55 brouard
510: (Module): On windows (cygwin) function asctime_r doesn't
511: exist so I changed back to asctime which exists.
512: (Module): Version 0.96b
513:
514: Revision 1.92 2003/06/25 16:30:45 brouard
515: (Module): On windows (cygwin) function asctime_r doesn't
516: exist so I changed back to asctime which exists.
517:
518: Revision 1.91 2003/06/25 15:30:29 brouard
519: * imach.c (Repository): Duplicated warning errors corrected.
520: (Repository): Elapsed time after each iteration is now output. It
521: helps to forecast when convergence will be reached. Elapsed time
522: is stamped in powell. We created a new html file for the graphs
523: concerning matrix of covariance. It has extension -cov.htm.
524:
525: Revision 1.90 2003/06/24 12:34:15 brouard
526: (Module): Some bugs corrected for windows. Also, when
527: mle=-1 a template is output in file "or"mypar.txt with the design
528: of the covariance matrix to be input.
529:
530: Revision 1.89 2003/06/24 12:30:52 brouard
531: (Module): Some bugs corrected for windows. Also, when
532: mle=-1 a template is output in file "or"mypar.txt with the design
533: of the covariance matrix to be input.
534:
535: Revision 1.88 2003/06/23 17:54:56 brouard
536: * 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.
537:
538: Revision 1.87 2003/06/18 12:26:01 brouard
539: Version 0.96
540:
541: Revision 1.86 2003/06/17 20:04:08 brouard
542: (Module): Change position of html and gnuplot routines and added
543: routine fileappend.
544:
545: Revision 1.85 2003/06/17 13:12:43 brouard
546: * imach.c (Repository): Check when date of death was earlier that
547: current date of interview. It may happen when the death was just
548: prior to the death. In this case, dh was negative and likelihood
549: was wrong (infinity). We still send an "Error" but patch by
550: assuming that the date of death was just one stepm after the
551: interview.
552: (Repository): Because some people have very long ID (first column)
553: we changed int to long in num[] and we added a new lvector for
554: memory allocation. But we also truncated to 8 characters (left
555: truncation)
556: (Repository): No more line truncation errors.
557:
558: Revision 1.84 2003/06/13 21:44:43 brouard
559: * imach.c (Repository): Replace "freqsummary" at a correct
560: place. It differs from routine "prevalence" which may be called
561: many times. Probs is memory consuming and must be used with
562: parcimony.
563: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
564:
565: Revision 1.83 2003/06/10 13:39:11 lievre
566: *** empty log message ***
567:
568: Revision 1.82 2003/06/05 15:57:20 brouard
569: Add log in imach.c and fullversion number is now printed.
570:
571: */
572: /*
573: Interpolated Markov Chain
574:
575: Short summary of the programme:
576:
577: This program computes Healthy Life Expectancies from
578: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
579: first survey ("cross") where individuals from different ages are
580: interviewed on their health status or degree of disability (in the
581: case of a health survey which is our main interest) -2- at least a
582: second wave of interviews ("longitudinal") which measure each change
583: (if any) in individual health status. Health expectancies are
584: computed from the time spent in each health state according to a
585: model. More health states you consider, more time is necessary to reach the
586: Maximum Likelihood of the parameters involved in the model. The
587: simplest model is the multinomial logistic model where pij is the
588: probability to be observed in state j at the second wave
589: conditional to be observed in state i at the first wave. Therefore
590: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
591: 'age' is age and 'sex' is a covariate. If you want to have a more
592: complex model than "constant and age", you should modify the program
593: where the markup *Covariates have to be included here again* invites
594: you to do it. More covariates you add, slower the
595: convergence.
596:
597: The advantage of this computer programme, compared to a simple
598: multinomial logistic model, is clear when the delay between waves is not
599: identical for each individual. Also, if a individual missed an
600: intermediate interview, the information is lost, but taken into
601: account using an interpolation or extrapolation.
602:
603: hPijx is the probability to be observed in state i at age x+h
604: conditional to the observed state i at age x. The delay 'h' can be
605: split into an exact number (nh*stepm) of unobserved intermediate
606: states. This elementary transition (by month, quarter,
607: semester or year) is modelled as a multinomial logistic. The hPx
608: matrix is simply the matrix product of nh*stepm elementary matrices
609: and the contribution of each individual to the likelihood is simply
610: hPijx.
611:
612: Also this programme outputs the covariance matrix of the parameters but also
613: of the life expectancies. It also computes the period (stable) prevalence.
614:
615: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
616: Institut national d'études démographiques, Paris.
617: This software have been partly granted by Euro-REVES, a concerted action
618: from the European Union.
619: It is copyrighted identically to a GNU software product, ie programme and
620: software can be distributed freely for non commercial use. Latest version
621: can be accessed at http://euroreves.ined.fr/imach .
622:
623: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
624: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
625:
626: **********************************************************************/
627: /*
628: main
629: read parameterfile
630: read datafile
631: concatwav
632: freqsummary
633: if (mle >= 1)
634: mlikeli
635: print results files
636: if mle==1
637: computes hessian
638: read end of parameter file: agemin, agemax, bage, fage, estepm
639: begin-prev-date,...
640: open gnuplot file
641: open html file
642: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
643: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
644: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
645: freexexit2 possible for memory heap.
646:
647: h Pij x | pij_nom ficrestpij
648: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
649: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
650: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
651:
652: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
653: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
654: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
655: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
656: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
657:
658: forecasting if prevfcast==1 prevforecast call prevalence()
659: health expectancies
660: Variance-covariance of DFLE
661: prevalence()
662: movingaverage()
663: varevsij()
664: if popbased==1 varevsij(,popbased)
665: total life expectancies
666: Variance of period (stable) prevalence
667: end
668: */
669:
670: /* #define DEBUG */
671: /* #define DEBUGBRENT */
672: /* #define DEBUGLINMIN */
673: /* #define DEBUGHESS */
674: #define DEBUGHESSIJ
675: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
676: #define POWELL /* Instead of NLOPT */
677: #define POWELLF1F3 /* Skip test */
678: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
679: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
680:
681: #include <math.h>
682: #include <stdio.h>
683: #include <stdlib.h>
684: #include <string.h>
685:
686: #ifdef _WIN32
687: #include <io.h>
688: #include <windows.h>
689: #include <tchar.h>
690: #else
691: #include <unistd.h>
692: #endif
693:
694: #include <limits.h>
695: #include <sys/types.h>
696:
697: #if defined(__GNUC__)
698: #include <sys/utsname.h> /* Doesn't work on Windows */
699: #endif
700:
701: #include <sys/stat.h>
702: #include <errno.h>
703: /* extern int errno; */
704:
705: /* #ifdef LINUX */
706: /* #include <time.h> */
707: /* #include "timeval.h" */
708: /* #else */
709: /* #include <sys/time.h> */
710: /* #endif */
711:
712: #include <time.h>
713:
714: #ifdef GSL
715: #include <gsl/gsl_errno.h>
716: #include <gsl/gsl_multimin.h>
717: #endif
718:
719:
720: #ifdef NLOPT
721: #include <nlopt.h>
722: typedef struct {
723: double (* function)(double [] );
724: } myfunc_data ;
725: #endif
726:
727: /* #include <libintl.h> */
728: /* #define _(String) gettext (String) */
729:
730: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
731:
732: #define GNUPLOTPROGRAM "gnuplot"
733: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
734: #define FILENAMELENGTH 132
735:
736: #define GLOCK_ERROR_NOPATH -1 /* empty path */
737: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
738:
739: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
740: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
741:
742: #define NINTERVMAX 8
743: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
744: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
745: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
746: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
747: #define MAXN 20000
748: #define YEARM 12. /**< Number of months per year */
749: #define AGESUP 130
750: #define AGEBASE 40
751: #define AGEOVERFLOW 1.e20
752: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
753: #ifdef _WIN32
754: #define DIRSEPARATOR '\\'
755: #define CHARSEPARATOR "\\"
756: #define ODIRSEPARATOR '/'
757: #else
758: #define DIRSEPARATOR '/'
759: #define CHARSEPARATOR "/"
760: #define ODIRSEPARATOR '\\'
761: #endif
762:
763: /* $Id: imach.c,v 1.208 2015/11/17 14:31:57 brouard Exp $ */
764: /* $State: Exp $ */
765: #include "version.h"
766: char version[]=__IMACH_VERSION__;
767: 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";
768: char fullversion[]="$Revision: 1.208 $ $Date: 2015/11/17 14:31:57 $";
769: char strstart[80];
770: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
771: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
772: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
773: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
774: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
775: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
776: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
777: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
778: int cptcovprodnoage=0; /**< Number of covariate products without age */
779: int cptcoveff=0; /* Total number of covariates to vary for printing results */
780: int cptcov=0; /* Working variable */
781: int npar=NPARMAX;
782: int nlstate=2; /* Number of live states */
783: int ndeath=1; /* Number of dead states */
784: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
785: int popbased=0;
786:
787: int *wav; /* Number of waves for this individuual 0 is possible */
788: int maxwav=0; /* Maxim number of waves */
789: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
790: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
791: int gipmx=0, gsw=0; /* Global variables on the number of contributions
792: to the likelihood and the sum of weights (done by funcone)*/
793: int mle=1, weightopt=0;
794: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
795: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
796: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
797: * wave mi and wave mi+1 is not an exact multiple of stepm. */
798: int countcallfunc=0; /* Count the number of calls to func */
799: double jmean=1; /* Mean space between 2 waves */
800: double **matprod2(); /* test */
801: double **oldm, **newm, **savm; /* Working pointers to matrices */
802: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
803: /*FILE *fic ; */ /* Used in readdata only */
804: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
805: FILE *ficlog, *ficrespow;
806: int globpr=0; /* Global variable for printing or not */
807: double fretone; /* Only one call to likelihood */
808: long ipmx=0; /* Number of contributions */
809: double sw; /* Sum of weights */
810: char filerespow[FILENAMELENGTH];
811: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
812: FILE *ficresilk;
813: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
814: FILE *ficresprobmorprev;
815: FILE *fichtm, *fichtmcov; /* Html File */
816: FILE *ficreseij;
817: char filerese[FILENAMELENGTH];
818: FILE *ficresstdeij;
819: char fileresstde[FILENAMELENGTH];
820: FILE *ficrescveij;
821: char filerescve[FILENAMELENGTH];
822: FILE *ficresvij;
823: char fileresv[FILENAMELENGTH];
824: FILE *ficresvpl;
825: char fileresvpl[FILENAMELENGTH];
826: char title[MAXLINE];
827: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
828: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
829: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
830: char command[FILENAMELENGTH];
831: int outcmd=0;
832:
833: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
834: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
835: char filelog[FILENAMELENGTH]; /* Log file */
836: char filerest[FILENAMELENGTH];
837: char fileregp[FILENAMELENGTH];
838: char popfile[FILENAMELENGTH];
839:
840: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
841:
842: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
843: /* struct timezone tzp; */
844: /* extern int gettimeofday(); */
845: struct tm tml, *gmtime(), *localtime();
846:
847: extern time_t time();
848:
849: struct tm start_time, end_time, curr_time, last_time, forecast_time;
850: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
851: struct tm tm;
852:
853: char strcurr[80], strfor[80];
854:
855: char *endptr;
856: long lval;
857: double dval;
858:
859: #define NR_END 1
860: #define FREE_ARG char*
861: #define FTOL 1.0e-10
862:
863: #define NRANSI
864: #define ITMAX 200
865:
866: #define TOL 2.0e-4
867:
868: #define CGOLD 0.3819660
869: #define ZEPS 1.0e-10
870: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
871:
872: #define GOLD 1.618034
873: #define GLIMIT 100.0
874: #define TINY 1.0e-20
875:
876: static double maxarg1,maxarg2;
877: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
878: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
879:
880: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
881: #define rint(a) floor(a+0.5)
882: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
883: #define mytinydouble 1.0e-16
884: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
885: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
886: /* static double dsqrarg; */
887: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
888: static double sqrarg;
889: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
890: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
891: int agegomp= AGEGOMP;
892:
893: int imx;
894: int stepm=1;
895: /* Stepm, step in month: minimum step interpolation*/
896:
897: int estepm;
898: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
899:
900: int m,nb;
901: long *num;
902: int firstpass=0, lastpass=4,*cod, *cens;
903: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
904: covariate for which somebody answered excluding
905: undefined. Usually 2: 0 and 1. */
906: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
907: covariate for which somebody answered including
908: undefined. Usually 3: -1, 0 and 1. */
909: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
910: double **pmmij, ***probs;
911: double *ageexmed,*agecens;
912: double dateintmean=0;
913:
914: double *weight;
915: int **s; /* Status */
916: double *agedc;
917: double **covar; /**< covar[j,i], value of jth covariate for individual i,
918: * covar=matrix(0,NCOVMAX,1,n);
919: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
920: double idx;
921: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
922: int *Tage;
923: int *Ndum; /** Freq of modality (tricode */
924: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
925: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
926: double *lsurv, *lpop, *tpop;
927:
928: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
929: double ftolhess; /**< Tolerance for computing hessian */
930:
931: /**************** split *************************/
932: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
933: {
934: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
935: the name of the file (name), its extension only (ext) and its first part of the name (finame)
936: */
937: char *ss; /* pointer */
938: int l1=0, l2=0; /* length counters */
939:
940: l1 = strlen(path ); /* length of path */
941: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
942: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
943: if ( ss == NULL ) { /* no directory, so determine current directory */
944: strcpy( name, path ); /* we got the fullname name because no directory */
945: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
946: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
947: /* get current working directory */
948: /* extern char* getcwd ( char *buf , int len);*/
949: #ifdef WIN32
950: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
951: #else
952: if (getcwd(dirc, FILENAME_MAX) == NULL) {
953: #endif
954: return( GLOCK_ERROR_GETCWD );
955: }
956: /* got dirc from getcwd*/
957: printf(" DIRC = %s \n",dirc);
958: } else { /* strip directory from path */
959: ss++; /* after this, the filename */
960: l2 = strlen( ss ); /* length of filename */
961: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
962: strcpy( name, ss ); /* save file name */
963: strncpy( dirc, path, l1 - l2 ); /* now the directory */
964: dirc[l1-l2] = '\0'; /* add zero */
965: printf(" DIRC2 = %s \n",dirc);
966: }
967: /* We add a separator at the end of dirc if not exists */
968: l1 = strlen( dirc ); /* length of directory */
969: if( dirc[l1-1] != DIRSEPARATOR ){
970: dirc[l1] = DIRSEPARATOR;
971: dirc[l1+1] = 0;
972: printf(" DIRC3 = %s \n",dirc);
973: }
974: ss = strrchr( name, '.' ); /* find last / */
975: if (ss >0){
976: ss++;
977: strcpy(ext,ss); /* save extension */
978: l1= strlen( name);
979: l2= strlen(ss)+1;
980: strncpy( finame, name, l1-l2);
981: finame[l1-l2]= 0;
982: }
983:
984: return( 0 ); /* we're done */
985: }
986:
987:
988: /******************************************/
989:
990: void replace_back_to_slash(char *s, char*t)
991: {
992: int i;
993: int lg=0;
994: i=0;
995: lg=strlen(t);
996: for(i=0; i<= lg; i++) {
997: (s[i] = t[i]);
998: if (t[i]== '\\') s[i]='/';
999: }
1000: }
1001:
1002: char *trimbb(char *out, char *in)
1003: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1004: char *s;
1005: s=out;
1006: while (*in != '\0'){
1007: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1008: in++;
1009: }
1010: *out++ = *in++;
1011: }
1012: *out='\0';
1013: return s;
1014: }
1015:
1016: /* char *substrchaine(char *out, char *in, char *chain) */
1017: /* { */
1018: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1019: /* char *s, *t; */
1020: /* t=in;s=out; */
1021: /* while ((*in != *chain) && (*in != '\0')){ */
1022: /* *out++ = *in++; */
1023: /* } */
1024:
1025: /* /\* *in matches *chain *\/ */
1026: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1027: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1028: /* } */
1029: /* in--; chain--; */
1030: /* while ( (*in != '\0')){ */
1031: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1032: /* *out++ = *in++; */
1033: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1034: /* } */
1035: /* *out='\0'; */
1036: /* out=s; */
1037: /* return out; */
1038: /* } */
1039: char *substrchaine(char *out, char *in, char *chain)
1040: {
1041: /* Substract chain 'chain' from 'in', return and output 'out' */
1042: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1043:
1044: char *strloc;
1045:
1046: strcpy (out, in);
1047: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1048: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1049: if(strloc != NULL){
1050: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1051: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1052: /* strcpy (strloc, strloc +strlen(chain));*/
1053: }
1054: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1055: return out;
1056: }
1057:
1058:
1059: char *cutl(char *blocc, char *alocc, char *in, char occ)
1060: {
1061: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1062: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1063: gives blocc="abcdef" and alocc="ghi2j".
1064: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1065: */
1066: char *s, *t;
1067: t=in;s=in;
1068: while ((*in != occ) && (*in != '\0')){
1069: *alocc++ = *in++;
1070: }
1071: if( *in == occ){
1072: *(alocc)='\0';
1073: s=++in;
1074: }
1075:
1076: if (s == t) {/* occ not found */
1077: *(alocc-(in-s))='\0';
1078: in=s;
1079: }
1080: while ( *in != '\0'){
1081: *blocc++ = *in++;
1082: }
1083:
1084: *blocc='\0';
1085: return t;
1086: }
1087: char *cutv(char *blocc, char *alocc, char *in, char occ)
1088: {
1089: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1090: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1091: gives blocc="abcdef2ghi" and alocc="j".
1092: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1093: */
1094: char *s, *t;
1095: t=in;s=in;
1096: while (*in != '\0'){
1097: while( *in == occ){
1098: *blocc++ = *in++;
1099: s=in;
1100: }
1101: *blocc++ = *in++;
1102: }
1103: if (s == t) /* occ not found */
1104: *(blocc-(in-s))='\0';
1105: else
1106: *(blocc-(in-s)-1)='\0';
1107: in=s;
1108: while ( *in != '\0'){
1109: *alocc++ = *in++;
1110: }
1111:
1112: *alocc='\0';
1113: return s;
1114: }
1115:
1116: int nbocc(char *s, char occ)
1117: {
1118: int i,j=0;
1119: int lg=20;
1120: i=0;
1121: lg=strlen(s);
1122: for(i=0; i<= lg; i++) {
1123: if (s[i] == occ ) j++;
1124: }
1125: return j;
1126: }
1127:
1128: /* void cutv(char *u,char *v, char*t, char occ) */
1129: /* { */
1130: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1131: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1132: /* gives u="abcdef2ghi" and v="j" *\/ */
1133: /* int i,lg,j,p=0; */
1134: /* i=0; */
1135: /* lg=strlen(t); */
1136: /* for(j=0; j<=lg-1; j++) { */
1137: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1138: /* } */
1139:
1140: /* for(j=0; j<p; j++) { */
1141: /* (u[j] = t[j]); */
1142: /* } */
1143: /* u[p]='\0'; */
1144:
1145: /* for(j=0; j<= lg; j++) { */
1146: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1147: /* } */
1148: /* } */
1149:
1150: #ifdef _WIN32
1151: char * strsep(char **pp, const char *delim)
1152: {
1153: char *p, *q;
1154:
1155: if ((p = *pp) == NULL)
1156: return 0;
1157: if ((q = strpbrk (p, delim)) != NULL)
1158: {
1159: *pp = q + 1;
1160: *q = '\0';
1161: }
1162: else
1163: *pp = 0;
1164: return p;
1165: }
1166: #endif
1167:
1168: /********************** nrerror ********************/
1169:
1170: void nrerror(char error_text[])
1171: {
1172: fprintf(stderr,"ERREUR ...\n");
1173: fprintf(stderr,"%s\n",error_text);
1174: exit(EXIT_FAILURE);
1175: }
1176: /*********************** vector *******************/
1177: double *vector(int nl, int nh)
1178: {
1179: double *v;
1180: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1181: if (!v) nrerror("allocation failure in vector");
1182: return v-nl+NR_END;
1183: }
1184:
1185: /************************ free vector ******************/
1186: void free_vector(double*v, int nl, int nh)
1187: {
1188: free((FREE_ARG)(v+nl-NR_END));
1189: }
1190:
1191: /************************ivector *******************************/
1192: int *ivector(long nl,long nh)
1193: {
1194: int *v;
1195: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1196: if (!v) nrerror("allocation failure in ivector");
1197: return v-nl+NR_END;
1198: }
1199:
1200: /******************free ivector **************************/
1201: void free_ivector(int *v, long nl, long nh)
1202: {
1203: free((FREE_ARG)(v+nl-NR_END));
1204: }
1205:
1206: /************************lvector *******************************/
1207: long *lvector(long nl,long nh)
1208: {
1209: long *v;
1210: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1211: if (!v) nrerror("allocation failure in ivector");
1212: return v-nl+NR_END;
1213: }
1214:
1215: /******************free lvector **************************/
1216: void free_lvector(long *v, long nl, long nh)
1217: {
1218: free((FREE_ARG)(v+nl-NR_END));
1219: }
1220:
1221: /******************* imatrix *******************************/
1222: int **imatrix(long nrl, long nrh, long ncl, long nch)
1223: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1224: {
1225: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1226: int **m;
1227:
1228: /* allocate pointers to rows */
1229: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1230: if (!m) nrerror("allocation failure 1 in matrix()");
1231: m += NR_END;
1232: m -= nrl;
1233:
1234:
1235: /* allocate rows and set pointers to them */
1236: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1237: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1238: m[nrl] += NR_END;
1239: m[nrl] -= ncl;
1240:
1241: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1242:
1243: /* return pointer to array of pointers to rows */
1244: return m;
1245: }
1246:
1247: /****************** free_imatrix *************************/
1248: void free_imatrix(m,nrl,nrh,ncl,nch)
1249: int **m;
1250: long nch,ncl,nrh,nrl;
1251: /* free an int matrix allocated by imatrix() */
1252: {
1253: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1254: free((FREE_ARG) (m+nrl-NR_END));
1255: }
1256:
1257: /******************* matrix *******************************/
1258: double **matrix(long nrl, long nrh, long ncl, long nch)
1259: {
1260: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1261: double **m;
1262:
1263: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1264: if (!m) nrerror("allocation failure 1 in matrix()");
1265: m += NR_END;
1266: m -= nrl;
1267:
1268: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1269: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1270: m[nrl] += NR_END;
1271: m[nrl] -= ncl;
1272:
1273: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1274: return m;
1275: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1276: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1277: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1278: */
1279: }
1280:
1281: /*************************free matrix ************************/
1282: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1283: {
1284: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1285: free((FREE_ARG)(m+nrl-NR_END));
1286: }
1287:
1288: /******************* ma3x *******************************/
1289: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1290: {
1291: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1292: double ***m;
1293:
1294: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1295: if (!m) nrerror("allocation failure 1 in matrix()");
1296: m += NR_END;
1297: m -= nrl;
1298:
1299: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1300: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1301: m[nrl] += NR_END;
1302: m[nrl] -= ncl;
1303:
1304: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1305:
1306: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1307: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1308: m[nrl][ncl] += NR_END;
1309: m[nrl][ncl] -= nll;
1310: for (j=ncl+1; j<=nch; j++)
1311: m[nrl][j]=m[nrl][j-1]+nlay;
1312:
1313: for (i=nrl+1; i<=nrh; i++) {
1314: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1315: for (j=ncl+1; j<=nch; j++)
1316: m[i][j]=m[i][j-1]+nlay;
1317: }
1318: return m;
1319: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1320: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1321: */
1322: }
1323:
1324: /*************************free ma3x ************************/
1325: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1326: {
1327: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1328: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1329: free((FREE_ARG)(m+nrl-NR_END));
1330: }
1331:
1332: /*************** function subdirf ***********/
1333: char *subdirf(char fileres[])
1334: {
1335: /* Caution optionfilefiname is hidden */
1336: strcpy(tmpout,optionfilefiname);
1337: strcat(tmpout,"/"); /* Add to the right */
1338: strcat(tmpout,fileres);
1339: return tmpout;
1340: }
1341:
1342: /*************** function subdirf2 ***********/
1343: char *subdirf2(char fileres[], char *preop)
1344: {
1345:
1346: /* Caution optionfilefiname is hidden */
1347: strcpy(tmpout,optionfilefiname);
1348: strcat(tmpout,"/");
1349: strcat(tmpout,preop);
1350: strcat(tmpout,fileres);
1351: return tmpout;
1352: }
1353:
1354: /*************** function subdirf3 ***********/
1355: char *subdirf3(char fileres[], char *preop, char *preop2)
1356: {
1357:
1358: /* Caution optionfilefiname is hidden */
1359: strcpy(tmpout,optionfilefiname);
1360: strcat(tmpout,"/");
1361: strcat(tmpout,preop);
1362: strcat(tmpout,preop2);
1363: strcat(tmpout,fileres);
1364: return tmpout;
1365: }
1366:
1367: char *asc_diff_time(long time_sec, char ascdiff[])
1368: {
1369: long sec_left, days, hours, minutes;
1370: days = (time_sec) / (60*60*24);
1371: sec_left = (time_sec) % (60*60*24);
1372: hours = (sec_left) / (60*60) ;
1373: sec_left = (sec_left) %(60*60);
1374: minutes = (sec_left) /60;
1375: sec_left = (sec_left) % (60);
1376: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1377: return ascdiff;
1378: }
1379:
1380: /***************** f1dim *************************/
1381: extern int ncom;
1382: extern double *pcom,*xicom;
1383: extern double (*nrfunc)(double []);
1384:
1385: double f1dim(double x)
1386: {
1387: int j;
1388: double f;
1389: double *xt;
1390:
1391: xt=vector(1,ncom);
1392: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1393: f=(*nrfunc)(xt);
1394: free_vector(xt,1,ncom);
1395: return f;
1396: }
1397:
1398: /*****************brent *************************/
1399: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1400: {
1401: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1402: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1403: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1404: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1405: * returned function value.
1406: */
1407: int iter;
1408: double a,b,d,etemp;
1409: double fu=0,fv,fw,fx;
1410: double ftemp=0.;
1411: double p,q,r,tol1,tol2,u,v,w,x,xm;
1412: double e=0.0;
1413:
1414: a=(ax < cx ? ax : cx);
1415: b=(ax > cx ? ax : cx);
1416: x=w=v=bx;
1417: fw=fv=fx=(*f)(x);
1418: for (iter=1;iter<=ITMAX;iter++) {
1419: xm=0.5*(a+b);
1420: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1421: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1422: printf(".");fflush(stdout);
1423: fprintf(ficlog,".");fflush(ficlog);
1424: #ifdef DEBUGBRENT
1425: 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);
1426: 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);
1427: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1428: #endif
1429: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1430: *xmin=x;
1431: return fx;
1432: }
1433: ftemp=fu;
1434: if (fabs(e) > tol1) {
1435: r=(x-w)*(fx-fv);
1436: q=(x-v)*(fx-fw);
1437: p=(x-v)*q-(x-w)*r;
1438: q=2.0*(q-r);
1439: if (q > 0.0) p = -p;
1440: q=fabs(q);
1441: etemp=e;
1442: e=d;
1443: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1444: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1445: else {
1446: d=p/q;
1447: u=x+d;
1448: if (u-a < tol2 || b-u < tol2)
1449: d=SIGN(tol1,xm-x);
1450: }
1451: } else {
1452: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1453: }
1454: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1455: fu=(*f)(u);
1456: if (fu <= fx) {
1457: if (u >= x) a=x; else b=x;
1458: SHFT(v,w,x,u)
1459: SHFT(fv,fw,fx,fu)
1460: } else {
1461: if (u < x) a=u; else b=u;
1462: if (fu <= fw || w == x) {
1463: v=w;
1464: w=u;
1465: fv=fw;
1466: fw=fu;
1467: } else if (fu <= fv || v == x || v == w) {
1468: v=u;
1469: fv=fu;
1470: }
1471: }
1472: }
1473: nrerror("Too many iterations in brent");
1474: *xmin=x;
1475: return fx;
1476: }
1477:
1478: /****************** mnbrak ***********************/
1479:
1480: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1481: double (*func)(double))
1482: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1483: the downhill direction (defined by the function as evaluated at the initial points) and returns
1484: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1485: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1486: */
1487: double ulim,u,r,q, dum;
1488: double fu;
1489:
1490: double scale=10.;
1491: int iterscale=0;
1492:
1493: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1494: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1495:
1496:
1497: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1498: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1499: /* *bx = *ax - (*ax - *bx)/scale; */
1500: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1501: /* } */
1502:
1503: if (*fb > *fa) {
1504: SHFT(dum,*ax,*bx,dum)
1505: SHFT(dum,*fb,*fa,dum)
1506: }
1507: *cx=(*bx)+GOLD*(*bx-*ax);
1508: *fc=(*func)(*cx);
1509: #ifdef DEBUG
1510: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1511: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1512: #endif
1513: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1514: r=(*bx-*ax)*(*fb-*fc);
1515: q=(*bx-*cx)*(*fb-*fa);
1516: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1517: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1518: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1519: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1520: fu=(*func)(u);
1521: #ifdef DEBUG
1522: /* f(x)=A(x-u)**2+f(u) */
1523: double A, fparabu;
1524: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1525: fparabu= *fa - A*(*ax-u)*(*ax-u);
1526: 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);
1527: 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);
1528: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1529: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1530: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1531: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1532: #endif
1533: #ifdef MNBRAKORIGINAL
1534: #else
1535: /* if (fu > *fc) { */
1536: /* #ifdef DEBUG */
1537: /* printf("mnbrak4 fu > fc \n"); */
1538: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1539: /* #endif */
1540: /* /\* 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 *\\/ *\/ */
1541: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1542: /* dum=u; /\* Shifting c and u *\/ */
1543: /* u = *cx; */
1544: /* *cx = dum; */
1545: /* dum = fu; */
1546: /* fu = *fc; */
1547: /* *fc =dum; */
1548: /* } else { /\* end *\/ */
1549: /* #ifdef DEBUG */
1550: /* printf("mnbrak3 fu < fc \n"); */
1551: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1552: /* #endif */
1553: /* dum=u; /\* Shifting c and u *\/ */
1554: /* u = *cx; */
1555: /* *cx = dum; */
1556: /* dum = fu; */
1557: /* fu = *fc; */
1558: /* *fc =dum; */
1559: /* } */
1560: #ifdef DEBUG
1561: printf("mnbrak34 fu < or >= fc \n");
1562: fprintf(ficlog, "mnbrak34 fu < fc\n");
1563: #endif
1564: dum=u; /* Shifting c and u */
1565: u = *cx;
1566: *cx = dum;
1567: dum = fu;
1568: fu = *fc;
1569: *fc =dum;
1570: #endif
1571: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1572: #ifdef DEBUG
1573: printf("mnbrak2 u after c but before ulim\n");
1574: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1575: #endif
1576: fu=(*func)(u);
1577: if (fu < *fc) {
1578: #ifdef DEBUG
1579: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1580: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1581: #endif
1582: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1583: SHFT(*fb,*fc,fu,(*func)(u))
1584: }
1585: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1586: #ifdef DEBUG
1587: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1588: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1589: #endif
1590: u=ulim;
1591: fu=(*func)(u);
1592: } else { /* u could be left to b (if r > q parabola has a maximum) */
1593: #ifdef DEBUG
1594: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1595: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1596: #endif
1597: u=(*cx)+GOLD*(*cx-*bx);
1598: fu=(*func)(u);
1599: } /* end tests */
1600: SHFT(*ax,*bx,*cx,u)
1601: SHFT(*fa,*fb,*fc,fu)
1602: #ifdef DEBUG
1603: 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);
1604: 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);
1605: #endif
1606: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1607: }
1608:
1609: /*************** linmin ************************/
1610: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1611: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1612: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1613: the value of func at the returned location p . This is actually all accomplished by calling the
1614: routines mnbrak and brent .*/
1615: int ncom;
1616: double *pcom,*xicom;
1617: double (*nrfunc)(double []);
1618:
1619: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1620: {
1621: double brent(double ax, double bx, double cx,
1622: double (*f)(double), double tol, double *xmin);
1623: double f1dim(double x);
1624: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1625: double *fc, double (*func)(double));
1626: int j;
1627: double xx,xmin,bx,ax;
1628: double fx,fb,fa;
1629:
1630: #ifdef LINMINORIGINAL
1631: #else
1632: double scale=10., axs, xxs; /* Scale added for infinity */
1633: #endif
1634:
1635: ncom=n;
1636: pcom=vector(1,n);
1637: xicom=vector(1,n);
1638: nrfunc=func;
1639: for (j=1;j<=n;j++) {
1640: pcom[j]=p[j];
1641: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1642: }
1643:
1644: #ifdef LINMINORIGINAL
1645: xx=1.;
1646: #else
1647: axs=0.0;
1648: xxs=1.;
1649: do{
1650: xx= xxs;
1651: #endif
1652: ax=0.;
1653: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1654: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1655: /* 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)) */
1656: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1657: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1658: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1659: /* 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]]*/
1660: #ifdef LINMINORIGINAL
1661: #else
1662: if (fx != fx){
1663: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1664: printf("|");
1665: fprintf(ficlog,"|");
1666: #ifdef DEBUGLINMIN
1667: 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);
1668: #endif
1669: }
1670: }while(fx != fx);
1671: #endif
1672:
1673: #ifdef DEBUGLINMIN
1674: 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);
1675: 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);
1676: #endif
1677: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1678: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1679: /* fmin = f(p[j] + xmin * xi[j]) */
1680: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1681: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1682: #ifdef DEBUG
1683: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1684: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1685: #endif
1686: #ifdef DEBUGLINMIN
1687: printf("linmin end ");
1688: fprintf(ficlog,"linmin end ");
1689: #endif
1690: for (j=1;j<=n;j++) {
1691: #ifdef LINMINORIGINAL
1692: xi[j] *= xmin;
1693: #else
1694: #ifdef DEBUGLINMIN
1695: if(xxs <1.0)
1696: printf(" before xi[%d]=%12.8f", j,xi[j]);
1697: #endif
1698: 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) */
1699: #ifdef DEBUGLINMIN
1700: if(xxs <1.0)
1701: 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 );
1702: #endif
1703: #endif
1704: p[j] += xi[j]; /* Parameters values are updated accordingly */
1705: }
1706: #ifdef DEBUGLINMIN
1707: printf("\n");
1708: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1709: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1710: for (j=1;j<=n;j++) {
1711: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1712: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1713: if(j % ncovmodel == 0){
1714: printf("\n");
1715: fprintf(ficlog,"\n");
1716: }
1717: }
1718: #else
1719: #endif
1720: free_vector(xicom,1,n);
1721: free_vector(pcom,1,n);
1722: }
1723:
1724:
1725: /*************** powell ************************/
1726: /*
1727: Minimization of a function func of n variables. Input consists of an initial starting point
1728: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1729: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1730: such that failure to decrease by more than this amount on one iteration signals doneness. On
1731: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1732: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1733: */
1734: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1735: double (*func)(double []))
1736: {
1737: void linmin(double p[], double xi[], int n, double *fret,
1738: double (*func)(double []));
1739: int i,ibig,j;
1740: double del,t,*pt,*ptt,*xit;
1741: double directest;
1742: double fp,fptt;
1743: double *xits;
1744: int niterf, itmp;
1745:
1746: pt=vector(1,n);
1747: ptt=vector(1,n);
1748: xit=vector(1,n);
1749: xits=vector(1,n);
1750: *fret=(*func)(p);
1751: for (j=1;j<=n;j++) pt[j]=p[j];
1752: rcurr_time = time(NULL);
1753: for (*iter=1;;++(*iter)) {
1754: fp=(*fret); /* From former iteration or initial value */
1755: ibig=0;
1756: del=0.0;
1757: rlast_time=rcurr_time;
1758: /* (void) gettimeofday(&curr_time,&tzp); */
1759: rcurr_time = time(NULL);
1760: curr_time = *localtime(&rcurr_time);
1761: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1762: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1763: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1764: for (i=1;i<=n;i++) {
1765: printf(" %d %.12f",i, p[i]);
1766: fprintf(ficlog," %d %.12lf",i, p[i]);
1767: fprintf(ficrespow," %.12lf", p[i]);
1768: }
1769: printf("\n");
1770: fprintf(ficlog,"\n");
1771: fprintf(ficrespow,"\n");fflush(ficrespow);
1772: if(*iter <=3){
1773: tml = *localtime(&rcurr_time);
1774: strcpy(strcurr,asctime(&tml));
1775: rforecast_time=rcurr_time;
1776: itmp = strlen(strcurr);
1777: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1778: strcurr[itmp-1]='\0';
1779: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1780: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1781: for(niterf=10;niterf<=30;niterf+=10){
1782: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1783: forecast_time = *localtime(&rforecast_time);
1784: strcpy(strfor,asctime(&forecast_time));
1785: itmp = strlen(strfor);
1786: if(strfor[itmp-1]=='\n')
1787: strfor[itmp-1]='\0';
1788: 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);
1789: 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);
1790: }
1791: }
1792: for (i=1;i<=n;i++) { /* For each direction i */
1793: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1794: fptt=(*fret);
1795: #ifdef DEBUG
1796: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1797: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1798: #endif
1799: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1800: fprintf(ficlog,"%d",i);fflush(ficlog);
1801: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1802: /* Outputs are fret(new point p) p is updated and xit rescaled */
1803: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1804: /* because that direction will be replaced unless the gain del is small */
1805: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1806: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1807: /* with the new direction. */
1808: del=fabs(fptt-(*fret));
1809: ibig=i;
1810: }
1811: #ifdef DEBUG
1812: printf("%d %.12e",i,(*fret));
1813: fprintf(ficlog,"%d %.12e",i,(*fret));
1814: for (j=1;j<=n;j++) {
1815: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1816: printf(" x(%d)=%.12e",j,xit[j]);
1817: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1818: }
1819: for(j=1;j<=n;j++) {
1820: printf(" p(%d)=%.12e",j,p[j]);
1821: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1822: }
1823: printf("\n");
1824: fprintf(ficlog,"\n");
1825: #endif
1826: } /* end loop on each direction i */
1827: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1828: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1829: /* New value of last point Pn is not computed, P(n-1) */
1830: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1831: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1832: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1833: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1834: /* decreased of more than 3.84 */
1835: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1836: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1837: /* By adding 10 parameters more the gain should be 18.31 */
1838:
1839: /* Starting the program with initial values given by a former maximization will simply change */
1840: /* the scales of the directions and the directions, because the are reset to canonical directions */
1841: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1842: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1843: #ifdef DEBUG
1844: int k[2],l;
1845: k[0]=1;
1846: k[1]=-1;
1847: printf("Max: %.12e",(*func)(p));
1848: fprintf(ficlog,"Max: %.12e",(*func)(p));
1849: for (j=1;j<=n;j++) {
1850: printf(" %.12e",p[j]);
1851: fprintf(ficlog," %.12e",p[j]);
1852: }
1853: printf("\n");
1854: fprintf(ficlog,"\n");
1855: for(l=0;l<=1;l++) {
1856: for (j=1;j<=n;j++) {
1857: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1858: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1859: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1860: }
1861: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1862: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1863: }
1864: #endif
1865:
1866:
1867: free_vector(xit,1,n);
1868: free_vector(xits,1,n);
1869: free_vector(ptt,1,n);
1870: free_vector(pt,1,n);
1871: return;
1872: } /* enough precision */
1873: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1874: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1875: ptt[j]=2.0*p[j]-pt[j];
1876: xit[j]=p[j]-pt[j];
1877: pt[j]=p[j];
1878: }
1879: fptt=(*func)(ptt); /* f_3 */
1880: #ifdef POWELLF1F3
1881: #else
1882: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1883: #endif
1884: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1885: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1886: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1887: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1888: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1889: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1890: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1891: #ifdef NRCORIGINAL
1892: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1893: #else
1894: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1895: t= t- del*SQR(fp-fptt);
1896: #endif
1897: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1898: #ifdef DEBUG
1899: 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);
1900: 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);
1901: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1902: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1903: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1904: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1905: 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);
1906: 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);
1907: #endif
1908: #ifdef POWELLORIGINAL
1909: if (t < 0.0) { /* Then we use it for new direction */
1910: #else
1911: if (directest*t < 0.0) { /* Contradiction between both tests */
1912: 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);
1913: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1914: 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);
1915: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1916: }
1917: if (directest < 0.0) { /* Then we use it for new direction */
1918: #endif
1919: #ifdef DEBUGLINMIN
1920: printf("Before linmin in direction P%d-P0\n",n);
1921: for (j=1;j<=n;j++) {
1922: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1923: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1924: if(j % ncovmodel == 0){
1925: printf("\n");
1926: fprintf(ficlog,"\n");
1927: }
1928: }
1929: #endif
1930: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1931: #ifdef DEBUGLINMIN
1932: for (j=1;j<=n;j++) {
1933: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1934: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1935: if(j % ncovmodel == 0){
1936: printf("\n");
1937: fprintf(ficlog,"\n");
1938: }
1939: }
1940: #endif
1941: for (j=1;j<=n;j++) {
1942: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1943: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1944: }
1945: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1946: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1947:
1948: #ifdef DEBUG
1949: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1950: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1951: for(j=1;j<=n;j++){
1952: printf(" %.12e",xit[j]);
1953: fprintf(ficlog," %.12e",xit[j]);
1954: }
1955: printf("\n");
1956: fprintf(ficlog,"\n");
1957: #endif
1958: } /* end of t or directest negative */
1959: #ifdef POWELLF1F3
1960: #else
1961: } /* end if (fptt < fp) */
1962: #endif
1963: } /* loop iteration */
1964: }
1965:
1966: /**** Prevalence limit (stable or period prevalence) ****************/
1967:
1968: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1969: {
1970: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1971: matrix by transitions matrix until convergence is reached with precision ftolpl */
1972: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
1973: /* Wx is row vector: population in state 1, population in state 2, population dead */
1974: /* or prevalence in state 1, prevalence in state 2, 0 */
1975: /* newm is the matrix after multiplications, its rows are identical at a factor */
1976: /* Initial matrix pimij */
1977: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
1978: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
1979: /* 0, 0 , 1} */
1980: /*
1981: * and after some iteration: */
1982: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
1983: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
1984: /* 0, 0 , 1} */
1985: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
1986: /* {0.51571254859325999, 0.4842874514067399, */
1987: /* 0.51326036147820708, 0.48673963852179264} */
1988: /* If we start from prlim again, prlim tends to a constant matrix */
1989:
1990: int i, ii,j,k;
1991: double min, max, maxmin, maxmax,sumnew=0.;
1992: /* double **matprod2(); */ /* test */
1993: double **out, cov[NCOVMAX+1], **pmij();
1994: double **newm;
1995: double agefin, delaymax=100. ; /* 100 Max number of years to converge */
1996: int ncvloop=0;
1997:
1998: for (ii=1;ii<=nlstate+ndeath;ii++)
1999: for (j=1;j<=nlstate+ndeath;j++){
2000: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2001: }
2002:
2003: cov[1]=1.;
2004:
2005: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2006: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2007: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2008: ncvloop++;
2009: newm=savm;
2010: /* Covariates have to be included here again */
2011: cov[2]=agefin;
2012: if(nagesqr==1)
2013: cov[3]= agefin*agefin;;
2014: for (k=1; k<=cptcovn;k++) {
2015: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2016: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2017: /* 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])]); */
2018: }
2019: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2020: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2021: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2022: for (k=1; k<=cptcovprod;k++) /* Useless */
2023: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2024: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2025:
2026: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2027: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2028: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2029: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2030: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2031: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2032:
2033: savm=oldm;
2034: oldm=newm;
2035: maxmax=0.;
2036: for(j=1;j<=nlstate;j++){
2037: min=1.;
2038: max=0.;
2039: for(i=1; i<=nlstate; i++) {
2040: sumnew=0;
2041: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2042: prlim[i][j]= newm[i][j]/(1-sumnew);
2043: max=FMAX(max,prlim[i][j]);
2044: min=FMIN(min,prlim[i][j]);
2045: /* printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min); */
2046: }
2047: maxmin=(max-min)/(max+min)*2;
2048: maxmax=FMAX(maxmax,maxmin);
2049: /* for(i=1; i<=nlstate; i++) { */
2050: /* sumnew=0.; */
2051: /* sumnew+=prlim[i][j]; */
2052: /* } */
2053: /* prmimj = sumnew/(float)nlstate; /\* Means of various prevalence limits. */
2054: } /* j loop */
2055: *ncvyear= (int)age- (int)agefin;
2056: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2057: if(maxmax < ftolpl){
2058: /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2059: return prlim;
2060: }
2061: } /* age loop */
2062: /* After some age loop it doesn't converge */
2063: printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g within %.0f years. \n\
2064: 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);
2065: /* printf(" age= %d newm\n",(int)age); */
2066: /* for(i=1; i<=nlstate+ndeath; i++) { */
2067: /* for(j=1;j<=nlstate+ndeath;j++){ */
2068: /* printf(" %lf", newm[i][j]); */
2069: /* } */
2070: /* printf("\n"); */
2071: /* } */
2072: /* printf("\n"); */
2073: /* printf("prlim\n"); */
2074: /* for(i=1; i<=nlstate; i++) { */
2075: /* sumnew=0; */
2076: /* for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k]; */
2077: /* for(j=1;j<=nlstate;j++){ */
2078: /* prlim[i][j]= newm[i][j]/(1-sumnew); */
2079: /* printf(" %lf", prlim[i][j]); */
2080: /* } */
2081: /* printf("\n"); */
2082: /* } */
2083: /* printf("\n"); */
2084:
2085: /* 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); */
2086: return prlim; /* should not reach here */
2087: }
2088:
2089: /*************** transition probabilities ***************/
2090:
2091: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2092: {
2093: /* According to parameters values stored in x and the covariate's values stored in cov,
2094: computes the probability to be observed in state j being in state i by appying the
2095: model to the ncovmodel covariates (including constant and age).
2096: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2097: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2098: ncth covariate in the global vector x is given by the formula:
2099: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2100: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2101: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2102: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2103: Outputs ps[i][j] the probability to be observed in j being in j according to
2104: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2105: */
2106: double s1, lnpijopii;
2107: /*double t34;*/
2108: int i,j, nc, ii, jj;
2109:
2110: for(i=1; i<= nlstate; i++){
2111: for(j=1; j<i;j++){
2112: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2113: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2114: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2115: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2116: }
2117: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2118: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2119: }
2120: for(j=i+1; j<=nlstate+ndeath;j++){
2121: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2122: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2123: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2124: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2125: }
2126: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2127: }
2128: }
2129:
2130: for(i=1; i<= nlstate; i++){
2131: s1=0;
2132: for(j=1; j<i; j++){
2133: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2134: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2135: }
2136: for(j=i+1; j<=nlstate+ndeath; j++){
2137: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2138: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2139: }
2140: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2141: ps[i][i]=1./(s1+1.);
2142: /* Computing other pijs */
2143: for(j=1; j<i; j++)
2144: ps[i][j]= exp(ps[i][j])*ps[i][i];
2145: for(j=i+1; j<=nlstate+ndeath; j++)
2146: ps[i][j]= exp(ps[i][j])*ps[i][i];
2147: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2148: } /* end i */
2149:
2150: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2151: for(jj=1; jj<= nlstate+ndeath; jj++){
2152: ps[ii][jj]=0;
2153: ps[ii][ii]=1;
2154: }
2155: }
2156:
2157:
2158: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2159: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2160: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2161: /* } */
2162: /* printf("\n "); */
2163: /* } */
2164: /* printf("\n ");printf("%lf ",cov[2]);*/
2165: /*
2166: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2167: goto end;*/
2168: return ps;
2169: }
2170:
2171: /**************** Product of 2 matrices ******************/
2172:
2173: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2174: {
2175: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2176: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2177: /* in, b, out are matrice of pointers which should have been initialized
2178: before: only the contents of out is modified. The function returns
2179: a pointer to pointers identical to out */
2180: int i, j, k;
2181: for(i=nrl; i<= nrh; i++)
2182: for(k=ncolol; k<=ncoloh; k++){
2183: out[i][k]=0.;
2184: for(j=ncl; j<=nch; j++)
2185: out[i][k] +=in[i][j]*b[j][k];
2186: }
2187: return out;
2188: }
2189:
2190:
2191: /************* Higher Matrix Product ***************/
2192:
2193: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2194: {
2195: /* Computes the transition matrix starting at age 'age' over
2196: 'nhstepm*hstepm*stepm' months (i.e. until
2197: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2198: nhstepm*hstepm matrices.
2199: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2200: (typically every 2 years instead of every month which is too big
2201: for the memory).
2202: Model is determined by parameters x and covariates have to be
2203: included manually here.
2204:
2205: */
2206:
2207: int i, j, d, h, k;
2208: double **out, cov[NCOVMAX+1];
2209: double **newm;
2210: double agexact;
2211:
2212: /* Hstepm could be zero and should return the unit matrix */
2213: for (i=1;i<=nlstate+ndeath;i++)
2214: for (j=1;j<=nlstate+ndeath;j++){
2215: oldm[i][j]=(i==j ? 1.0 : 0.0);
2216: po[i][j][0]=(i==j ? 1.0 : 0.0);
2217: }
2218: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2219: for(h=1; h <=nhstepm; h++){
2220: for(d=1; d <=hstepm; d++){
2221: newm=savm;
2222: /* Covariates have to be included here again */
2223: cov[1]=1.;
2224: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2225: cov[2]=agexact;
2226: if(nagesqr==1)
2227: cov[3]= agexact*agexact;
2228: for (k=1; k<=cptcovn;k++)
2229: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2230: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2231: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2232: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2233: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2234: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2235: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2236: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2237: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2238:
2239:
2240: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2241: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2242: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2243: pmij(pmmij,cov,ncovmodel,x,nlstate));
2244: savm=oldm;
2245: oldm=newm;
2246: }
2247: for(i=1; i<=nlstate+ndeath; i++)
2248: for(j=1;j<=nlstate+ndeath;j++) {
2249: po[i][j][h]=newm[i][j];
2250: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2251: }
2252: /*printf("h=%d ",h);*/
2253: } /* end h */
2254: /* printf("\n H=%d \n",h); */
2255: return po;
2256: }
2257:
2258: #ifdef NLOPT
2259: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2260: double fret;
2261: double *xt;
2262: int j;
2263: myfunc_data *d2 = (myfunc_data *) pd;
2264: /* xt = (p1-1); */
2265: xt=vector(1,n);
2266: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2267:
2268: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2269: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2270: printf("Function = %.12lf ",fret);
2271: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2272: printf("\n");
2273: free_vector(xt,1,n);
2274: return fret;
2275: }
2276: #endif
2277:
2278: /*************** log-likelihood *************/
2279: double func( double *x)
2280: {
2281: int i, ii, j, k, mi, d, kk;
2282: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2283: double **out;
2284: double sw; /* Sum of weights */
2285: double lli; /* Individual log likelihood */
2286: int s1, s2;
2287: double bbh, survp;
2288: long ipmx;
2289: double agexact;
2290: /*extern weight */
2291: /* We are differentiating ll according to initial status */
2292: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2293: /*for(i=1;i<imx;i++)
2294: printf(" %d\n",s[4][i]);
2295: */
2296:
2297: ++countcallfunc;
2298:
2299: cov[1]=1.;
2300:
2301: for(k=1; k<=nlstate; k++) ll[k]=0.;
2302:
2303: if(mle==1){
2304: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2305: /* Computes the values of the ncovmodel covariates of the model
2306: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2307: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2308: to be observed in j being in i according to the model.
2309: */
2310: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2311: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2312: }
2313: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2314: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2315: has been calculated etc */
2316: for(mi=1; mi<= wav[i]-1; mi++){
2317: for (ii=1;ii<=nlstate+ndeath;ii++)
2318: for (j=1;j<=nlstate+ndeath;j++){
2319: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2320: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2321: }
2322: for(d=0; d<dh[mi][i]; d++){
2323: newm=savm;
2324: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2325: cov[2]=agexact;
2326: if(nagesqr==1)
2327: cov[3]= agexact*agexact;
2328: for (kk=1; kk<=cptcovage;kk++) {
2329: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2330: }
2331: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2332: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2333: savm=oldm;
2334: oldm=newm;
2335: } /* end mult */
2336:
2337: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2338: /* But now since version 0.9 we anticipate for bias at large stepm.
2339: * If stepm is larger than one month (smallest stepm) and if the exact delay
2340: * (in months) between two waves is not a multiple of stepm, we rounded to
2341: * the nearest (and in case of equal distance, to the lowest) interval but now
2342: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2343: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2344: * probability in order to take into account the bias as a fraction of the way
2345: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2346: * -stepm/2 to stepm/2 .
2347: * For stepm=1 the results are the same as for previous versions of Imach.
2348: * For stepm > 1 the results are less biased than in previous versions.
2349: */
2350: s1=s[mw[mi][i]][i];
2351: s2=s[mw[mi+1][i]][i];
2352: bbh=(double)bh[mi][i]/(double)stepm;
2353: /* bias bh is positive if real duration
2354: * is higher than the multiple of stepm and negative otherwise.
2355: */
2356: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2357: if( s2 > nlstate){
2358: /* i.e. if s2 is a death state and if the date of death is known
2359: then the contribution to the likelihood is the probability to
2360: die between last step unit time and current step unit time,
2361: which is also equal to probability to die before dh
2362: minus probability to die before dh-stepm .
2363: In version up to 0.92 likelihood was computed
2364: as if date of death was unknown. Death was treated as any other
2365: health state: the date of the interview describes the actual state
2366: and not the date of a change in health state. The former idea was
2367: to consider that at each interview the state was recorded
2368: (healthy, disable or death) and IMaCh was corrected; but when we
2369: introduced the exact date of death then we should have modified
2370: the contribution of an exact death to the likelihood. This new
2371: contribution is smaller and very dependent of the step unit
2372: stepm. It is no more the probability to die between last interview
2373: and month of death but the probability to survive from last
2374: interview up to one month before death multiplied by the
2375: probability to die within a month. Thanks to Chris
2376: Jackson for correcting this bug. Former versions increased
2377: mortality artificially. The bad side is that we add another loop
2378: which slows down the processing. The difference can be up to 10%
2379: lower mortality.
2380: */
2381: /* If, at the beginning of the maximization mostly, the
2382: cumulative probability or probability to be dead is
2383: constant (ie = 1) over time d, the difference is equal to
2384: 0. out[s1][3] = savm[s1][3]: probability, being at state
2385: s1 at precedent wave, to be dead a month before current
2386: wave is equal to probability, being at state s1 at
2387: precedent wave, to be dead at mont of the current
2388: wave. Then the observed probability (that this person died)
2389: is null according to current estimated parameter. In fact,
2390: it should be very low but not zero otherwise the log go to
2391: infinity.
2392: */
2393: /* #ifdef INFINITYORIGINAL */
2394: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2395: /* #else */
2396: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2397: /* lli=log(mytinydouble); */
2398: /* else */
2399: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2400: /* #endif */
2401: lli=log(out[s1][s2] - savm[s1][s2]);
2402:
2403: } else if (s2==-2) {
2404: for (j=1,survp=0. ; j<=nlstate; j++)
2405: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2406: /*survp += out[s1][j]; */
2407: lli= log(survp);
2408: }
2409:
2410: else if (s2==-4) {
2411: for (j=3,survp=0. ; j<=nlstate; j++)
2412: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2413: lli= log(survp);
2414: }
2415:
2416: else if (s2==-5) {
2417: for (j=1,survp=0. ; j<=2; j++)
2418: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2419: lli= log(survp);
2420: }
2421:
2422: else{
2423: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2424: /* 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 */
2425: }
2426: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2427: /*if(lli ==000.0)*/
2428: /*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); */
2429: ipmx +=1;
2430: sw += weight[i];
2431: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2432: /* if (lli < log(mytinydouble)){ */
2433: /* 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); */
2434: /* 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]); */
2435: /* } */
2436: } /* end of wave */
2437: } /* end of individual */
2438: } else if(mle==2){
2439: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2440: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2441: for(mi=1; mi<= wav[i]-1; mi++){
2442: for (ii=1;ii<=nlstate+ndeath;ii++)
2443: for (j=1;j<=nlstate+ndeath;j++){
2444: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2445: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2446: }
2447: for(d=0; d<=dh[mi][i]; d++){
2448: newm=savm;
2449: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2450: cov[2]=agexact;
2451: if(nagesqr==1)
2452: cov[3]= agexact*agexact;
2453: for (kk=1; kk<=cptcovage;kk++) {
2454: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2455: }
2456: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2457: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2458: savm=oldm;
2459: oldm=newm;
2460: } /* end mult */
2461:
2462: s1=s[mw[mi][i]][i];
2463: s2=s[mw[mi+1][i]][i];
2464: bbh=(double)bh[mi][i]/(double)stepm;
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: ipmx +=1;
2467: sw += weight[i];
2468: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2469: } /* end of wave */
2470: } /* end of individual */
2471: } else if(mle==3){ /* exponential inter-extrapolation */
2472: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2473: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2474: for(mi=1; mi<= wav[i]-1; mi++){
2475: for (ii=1;ii<=nlstate+ndeath;ii++)
2476: for (j=1;j<=nlstate+ndeath;j++){
2477: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2478: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2479: }
2480: for(d=0; d<dh[mi][i]; d++){
2481: newm=savm;
2482: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2483: cov[2]=agexact;
2484: if(nagesqr==1)
2485: cov[3]= agexact*agexact;
2486: for (kk=1; kk<=cptcovage;kk++) {
2487: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2488: }
2489: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2490: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2491: savm=oldm;
2492: oldm=newm;
2493: } /* end mult */
2494:
2495: s1=s[mw[mi][i]][i];
2496: s2=s[mw[mi+1][i]][i];
2497: bbh=(double)bh[mi][i]/(double)stepm;
2498: 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 */
2499: ipmx +=1;
2500: sw += weight[i];
2501: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2502: } /* end of wave */
2503: } /* end of individual */
2504: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2505: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2506: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2507: for(mi=1; mi<= wav[i]-1; mi++){
2508: for (ii=1;ii<=nlstate+ndeath;ii++)
2509: for (j=1;j<=nlstate+ndeath;j++){
2510: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2511: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2512: }
2513: for(d=0; d<dh[mi][i]; d++){
2514: newm=savm;
2515: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2516: cov[2]=agexact;
2517: if(nagesqr==1)
2518: cov[3]= agexact*agexact;
2519: for (kk=1; kk<=cptcovage;kk++) {
2520: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2521: }
2522:
2523: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2524: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2525: savm=oldm;
2526: oldm=newm;
2527: } /* end mult */
2528:
2529: s1=s[mw[mi][i]][i];
2530: s2=s[mw[mi+1][i]][i];
2531: if( s2 > nlstate){
2532: lli=log(out[s1][s2] - savm[s1][s2]);
2533: }else{
2534: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2535: }
2536: ipmx +=1;
2537: sw += weight[i];
2538: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2539: /* 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]); */
2540: } /* end of wave */
2541: } /* end of individual */
2542: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2543: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2544: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2545: for(mi=1; mi<= wav[i]-1; mi++){
2546: for (ii=1;ii<=nlstate+ndeath;ii++)
2547: for (j=1;j<=nlstate+ndeath;j++){
2548: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2549: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2550: }
2551: for(d=0; d<dh[mi][i]; d++){
2552: newm=savm;
2553: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2554: cov[2]=agexact;
2555: if(nagesqr==1)
2556: cov[3]= agexact*agexact;
2557: for (kk=1; kk<=cptcovage;kk++) {
2558: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2559: }
2560:
2561: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2562: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2563: savm=oldm;
2564: oldm=newm;
2565: } /* end mult */
2566:
2567: s1=s[mw[mi][i]][i];
2568: s2=s[mw[mi+1][i]][i];
2569: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2570: ipmx +=1;
2571: sw += weight[i];
2572: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2573: /*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]);*/
2574: } /* end of wave */
2575: } /* end of individual */
2576: } /* End of if */
2577: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2578: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2579: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2580: return -l;
2581: }
2582:
2583: /*************** log-likelihood *************/
2584: double funcone( double *x)
2585: {
2586: /* Same as likeli but slower because of a lot of printf and if */
2587: int i, ii, j, k, mi, d, kk;
2588: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2589: double **out;
2590: double lli; /* Individual log likelihood */
2591: double llt;
2592: int s1, s2;
2593: double bbh, survp;
2594: double agexact;
2595: /*extern weight */
2596: /* We are differentiating ll according to initial status */
2597: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2598: /*for(i=1;i<imx;i++)
2599: printf(" %d\n",s[4][i]);
2600: */
2601: cov[1]=1.;
2602:
2603: for(k=1; k<=nlstate; k++) ll[k]=0.;
2604:
2605: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2606: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2607: for(mi=1; mi<= wav[i]-1; mi++){
2608: for (ii=1;ii<=nlstate+ndeath;ii++)
2609: for (j=1;j<=nlstate+ndeath;j++){
2610: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2611: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2612: }
2613: for(d=0; d<dh[mi][i]; d++){
2614: newm=savm;
2615: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2616: cov[2]=agexact;
2617: if(nagesqr==1)
2618: cov[3]= agexact*agexact;
2619: for (kk=1; kk<=cptcovage;kk++) {
2620: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2621: }
2622:
2623: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2624: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2625: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2626: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2627: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2628: savm=oldm;
2629: oldm=newm;
2630: } /* end mult */
2631:
2632: s1=s[mw[mi][i]][i];
2633: s2=s[mw[mi+1][i]][i];
2634: bbh=(double)bh[mi][i]/(double)stepm;
2635: /* bias is positive if real duration
2636: * is higher than the multiple of stepm and negative otherwise.
2637: */
2638: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2639: lli=log(out[s1][s2] - savm[s1][s2]);
2640: } else if (s2==-2) {
2641: for (j=1,survp=0. ; j<=nlstate; j++)
2642: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2643: lli= log(survp);
2644: }else if (mle==1){
2645: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2646: } else if(mle==2){
2647: 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 */
2648: } else if(mle==3){ /* exponential inter-extrapolation */
2649: 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 */
2650: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2651: lli=log(out[s1][s2]); /* Original formula */
2652: } else{ /* mle=0 back to 1 */
2653: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2654: /*lli=log(out[s1][s2]); */ /* Original formula */
2655: } /* End of if */
2656: ipmx +=1;
2657: sw += weight[i];
2658: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2659: /*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]); */
2660: if(globpr){
2661: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2662: %11.6f %11.6f %11.6f ", \
2663: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2664: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2665: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2666: llt +=ll[k]*gipmx/gsw;
2667: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2668: }
2669: fprintf(ficresilk," %10.6f\n", -llt);
2670: }
2671: } /* end of wave */
2672: } /* end of individual */
2673: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2674: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2675: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2676: if(globpr==0){ /* First time we count the contributions and weights */
2677: gipmx=ipmx;
2678: gsw=sw;
2679: }
2680: return -l;
2681: }
2682:
2683:
2684: /*************** function likelione ***********/
2685: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2686: {
2687: /* This routine should help understanding what is done with
2688: the selection of individuals/waves and
2689: to check the exact contribution to the likelihood.
2690: Plotting could be done.
2691: */
2692: int k;
2693:
2694: if(*globpri !=0){ /* Just counts and sums, no printings */
2695: strcpy(fileresilk,"ILK_");
2696: strcat(fileresilk,fileresu);
2697: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2698: printf("Problem with resultfile: %s\n", fileresilk);
2699: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2700: }
2701: 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");
2702: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
2703: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2704: for(k=1; k<=nlstate; k++)
2705: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2706: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2707: }
2708:
2709: *fretone=(*funcone)(p);
2710: if(*globpri !=0){
2711: fclose(ficresilk);
2712: if (mle ==0)
2713: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2714: else if(mle >=1)
2715: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2716: 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));
2717:
2718:
2719: for (k=1; k<= nlstate ; k++) {
2720: fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
2721: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2722: }
2723: 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> \
2724: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2725: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2726: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2727: fflush(fichtm);
2728: }
2729: return;
2730: }
2731:
2732:
2733: /*********** Maximum Likelihood Estimation ***************/
2734:
2735: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2736: {
2737: int i,j, iter=0;
2738: double **xi;
2739: double fret;
2740: double fretone; /* Only one call to likelihood */
2741: /* char filerespow[FILENAMELENGTH];*/
2742:
2743: #ifdef NLOPT
2744: int creturn;
2745: nlopt_opt opt;
2746: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2747: double *lb;
2748: double minf; /* the minimum objective value, upon return */
2749: double * p1; /* Shifted parameters from 0 instead of 1 */
2750: myfunc_data dinst, *d = &dinst;
2751: #endif
2752:
2753:
2754: xi=matrix(1,npar,1,npar);
2755: for (i=1;i<=npar;i++)
2756: for (j=1;j<=npar;j++)
2757: xi[i][j]=(i==j ? 1.0 : 0.0);
2758: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2759: strcpy(filerespow,"POW_");
2760: strcat(filerespow,fileres);
2761: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2762: printf("Problem with resultfile: %s\n", filerespow);
2763: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2764: }
2765: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2766: for (i=1;i<=nlstate;i++)
2767: for(j=1;j<=nlstate+ndeath;j++)
2768: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2769: fprintf(ficrespow,"\n");
2770: #ifdef POWELL
2771: powell(p,xi,npar,ftol,&iter,&fret,func);
2772: #endif
2773:
2774: #ifdef NLOPT
2775: #ifdef NEWUOA
2776: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2777: #else
2778: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2779: #endif
2780: lb=vector(0,npar-1);
2781: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2782: nlopt_set_lower_bounds(opt, lb);
2783: nlopt_set_initial_step1(opt, 0.1);
2784:
2785: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2786: d->function = func;
2787: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2788: nlopt_set_min_objective(opt, myfunc, d);
2789: nlopt_set_xtol_rel(opt, ftol);
2790: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2791: printf("nlopt failed! %d\n",creturn);
2792: }
2793: else {
2794: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2795: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2796: iter=1; /* not equal */
2797: }
2798: nlopt_destroy(opt);
2799: #endif
2800: free_matrix(xi,1,npar,1,npar);
2801: fclose(ficrespow);
2802: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2803: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2804: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2805:
2806: }
2807:
2808: /**** Computes Hessian and covariance matrix ***/
2809: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2810: {
2811: double **a,**y,*x,pd;
2812: /* double **hess; */
2813: int i, j;
2814: int *indx;
2815:
2816: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2817: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2818: void lubksb(double **a, int npar, int *indx, double b[]) ;
2819: void ludcmp(double **a, int npar, int *indx, double *d) ;
2820: double gompertz(double p[]);
2821: /* hess=matrix(1,npar,1,npar); */
2822:
2823: printf("\nCalculation of the hessian matrix. Wait...\n");
2824: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2825: for (i=1;i<=npar;i++){
2826: printf("%d-",i);fflush(stdout);
2827: fprintf(ficlog,"%d-",i);fflush(ficlog);
2828:
2829: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2830:
2831: /* printf(" %f ",p[i]);
2832: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2833: }
2834:
2835: for (i=1;i<=npar;i++) {
2836: for (j=1;j<=npar;j++) {
2837: if (j>i) {
2838: printf(".%d-%d",i,j);fflush(stdout);
2839: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2840: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2841:
2842: hess[j][i]=hess[i][j];
2843: /*printf(" %lf ",hess[i][j]);*/
2844: }
2845: }
2846: }
2847: printf("\n");
2848: fprintf(ficlog,"\n");
2849:
2850: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2851: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2852:
2853: a=matrix(1,npar,1,npar);
2854: y=matrix(1,npar,1,npar);
2855: x=vector(1,npar);
2856: indx=ivector(1,npar);
2857: for (i=1;i<=npar;i++)
2858: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2859: ludcmp(a,npar,indx,&pd);
2860:
2861: for (j=1;j<=npar;j++) {
2862: for (i=1;i<=npar;i++) x[i]=0;
2863: x[j]=1;
2864: lubksb(a,npar,indx,x);
2865: for (i=1;i<=npar;i++){
2866: matcov[i][j]=x[i];
2867: }
2868: }
2869:
2870: printf("\n#Hessian matrix#\n");
2871: fprintf(ficlog,"\n#Hessian matrix#\n");
2872: for (i=1;i<=npar;i++) {
2873: for (j=1;j<=npar;j++) {
2874: printf("%.6e ",hess[i][j]);
2875: fprintf(ficlog,"%.6e ",hess[i][j]);
2876: }
2877: printf("\n");
2878: fprintf(ficlog,"\n");
2879: }
2880:
2881: /* printf("\n#Covariance matrix#\n"); */
2882: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2883: /* for (i=1;i<=npar;i++) { */
2884: /* for (j=1;j<=npar;j++) { */
2885: /* printf("%.6e ",matcov[i][j]); */
2886: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2887: /* } */
2888: /* printf("\n"); */
2889: /* fprintf(ficlog,"\n"); */
2890: /* } */
2891:
2892: /* Recompute Inverse */
2893: /* for (i=1;i<=npar;i++) */
2894: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2895: /* ludcmp(a,npar,indx,&pd); */
2896:
2897: /* printf("\n#Hessian matrix recomputed#\n"); */
2898:
2899: /* for (j=1;j<=npar;j++) { */
2900: /* for (i=1;i<=npar;i++) x[i]=0; */
2901: /* x[j]=1; */
2902: /* lubksb(a,npar,indx,x); */
2903: /* for (i=1;i<=npar;i++){ */
2904: /* y[i][j]=x[i]; */
2905: /* printf("%.3e ",y[i][j]); */
2906: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2907: /* } */
2908: /* printf("\n"); */
2909: /* fprintf(ficlog,"\n"); */
2910: /* } */
2911:
2912: /* Verifying the inverse matrix */
2913: #ifdef DEBUGHESS
2914: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2915:
2916: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2917: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2918:
2919: for (j=1;j<=npar;j++) {
2920: for (i=1;i<=npar;i++){
2921: printf("%.2f ",y[i][j]);
2922: fprintf(ficlog,"%.2f ",y[i][j]);
2923: }
2924: printf("\n");
2925: fprintf(ficlog,"\n");
2926: }
2927: #endif
2928:
2929: free_matrix(a,1,npar,1,npar);
2930: free_matrix(y,1,npar,1,npar);
2931: free_vector(x,1,npar);
2932: free_ivector(indx,1,npar);
2933: /* free_matrix(hess,1,npar,1,npar); */
2934:
2935:
2936: }
2937:
2938: /*************** hessian matrix ****************/
2939: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2940: { /* Around values of x, computes the function func and returns the scales delti and hessian */
2941: int i;
2942: int l=1, lmax=20;
2943: double k1,k2, res, fx;
2944: double p2[MAXPARM+1]; /* identical to x */
2945: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2946: int k=0,kmax=10;
2947: double l1;
2948:
2949: fx=func(x);
2950: for (i=1;i<=npar;i++) p2[i]=x[i];
2951: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2952: l1=pow(10,l);
2953: delts=delt;
2954: for(k=1 ; k <kmax; k=k+1){
2955: delt = delta*(l1*k);
2956: p2[theta]=x[theta] +delt;
2957: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2958: p2[theta]=x[theta]-delt;
2959: k2=func(p2)-fx;
2960: /*res= (k1-2.0*fx+k2)/delt/delt; */
2961: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
2962:
2963: #ifdef DEBUGHESSII
2964: 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);
2965: 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);
2966: #endif
2967: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2968: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2969: k=kmax;
2970: }
2971: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2972: k=kmax; l=lmax*10;
2973: }
2974: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2975: delts=delt;
2976: }
2977: } /* End loop k */
2978: }
2979: delti[theta]=delts;
2980: return res;
2981:
2982: }
2983:
2984: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2985: {
2986: int i;
2987: int l=1, lmax=20;
2988: double k1,k2,k3,k4,res,fx;
2989: double p2[MAXPARM+1];
2990: int k, kmax=1;
2991: double v1, v2, cv12, lc1, lc2;
2992:
2993: int firstime=0;
2994:
2995: fx=func(x);
2996: for (k=1; k<=kmax; k=k+10) {
2997: for (i=1;i<=npar;i++) p2[i]=x[i];
2998: p2[thetai]=x[thetai]+delti[thetai]*k;
2999: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3000: k1=func(p2)-fx;
3001:
3002: p2[thetai]=x[thetai]+delti[thetai]*k;
3003: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3004: k2=func(p2)-fx;
3005:
3006: p2[thetai]=x[thetai]-delti[thetai]*k;
3007: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3008: k3=func(p2)-fx;
3009:
3010: p2[thetai]=x[thetai]-delti[thetai]*k;
3011: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3012: k4=func(p2)-fx;
3013: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3014: if(k1*k2*k3*k4 <0.){
3015: firstime=1;
3016: kmax=kmax+10;
3017: }
3018: if(kmax >=10 || firstime ==1){
3019: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3020: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3021: 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);
3022: 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);
3023: }
3024: #ifdef DEBUGHESSIJ
3025: v1=hess[thetai][thetai];
3026: v2=hess[thetaj][thetaj];
3027: cv12=res;
3028: /* Computing eigen value of Hessian matrix */
3029: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3030: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3031: if ((lc2 <0) || (lc1 <0) ){
3032: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3033: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3034: 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);
3035: 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);
3036: }
3037: #endif
3038: }
3039: return res;
3040: }
3041:
3042: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3043: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3044: /* { */
3045: /* int i; */
3046: /* int l=1, lmax=20; */
3047: /* double k1,k2,k3,k4,res,fx; */
3048: /* double p2[MAXPARM+1]; */
3049: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3050: /* int k=0,kmax=10; */
3051: /* double l1; */
3052:
3053: /* fx=func(x); */
3054: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3055: /* l1=pow(10,l); */
3056: /* delts=delt; */
3057: /* for(k=1 ; k <kmax; k=k+1){ */
3058: /* delt = delti*(l1*k); */
3059: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3060: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3061: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3062: /* k1=func(p2)-fx; */
3063:
3064: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3065: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3066: /* k2=func(p2)-fx; */
3067:
3068: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3069: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3070: /* k3=func(p2)-fx; */
3071:
3072: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3073: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3074: /* k4=func(p2)-fx; */
3075: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3076: /* #ifdef DEBUGHESSIJ */
3077: /* 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); */
3078: /* 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); */
3079: /* #endif */
3080: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3081: /* k=kmax; */
3082: /* } */
3083: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3084: /* k=kmax; l=lmax*10; */
3085: /* } */
3086: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3087: /* delts=delt; */
3088: /* } */
3089: /* } /\* End loop k *\/ */
3090: /* } */
3091: /* delti[theta]=delts; */
3092: /* return res; */
3093: /* } */
3094:
3095:
3096: /************** Inverse of matrix **************/
3097: void ludcmp(double **a, int n, int *indx, double *d)
3098: {
3099: int i,imax,j,k;
3100: double big,dum,sum,temp;
3101: double *vv;
3102:
3103: vv=vector(1,n);
3104: *d=1.0;
3105: for (i=1;i<=n;i++) {
3106: big=0.0;
3107: for (j=1;j<=n;j++)
3108: if ((temp=fabs(a[i][j])) > big) big=temp;
3109: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3110: vv[i]=1.0/big;
3111: }
3112: for (j=1;j<=n;j++) {
3113: for (i=1;i<j;i++) {
3114: sum=a[i][j];
3115: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3116: a[i][j]=sum;
3117: }
3118: big=0.0;
3119: for (i=j;i<=n;i++) {
3120: sum=a[i][j];
3121: for (k=1;k<j;k++)
3122: sum -= a[i][k]*a[k][j];
3123: a[i][j]=sum;
3124: if ( (dum=vv[i]*fabs(sum)) >= big) {
3125: big=dum;
3126: imax=i;
3127: }
3128: }
3129: if (j != imax) {
3130: for (k=1;k<=n;k++) {
3131: dum=a[imax][k];
3132: a[imax][k]=a[j][k];
3133: a[j][k]=dum;
3134: }
3135: *d = -(*d);
3136: vv[imax]=vv[j];
3137: }
3138: indx[j]=imax;
3139: if (a[j][j] == 0.0) a[j][j]=TINY;
3140: if (j != n) {
3141: dum=1.0/(a[j][j]);
3142: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3143: }
3144: }
3145: free_vector(vv,1,n); /* Doesn't work */
3146: ;
3147: }
3148:
3149: void lubksb(double **a, int n, int *indx, double b[])
3150: {
3151: int i,ii=0,ip,j;
3152: double sum;
3153:
3154: for (i=1;i<=n;i++) {
3155: ip=indx[i];
3156: sum=b[ip];
3157: b[ip]=b[i];
3158: if (ii)
3159: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3160: else if (sum) ii=i;
3161: b[i]=sum;
3162: }
3163: for (i=n;i>=1;i--) {
3164: sum=b[i];
3165: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3166: b[i]=sum/a[i][i];
3167: }
3168: }
3169:
3170: void pstamp(FILE *fichier)
3171: {
3172: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3173: }
3174:
3175: /************ Frequencies ********************/
3176: 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[])
3177: { /* Some frequencies */
3178:
3179: int i, m, jk, j1, bool, z1,j;
3180: int first;
3181: double ***freq; /* Frequencies */
3182: double *pp, **prop;
3183: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3184: char fileresp[FILENAMELENGTH];
3185:
3186: pp=vector(1,nlstate);
3187: prop=matrix(1,nlstate,iagemin,iagemax+3);
3188: strcpy(fileresp,"P_");
3189: strcat(fileresp,fileresu);
3190: if((ficresp=fopen(fileresp,"w"))==NULL) {
3191: printf("Problem with prevalence resultfile: %s\n", fileresp);
3192: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3193: exit(0);
3194: }
3195: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3196: j1=0;
3197:
3198: j=cptcoveff;
3199: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3200:
3201: first=1;
3202:
3203: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3204: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3205: /* j1++; */
3206: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
3207: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3208: scanf("%d", i);*/
3209: for (i=-5; i<=nlstate+ndeath; i++)
3210: for (jk=-5; jk<=nlstate+ndeath; jk++)
3211: for(m=iagemin; m <= iagemax+3; m++)
3212: freq[i][jk][m]=0;
3213:
3214: for (i=1; i<=nlstate; i++)
3215: for(m=iagemin; m <= iagemax+3; m++)
3216: prop[i][m]=0;
3217:
3218: dateintsum=0;
3219: k2cpt=0;
3220: for (i=1; i<=imx; i++) {
3221: bool=1;
3222: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3223: for (z1=1; z1<=cptcoveff; z1++)
3224: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3225: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3226: bool=0;
3227: /* 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",
3228: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3229: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3230: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3231: }
3232: }
3233:
3234: if (bool==1){
3235: for(m=firstpass; m<=lastpass; m++){
3236: k2=anint[m][i]+(mint[m][i]/12.);
3237: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3238: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3239: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3240: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
3241: if (m<lastpass) {
3242: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3243: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3244: }
3245:
3246: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
3247: dateintsum=dateintsum+k2;
3248: k2cpt++;
3249: }
3250: /*}*/
3251: }
3252: }
3253: } /* end i */
3254:
3255: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3256: pstamp(ficresp);
3257: if (cptcovn>0) {
3258: fprintf(ficresp, "\n#********** Variable ");
3259: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3260: fprintf(ficresp, "**********\n#");
3261: fprintf(ficlog, "\n#********** Variable ");
3262: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3263: fprintf(ficlog, "**********\n#");
3264: }
3265: for(i=1; i<=nlstate;i++)
3266: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3267: fprintf(ficresp, "\n");
3268:
3269: for(i=iagemin; i <= iagemax+3; i++){
3270: if(i==iagemax+3){
3271: fprintf(ficlog,"Total");
3272: }else{
3273: if(first==1){
3274: first=0;
3275: printf("See log file for details...\n");
3276: }
3277: fprintf(ficlog,"Age %d", i);
3278: }
3279: for(jk=1; jk <=nlstate ; jk++){
3280: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3281: pp[jk] += freq[jk][m][i];
3282: }
3283: for(jk=1; jk <=nlstate ; jk++){
3284: for(m=-1, pos=0; m <=0 ; m++)
3285: pos += freq[jk][m][i];
3286: if(pp[jk]>=1.e-10){
3287: if(first==1){
3288: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3289: }
3290: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3291: }else{
3292: if(first==1)
3293: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3294: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3295: }
3296: }
3297:
3298: for(jk=1; jk <=nlstate ; jk++){
3299: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3300: pp[jk] += freq[jk][m][i];
3301: }
3302: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3303: pos += pp[jk];
3304: posprop += prop[jk][i];
3305: }
3306: for(jk=1; jk <=nlstate ; jk++){
3307: if(pos>=1.e-5){
3308: if(first==1)
3309: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3310: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3311: }else{
3312: if(first==1)
3313: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3314: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3315: }
3316: if( i <= iagemax){
3317: if(pos>=1.e-5){
3318: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3319: /*probs[i][jk][j1]= pp[jk]/pos;*/
3320: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3321: }
3322: else
3323: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3324: }
3325: }
3326:
3327: for(jk=-1; jk <=nlstate+ndeath; jk++)
3328: for(m=-1; m <=nlstate+ndeath; m++)
3329: if(freq[jk][m][i] !=0 ) {
3330: if(first==1)
3331: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3332: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3333: }
3334: if(i <= iagemax)
3335: fprintf(ficresp,"\n");
3336: if(first==1)
3337: printf("Others in log...\n");
3338: fprintf(ficlog,"\n");
3339: }
3340: /*}*/
3341: }
3342: dateintmean=dateintsum/k2cpt;
3343:
3344: fclose(ficresp);
3345: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3346: free_vector(pp,1,nlstate);
3347: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3348: /* End of Freq */
3349: }
3350:
3351: /************ Prevalence ********************/
3352: 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)
3353: {
3354: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3355: in each health status at the date of interview (if between dateprev1 and dateprev2).
3356: We still use firstpass and lastpass as another selection.
3357: */
3358:
3359: int i, m, jk, j1, bool, z1,j;
3360:
3361: double **prop;
3362: double posprop;
3363: double y2; /* in fractional years */
3364: int iagemin, iagemax;
3365: int first; /** to stop verbosity which is redirected to log file */
3366:
3367: iagemin= (int) agemin;
3368: iagemax= (int) agemax;
3369: /*pp=vector(1,nlstate);*/
3370: prop=matrix(1,nlstate,iagemin,iagemax+3);
3371: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3372: j1=0;
3373:
3374: /*j=cptcoveff;*/
3375: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3376:
3377: first=1;
3378: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3379: /*for(i1=1; i1<=ncodemax[k1];i1++){
3380: j1++;*/
3381:
3382: for (i=1; i<=nlstate; i++)
3383: for(m=iagemin; m <= iagemax+3; m++)
3384: prop[i][m]=0.0;
3385:
3386: for (i=1; i<=imx; i++) { /* Each individual */
3387: bool=1;
3388: if (cptcovn>0) {
3389: for (z1=1; z1<=cptcoveff; z1++)
3390: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3391: bool=0;
3392: }
3393: if (bool==1) {
3394: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3395: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3396: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3397: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3398: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3399: 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);
3400: if (s[m][i]>0 && s[m][i]<=nlstate) {
3401: /*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]]);*/
3402: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3403: prop[s[m][i]][iagemax+3] += weight[i];
3404: }
3405: }
3406: } /* end selection of waves */
3407: }
3408: }
3409: for(i=iagemin; i <= iagemax+3; i++){
3410: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3411: posprop += prop[jk][i];
3412: }
3413:
3414: for(jk=1; jk <=nlstate ; jk++){
3415: if( i <= iagemax){
3416: if(posprop>=1.e-5){
3417: probs[i][jk][j1]= prop[jk][i]/posprop;
3418: } else{
3419: if(first==1){
3420: first=0;
3421: 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]);
3422: }
3423: }
3424: }
3425: }/* end jk */
3426: }/* end i */
3427: /*} *//* end i1 */
3428: } /* end j1 */
3429:
3430: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3431: /*free_vector(pp,1,nlstate);*/
3432: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3433: } /* End of prevalence */
3434:
3435: /************* Waves Concatenation ***************/
3436:
3437: 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)
3438: {
3439: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3440: Death is a valid wave (if date is known).
3441: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3442: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3443: and mw[mi+1][i]. dh depends on stepm.
3444: */
3445:
3446: int i, mi, m;
3447: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3448: double sum=0., jmean=0.;*/
3449: int first;
3450: int j, k=0,jk, ju, jl;
3451: double sum=0.;
3452: first=0;
3453: jmin=100000;
3454: jmax=-1;
3455: jmean=0.;
3456: for(i=1; i<=imx; i++){
3457: mi=0;
3458: m=firstpass;
3459: while(s[m][i] <= nlstate){
3460: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3461: mw[++mi][i]=m;
3462: if(m >=lastpass)
3463: break;
3464: else
3465: m++;
3466: }/* end while */
3467: if (s[m][i] > nlstate){
3468: mi++; /* Death is another wave */
3469: /* if(mi==0) never been interviewed correctly before death */
3470: /* Only death is a correct wave */
3471: mw[mi][i]=m;
3472: }
3473:
3474: wav[i]=mi;
3475: if(mi==0){
3476: nbwarn++;
3477: if(first==0){
3478: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3479: first=1;
3480: }
3481: if(first==1){
3482: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3483: }
3484: } /* end mi==0 */
3485: } /* End individuals */
3486:
3487: for(i=1; i<=imx; i++){
3488: for(mi=1; mi<wav[i];mi++){
3489: if (stepm <=0)
3490: dh[mi][i]=1;
3491: else{
3492: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3493: if (agedc[i] < 2*AGESUP) {
3494: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3495: if(j==0) j=1; /* Survives at least one month after exam */
3496: else if(j<0){
3497: nberr++;
3498: 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]);
3499: j=1; /* Temporary Dangerous patch */
3500: 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);
3501: 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]);
3502: 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);
3503: }
3504: k=k+1;
3505: if (j >= jmax){
3506: jmax=j;
3507: ijmax=i;
3508: }
3509: if (j <= jmin){
3510: jmin=j;
3511: ijmin=i;
3512: }
3513: sum=sum+j;
3514: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3515: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3516: }
3517: }
3518: else{
3519: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3520: /* 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]); */
3521:
3522: k=k+1;
3523: if (j >= jmax) {
3524: jmax=j;
3525: ijmax=i;
3526: }
3527: else if (j <= jmin){
3528: jmin=j;
3529: ijmin=i;
3530: }
3531: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3532: /*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]);*/
3533: if(j<0){
3534: nberr++;
3535: 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]);
3536: 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]);
3537: }
3538: sum=sum+j;
3539: }
3540: jk= j/stepm;
3541: jl= j -jk*stepm;
3542: ju= j -(jk+1)*stepm;
3543: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3544: if(jl==0){
3545: dh[mi][i]=jk;
3546: bh[mi][i]=0;
3547: }else{ /* We want a negative bias in order to only have interpolation ie
3548: * to avoid the price of an extra matrix product in likelihood */
3549: dh[mi][i]=jk+1;
3550: bh[mi][i]=ju;
3551: }
3552: }else{
3553: if(jl <= -ju){
3554: dh[mi][i]=jk;
3555: bh[mi][i]=jl; /* bias is positive if real duration
3556: * is higher than the multiple of stepm and negative otherwise.
3557: */
3558: }
3559: else{
3560: dh[mi][i]=jk+1;
3561: bh[mi][i]=ju;
3562: }
3563: if(dh[mi][i]==0){
3564: dh[mi][i]=1; /* At least one step */
3565: bh[mi][i]=ju; /* At least one step */
3566: /* 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);*/
3567: }
3568: } /* end if mle */
3569: }
3570: } /* end wave */
3571: }
3572: jmean=sum/k;
3573: 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);
3574: 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);
3575: }
3576:
3577: /*********** Tricode ****************************/
3578: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3579: {
3580: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3581: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3582: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3583: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3584: * nbcode[Tvar[j]][1]=
3585: */
3586:
3587: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3588: int modmaxcovj=0; /* Modality max of covariates j */
3589: int cptcode=0; /* Modality max of covariates j */
3590: int modmincovj=0; /* Modality min of covariates j */
3591:
3592:
3593: cptcoveff=0;
3594:
3595: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3596:
3597: /* Loop on covariates without age and products */
3598: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3599: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3600: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3601: modality of this covariate Vj*/
3602: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3603: * If product of Vn*Vm, still boolean *:
3604: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3605: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3606: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3607: modality of the nth covariate of individual i. */
3608: if (ij > modmaxcovj)
3609: modmaxcovj=ij;
3610: else if (ij < modmincovj)
3611: modmincovj=ij;
3612: if ((ij < -1) && (ij > NCOVMAX)){
3613: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3614: exit(1);
3615: }else
3616: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3617: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3618: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3619: /* getting the maximum value of the modality of the covariate
3620: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3621: female is 1, then modmaxcovj=1.*/
3622: } /* end for loop on individuals i */
3623: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3624: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3625: cptcode=modmaxcovj;
3626: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3627: /*for (i=0; i<=cptcode; i++) {*/
3628: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3629: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3630: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3631: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3632: if( k != -1){
3633: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3634: covariate for which somebody answered excluding
3635: undefined. Usually 2: 0 and 1. */
3636: }
3637: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3638: covariate for which somebody answered including
3639: undefined. Usually 3: -1, 0 and 1. */
3640: }
3641: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3642: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3643: } /* Ndum[-1] number of undefined modalities */
3644:
3645: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3646: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3647: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3648: modmincovj=3; modmaxcovj = 7;
3649: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3650: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3651: defining two dummy variables: variables V1_1 and V1_2.
3652: nbcode[Tvar[j]][ij]=k;
3653: nbcode[Tvar[j]][1]=0;
3654: nbcode[Tvar[j]][2]=1;
3655: nbcode[Tvar[j]][3]=2;
3656: To be continued (not working yet).
3657: */
3658: ij=0; /* ij is similar to i but can jump over null modalities */
3659: 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*/
3660: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3661: break;
3662: }
3663: ij++;
3664: 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.*/
3665: cptcode = ij; /* New max modality for covar j */
3666: } /* end of loop on modality i=-1 to 1 or more */
3667:
3668: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3669: /* /\*recode from 0 *\/ */
3670: /* k is a modality. If we have model=V1+V1*sex */
3671: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3672: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3673: /* } */
3674: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3675: /* if (ij > ncodemax[j]) { */
3676: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3677: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3678: /* break; */
3679: /* } */
3680: /* } /\* end of loop on modality k *\/ */
3681: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3682:
3683: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3684:
3685: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3686: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3687: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3688: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3689: }
3690:
3691: ij=0;
3692: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3693: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3694: if((Ndum[i]!=0) && (i<=ncovcol)){
3695: ij++;
3696: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3697: Tvaraff[ij]=i; /*For printing (unclear) */
3698: }else{
3699: /* Tvaraff[ij]=0; */
3700: }
3701: }
3702: /* ij--; */
3703: cptcoveff=ij; /*Number of total covariates*/
3704:
3705: }
3706:
3707:
3708: /*********** Health Expectancies ****************/
3709:
3710: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3711:
3712: {
3713: /* Health expectancies, no variances */
3714: int i, j, nhstepm, hstepm, h, nstepm;
3715: int nhstepma, nstepma; /* Decreasing with age */
3716: double age, agelim, hf;
3717: double ***p3mat;
3718: double eip;
3719:
3720: pstamp(ficreseij);
3721: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3722: fprintf(ficreseij,"# Age");
3723: for(i=1; i<=nlstate;i++){
3724: for(j=1; j<=nlstate;j++){
3725: fprintf(ficreseij," e%1d%1d ",i,j);
3726: }
3727: fprintf(ficreseij," e%1d. ",i);
3728: }
3729: fprintf(ficreseij,"\n");
3730:
3731:
3732: if(estepm < stepm){
3733: printf ("Problem %d lower than %d\n",estepm, stepm);
3734: }
3735: else hstepm=estepm;
3736: /* We compute the life expectancy from trapezoids spaced every estepm months
3737: * This is mainly to measure the difference between two models: for example
3738: * if stepm=24 months pijx are given only every 2 years and by summing them
3739: * we are calculating an estimate of the Life Expectancy assuming a linear
3740: * progression in between and thus overestimating or underestimating according
3741: * to the curvature of the survival function. If, for the same date, we
3742: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3743: * to compare the new estimate of Life expectancy with the same linear
3744: * hypothesis. A more precise result, taking into account a more precise
3745: * curvature will be obtained if estepm is as small as stepm. */
3746:
3747: /* For example we decided to compute the life expectancy with the smallest unit */
3748: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3749: nhstepm is the number of hstepm from age to agelim
3750: nstepm is the number of stepm from age to agelin.
3751: Look at hpijx to understand the reason of that which relies in memory size
3752: and note for a fixed period like estepm months */
3753: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3754: survival function given by stepm (the optimization length). Unfortunately it
3755: means that if the survival funtion is printed only each two years of age and if
3756: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3757: results. So we changed our mind and took the option of the best precision.
3758: */
3759: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3760:
3761: agelim=AGESUP;
3762: /* If stepm=6 months */
3763: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3764: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3765:
3766: /* nhstepm age range expressed in number of stepm */
3767: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3768: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3769: /* if (stepm >= YEARM) hstepm=1;*/
3770: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3771: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3772:
3773: for (age=bage; age<=fage; age ++){
3774: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3775: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3776: /* if (stepm >= YEARM) hstepm=1;*/
3777: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3778:
3779: /* If stepm=6 months */
3780: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3781: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3782:
3783: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3784:
3785: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3786:
3787: printf("%d|",(int)age);fflush(stdout);
3788: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3789:
3790: /* Computing expectancies */
3791: for(i=1; i<=nlstate;i++)
3792: for(j=1; j<=nlstate;j++)
3793: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3794: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3795:
3796: /* 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]);*/
3797:
3798: }
3799:
3800: fprintf(ficreseij,"%3.0f",age );
3801: for(i=1; i<=nlstate;i++){
3802: eip=0;
3803: for(j=1; j<=nlstate;j++){
3804: eip +=eij[i][j][(int)age];
3805: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3806: }
3807: fprintf(ficreseij,"%9.4f", eip );
3808: }
3809: fprintf(ficreseij,"\n");
3810:
3811: }
3812: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3813: printf("\n");
3814: fprintf(ficlog,"\n");
3815:
3816: }
3817:
3818: 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[] )
3819:
3820: {
3821: /* Covariances of health expectancies eij and of total life expectancies according
3822: to initial status i, ei. .
3823: */
3824: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3825: int nhstepma, nstepma; /* Decreasing with age */
3826: double age, agelim, hf;
3827: double ***p3matp, ***p3matm, ***varhe;
3828: double **dnewm,**doldm;
3829: double *xp, *xm;
3830: double **gp, **gm;
3831: double ***gradg, ***trgradg;
3832: int theta;
3833:
3834: double eip, vip;
3835:
3836: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3837: xp=vector(1,npar);
3838: xm=vector(1,npar);
3839: dnewm=matrix(1,nlstate*nlstate,1,npar);
3840: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3841:
3842: pstamp(ficresstdeij);
3843: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3844: fprintf(ficresstdeij,"# Age");
3845: for(i=1; i<=nlstate;i++){
3846: for(j=1; j<=nlstate;j++)
3847: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3848: fprintf(ficresstdeij," e%1d. ",i);
3849: }
3850: fprintf(ficresstdeij,"\n");
3851:
3852: pstamp(ficrescveij);
3853: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3854: fprintf(ficrescveij,"# Age");
3855: for(i=1; i<=nlstate;i++)
3856: for(j=1; j<=nlstate;j++){
3857: cptj= (j-1)*nlstate+i;
3858: for(i2=1; i2<=nlstate;i2++)
3859: for(j2=1; j2<=nlstate;j2++){
3860: cptj2= (j2-1)*nlstate+i2;
3861: if(cptj2 <= cptj)
3862: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3863: }
3864: }
3865: fprintf(ficrescveij,"\n");
3866:
3867: if(estepm < stepm){
3868: printf ("Problem %d lower than %d\n",estepm, stepm);
3869: }
3870: else hstepm=estepm;
3871: /* We compute the life expectancy from trapezoids spaced every estepm months
3872: * This is mainly to measure the difference between two models: for example
3873: * if stepm=24 months pijx are given only every 2 years and by summing them
3874: * we are calculating an estimate of the Life Expectancy assuming a linear
3875: * progression in between and thus overestimating or underestimating according
3876: * to the curvature of the survival function. If, for the same date, we
3877: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3878: * to compare the new estimate of Life expectancy with the same linear
3879: * hypothesis. A more precise result, taking into account a more precise
3880: * curvature will be obtained if estepm is as small as stepm. */
3881:
3882: /* For example we decided to compute the life expectancy with the smallest unit */
3883: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3884: nhstepm is the number of hstepm from age to agelim
3885: nstepm is the number of stepm from age to agelin.
3886: Look at hpijx to understand the reason of that which relies in memory size
3887: and note for a fixed period like estepm months */
3888: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3889: survival function given by stepm (the optimization length). Unfortunately it
3890: means that if the survival funtion is printed only each two years of age and if
3891: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3892: results. So we changed our mind and took the option of the best precision.
3893: */
3894: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3895:
3896: /* If stepm=6 months */
3897: /* nhstepm age range expressed in number of stepm */
3898: agelim=AGESUP;
3899: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3900: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3901: /* if (stepm >= YEARM) hstepm=1;*/
3902: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3903:
3904: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3905: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3906: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3907: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3908: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3909: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3910:
3911: for (age=bage; age<=fage; age ++){
3912: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3913: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3914: /* if (stepm >= YEARM) hstepm=1;*/
3915: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3916:
3917: /* If stepm=6 months */
3918: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3919: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3920:
3921: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3922:
3923: /* Computing Variances of health expectancies */
3924: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3925: decrease memory allocation */
3926: for(theta=1; theta <=npar; theta++){
3927: for(i=1; i<=npar; i++){
3928: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3929: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3930: }
3931: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3932: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3933:
3934: for(j=1; j<= nlstate; j++){
3935: for(i=1; i<=nlstate; i++){
3936: for(h=0; h<=nhstepm-1; h++){
3937: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3938: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3939: }
3940: }
3941: }
3942:
3943: for(ij=1; ij<= nlstate*nlstate; ij++)
3944: for(h=0; h<=nhstepm-1; h++){
3945: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3946: }
3947: }/* End theta */
3948:
3949:
3950: for(h=0; h<=nhstepm-1; h++)
3951: for(j=1; j<=nlstate*nlstate;j++)
3952: for(theta=1; theta <=npar; theta++)
3953: trgradg[h][j][theta]=gradg[h][theta][j];
3954:
3955:
3956: for(ij=1;ij<=nlstate*nlstate;ij++)
3957: for(ji=1;ji<=nlstate*nlstate;ji++)
3958: varhe[ij][ji][(int)age] =0.;
3959:
3960: printf("%d|",(int)age);fflush(stdout);
3961: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3962: for(h=0;h<=nhstepm-1;h++){
3963: for(k=0;k<=nhstepm-1;k++){
3964: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3965: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3966: for(ij=1;ij<=nlstate*nlstate;ij++)
3967: for(ji=1;ji<=nlstate*nlstate;ji++)
3968: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3969: }
3970: }
3971:
3972: /* Computing expectancies */
3973: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3974: for(i=1; i<=nlstate;i++)
3975: for(j=1; j<=nlstate;j++)
3976: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3977: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3978:
3979: /* 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]);*/
3980:
3981: }
3982:
3983: fprintf(ficresstdeij,"%3.0f",age );
3984: for(i=1; i<=nlstate;i++){
3985: eip=0.;
3986: vip=0.;
3987: for(j=1; j<=nlstate;j++){
3988: eip += eij[i][j][(int)age];
3989: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3990: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3991: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3992: }
3993: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3994: }
3995: fprintf(ficresstdeij,"\n");
3996:
3997: fprintf(ficrescveij,"%3.0f",age );
3998: for(i=1; i<=nlstate;i++)
3999: for(j=1; j<=nlstate;j++){
4000: cptj= (j-1)*nlstate+i;
4001: for(i2=1; i2<=nlstate;i2++)
4002: for(j2=1; j2<=nlstate;j2++){
4003: cptj2= (j2-1)*nlstate+i2;
4004: if(cptj2 <= cptj)
4005: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4006: }
4007: }
4008: fprintf(ficrescveij,"\n");
4009:
4010: }
4011: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4012: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4013: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4014: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4015: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4016: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4017: printf("\n");
4018: fprintf(ficlog,"\n");
4019:
4020: free_vector(xm,1,npar);
4021: free_vector(xp,1,npar);
4022: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4023: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4024: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4025: }
4026:
4027: /************ Variance ******************/
4028: void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
4029: {
4030: /* Variance of health expectancies */
4031: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4032: /* double **newm;*/
4033: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4034:
4035: int movingaverage();
4036: double **dnewm,**doldm;
4037: double **dnewmp,**doldmp;
4038: int i, j, nhstepm, hstepm, h, nstepm ;
4039: int k;
4040: double *xp;
4041: double **gp, **gm; /* for var eij */
4042: double ***gradg, ***trgradg; /*for var eij */
4043: double **gradgp, **trgradgp; /* for var p point j */
4044: double *gpp, *gmp; /* for var p point j */
4045: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4046: double ***p3mat;
4047: double age,agelim, hf;
4048: double ***mobaverage;
4049: int theta;
4050: char digit[4];
4051: char digitp[25];
4052:
4053: char fileresprobmorprev[FILENAMELENGTH];
4054:
4055: if(popbased==1){
4056: if(mobilav!=0)
4057: strcpy(digitp,"-POPULBASED-MOBILAV_");
4058: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4059: }
4060: else
4061: strcpy(digitp,"-STABLBASED_");
4062:
4063: if (mobilav!=0) {
4064: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4065: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4066: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4067: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4068: }
4069: }
4070:
4071: strcpy(fileresprobmorprev,"PRMORPREV-");
4072: sprintf(digit,"%-d",ij);
4073: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4074: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4075: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4076: strcat(fileresprobmorprev,fileresu);
4077: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4078: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4079: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4080: }
4081: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4082: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4083: pstamp(ficresprobmorprev);
4084: 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);
4085: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4086: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4087: fprintf(ficresprobmorprev," p.%-d SE",j);
4088: for(i=1; i<=nlstate;i++)
4089: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4090: }
4091: fprintf(ficresprobmorprev,"\n");
4092:
4093: fprintf(ficgp,"\n# Routine varevsij");
4094: fprintf(ficgp,"\nunset title \n");
4095: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4096: 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");
4097: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4098: /* } */
4099: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4100: pstamp(ficresvij);
4101: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4102: if(popbased==1)
4103: 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);
4104: else
4105: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4106: fprintf(ficresvij,"# Age");
4107: for(i=1; i<=nlstate;i++)
4108: for(j=1; j<=nlstate;j++)
4109: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4110: fprintf(ficresvij,"\n");
4111:
4112: xp=vector(1,npar);
4113: dnewm=matrix(1,nlstate,1,npar);
4114: doldm=matrix(1,nlstate,1,nlstate);
4115: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4116: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4117:
4118: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4119: gpp=vector(nlstate+1,nlstate+ndeath);
4120: gmp=vector(nlstate+1,nlstate+ndeath);
4121: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4122:
4123: if(estepm < stepm){
4124: printf ("Problem %d lower than %d\n",estepm, stepm);
4125: }
4126: else hstepm=estepm;
4127: /* For example we decided to compute the life expectancy with the smallest unit */
4128: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4129: nhstepm is the number of hstepm from age to agelim
4130: nstepm is the number of stepm from age to agelim.
4131: Look at function hpijx to understand why (it is linked to memory size questions)
4132: we decided (b) to get a life expectancy respecting the most precise curvature of the
4133: survival function given by stepm (the optimization length). Unfortunately it
4134: means that if the survival funtion is printed every two years of age and if
4135: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4136: results. So we changed our mind and took the option of the best precision.
4137: */
4138: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4139: agelim = AGESUP;
4140: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4141: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4142: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4143: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4144: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4145: gp=matrix(0,nhstepm,1,nlstate);
4146: gm=matrix(0,nhstepm,1,nlstate);
4147:
4148:
4149: for(theta=1; theta <=npar; theta++){
4150: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4151: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4152: }
4153: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4154: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4155:
4156: if (popbased==1) {
4157: if(mobilav ==0){
4158: for(i=1; i<=nlstate;i++)
4159: prlim[i][i]=probs[(int)age][i][ij];
4160: }else{ /* mobilav */
4161: for(i=1; i<=nlstate;i++)
4162: prlim[i][i]=mobaverage[(int)age][i][ij];
4163: }
4164: }
4165:
4166: for(j=1; j<= nlstate; j++){
4167: for(h=0; h<=nhstepm; h++){
4168: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4169: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4170: }
4171: }
4172: /* This for computing probability of death (h=1 means
4173: computed over hstepm matrices product = hstepm*stepm months)
4174: as a weighted average of prlim.
4175: */
4176: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4177: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4178: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4179: }
4180: /* end probability of death */
4181:
4182: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4183: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4184: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4185: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
4186:
4187: if (popbased==1) {
4188: if(mobilav ==0){
4189: for(i=1; i<=nlstate;i++)
4190: prlim[i][i]=probs[(int)age][i][ij];
4191: }else{ /* mobilav */
4192: for(i=1; i<=nlstate;i++)
4193: prlim[i][i]=mobaverage[(int)age][i][ij];
4194: }
4195: }
4196:
4197: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4198: for(h=0; h<=nhstepm; h++){
4199: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4200: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4201: }
4202: }
4203: /* This for computing probability of death (h=1 means
4204: computed over hstepm matrices product = hstepm*stepm months)
4205: as a weighted average of prlim.
4206: */
4207: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4208: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4209: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4210: }
4211: /* end probability of death */
4212:
4213: for(j=1; j<= nlstate; j++) /* vareij */
4214: for(h=0; h<=nhstepm; h++){
4215: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4216: }
4217:
4218: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4219: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4220: }
4221:
4222: } /* End theta */
4223:
4224: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4225:
4226: for(h=0; h<=nhstepm; h++) /* veij */
4227: for(j=1; j<=nlstate;j++)
4228: for(theta=1; theta <=npar; theta++)
4229: trgradg[h][j][theta]=gradg[h][theta][j];
4230:
4231: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4232: for(theta=1; theta <=npar; theta++)
4233: trgradgp[j][theta]=gradgp[theta][j];
4234:
4235:
4236: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4237: for(i=1;i<=nlstate;i++)
4238: for(j=1;j<=nlstate;j++)
4239: vareij[i][j][(int)age] =0.;
4240:
4241: for(h=0;h<=nhstepm;h++){
4242: for(k=0;k<=nhstepm;k++){
4243: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4244: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4245: for(i=1;i<=nlstate;i++)
4246: for(j=1;j<=nlstate;j++)
4247: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4248: }
4249: }
4250:
4251: /* pptj */
4252: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4253: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4254: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4255: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4256: varppt[j][i]=doldmp[j][i];
4257: /* end ppptj */
4258: /* x centered again */
4259: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4260: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
4261:
4262: if (popbased==1) {
4263: if(mobilav ==0){
4264: for(i=1; i<=nlstate;i++)
4265: prlim[i][i]=probs[(int)age][i][ij];
4266: }else{ /* mobilav */
4267: for(i=1; i<=nlstate;i++)
4268: prlim[i][i]=mobaverage[(int)age][i][ij];
4269: }
4270: }
4271:
4272: /* This for computing probability of death (h=1 means
4273: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4274: as a weighted average of prlim.
4275: */
4276: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4277: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4278: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4279: }
4280: /* end probability of death */
4281:
4282: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4283: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4284: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4285: for(i=1; i<=nlstate;i++){
4286: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4287: }
4288: }
4289: fprintf(ficresprobmorprev,"\n");
4290:
4291: fprintf(ficresvij,"%.0f ",age );
4292: for(i=1; i<=nlstate;i++)
4293: for(j=1; j<=nlstate;j++){
4294: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4295: }
4296: fprintf(ficresvij,"\n");
4297: free_matrix(gp,0,nhstepm,1,nlstate);
4298: free_matrix(gm,0,nhstepm,1,nlstate);
4299: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4300: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4301: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4302: } /* End age */
4303: free_vector(gpp,nlstate+1,nlstate+ndeath);
4304: free_vector(gmp,nlstate+1,nlstate+ndeath);
4305: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4306: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4307: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4308: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4309: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4310: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4311: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4312: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4313: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4314: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4315: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4316: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4317: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4318: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4319: 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);
4320: /* 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);
4321: */
4322: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4323: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4324:
4325: free_vector(xp,1,npar);
4326: free_matrix(doldm,1,nlstate,1,nlstate);
4327: free_matrix(dnewm,1,nlstate,1,npar);
4328: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4329: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4330: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4331: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4332: fclose(ficresprobmorprev);
4333: fflush(ficgp);
4334: fflush(fichtm);
4335: } /* end varevsij */
4336:
4337: /************ Variance of prevlim ******************/
4338: void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyear, int ij, char strstart[])
4339: {
4340: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4341: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4342:
4343: double **dnewm,**doldm;
4344: int i, j, nhstepm, hstepm;
4345: double *xp;
4346: double *gp, *gm;
4347: double **gradg, **trgradg;
4348: double **mgm, **mgp;
4349: double age,agelim;
4350: int theta;
4351:
4352: pstamp(ficresvpl);
4353: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4354: fprintf(ficresvpl,"# Age");
4355: for(i=1; i<=nlstate;i++)
4356: fprintf(ficresvpl," %1d-%1d",i,i);
4357: fprintf(ficresvpl,"\n");
4358:
4359: xp=vector(1,npar);
4360: dnewm=matrix(1,nlstate,1,npar);
4361: doldm=matrix(1,nlstate,1,nlstate);
4362:
4363: hstepm=1*YEARM; /* Every year of age */
4364: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4365: agelim = AGESUP;
4366: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4367: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4368: if (stepm >= YEARM) hstepm=1;
4369: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4370: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4371: gradg=matrix(1,npar,1,nlstate);
4372: mgp=matrix(1,npar,1,nlstate);
4373: mgm=matrix(1,npar,1,nlstate);
4374: gp=vector(1,nlstate);
4375: gm=vector(1,nlstate);
4376:
4377: for(theta=1; theta <=npar; theta++){
4378: for(i=1; i<=npar; i++){ /* Computes gradient */
4379: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4380: }
4381: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Missing or not useful because 1 year */
4382: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4383: for(i=1;i<=nlstate;i++){
4384: gp[i] = prlim[i][i];
4385: mgp[theta][i] = prlim[i][i];
4386: }
4387: for(i=1; i<=npar; i++) /* Computes gradient */
4388: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4389: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
4390: for(i=1;i<=nlstate;i++){
4391: gm[i] = prlim[i][i];
4392: mgm[theta][i] = prlim[i][i];
4393: }
4394: for(i=1;i<=nlstate;i++)
4395: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4396: } /* End theta */
4397:
4398: trgradg =matrix(1,nlstate,1,npar);
4399:
4400: for(j=1; j<=nlstate;j++)
4401: for(theta=1; theta <=npar; theta++)
4402: trgradg[j][theta]=gradg[theta][j];
4403: if((int)age==68 ||(int)age== 69 ){
4404: printf("\nmgm mgp %d ",(int)age);
4405: for(j=1; j<=nlstate;j++){
4406: printf("%d ",j);
4407: for(theta=1; theta <=npar; theta++)
4408: printf("%d %lf %lf",theta,mgm[theta][j],mgp[theta][j]);
4409: printf("\n ");
4410: }
4411: }
4412: if((int)age==68 ||(int)age== 69 ){
4413: printf("\n gradg %d ",(int)age);
4414: for(j=1; j<=nlstate;j++){
4415: printf("%d ",j);
4416: for(theta=1; theta <=npar; theta++)
4417: printf("%d %lf ",theta,gradg[theta][j]);
4418: printf("\n ");
4419: }
4420: }
4421:
4422: for(i=1;i<=nlstate;i++)
4423: varpl[i][(int)age] =0.;
4424: if((int)age==68 ||(int)age== 69 ){
4425: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4426: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4427: }else{
4428: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4429: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4430: }
4431: for(i=1;i<=nlstate;i++)
4432: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4433:
4434: fprintf(ficresvpl,"%.0f ",age );
4435: for(i=1; i<=nlstate;i++)
4436: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4437: fprintf(ficresvpl,"\n");
4438: free_vector(gp,1,nlstate);
4439: free_vector(gm,1,nlstate);
4440: free_matrix(mgm,1,npar,1,nlstate);
4441: free_matrix(mgp,1,npar,1,nlstate);
4442: free_matrix(gradg,1,npar,1,nlstate);
4443: free_matrix(trgradg,1,nlstate,1,npar);
4444: } /* End age */
4445:
4446: free_vector(xp,1,npar);
4447: free_matrix(doldm,1,nlstate,1,npar);
4448: free_matrix(dnewm,1,nlstate,1,nlstate);
4449:
4450: }
4451:
4452: /************ Variance of one-step probabilities ******************/
4453: 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[])
4454: {
4455: int i, j=0, k1, l1, tj;
4456: int k2, l2, j1, z1;
4457: int k=0, l;
4458: int first=1, first1, first2;
4459: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4460: double **dnewm,**doldm;
4461: double *xp;
4462: double *gp, *gm;
4463: double **gradg, **trgradg;
4464: double **mu;
4465: double age, cov[NCOVMAX+1];
4466: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4467: int theta;
4468: char fileresprob[FILENAMELENGTH];
4469: char fileresprobcov[FILENAMELENGTH];
4470: char fileresprobcor[FILENAMELENGTH];
4471: double ***varpij;
4472:
4473: strcpy(fileresprob,"PROB_");
4474: strcat(fileresprob,fileres);
4475: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4476: printf("Problem with resultfile: %s\n", fileresprob);
4477: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4478: }
4479: strcpy(fileresprobcov,"PROBCOV_");
4480: strcat(fileresprobcov,fileresu);
4481: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4482: printf("Problem with resultfile: %s\n", fileresprobcov);
4483: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4484: }
4485: strcpy(fileresprobcor,"PROBCOR_");
4486: strcat(fileresprobcor,fileresu);
4487: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4488: printf("Problem with resultfile: %s\n", fileresprobcor);
4489: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4490: }
4491: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4492: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4493: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4494: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4495: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4496: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4497: pstamp(ficresprob);
4498: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4499: fprintf(ficresprob,"# Age");
4500: pstamp(ficresprobcov);
4501: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4502: fprintf(ficresprobcov,"# Age");
4503: pstamp(ficresprobcor);
4504: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4505: fprintf(ficresprobcor,"# Age");
4506:
4507:
4508: for(i=1; i<=nlstate;i++)
4509: for(j=1; j<=(nlstate+ndeath);j++){
4510: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4511: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4512: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4513: }
4514: /* fprintf(ficresprob,"\n");
4515: fprintf(ficresprobcov,"\n");
4516: fprintf(ficresprobcor,"\n");
4517: */
4518: xp=vector(1,npar);
4519: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4520: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4521: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4522: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4523: first=1;
4524: fprintf(ficgp,"\n# Routine varprob");
4525: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4526: fprintf(fichtm,"\n");
4527:
4528: 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);
4529: 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);
4530: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4531: and drawn. It helps understanding how is the covariance between two incidences.\
4532: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4533: 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. \
4534: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4535: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4536: standard deviations wide on each axis. <br>\
4537: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4538: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4539: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4540:
4541: cov[1]=1;
4542: /* tj=cptcoveff; */
4543: tj = (int) pow(2,cptcoveff);
4544: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4545: j1=0;
4546: for(j1=1; j1<=tj;j1++){
4547: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4548: /*j1++;*/
4549: if (cptcovn>0) {
4550: fprintf(ficresprob, "\n#********** Variable ");
4551: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4552: fprintf(ficresprob, "**********\n#\n");
4553: fprintf(ficresprobcov, "\n#********** Variable ");
4554: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4555: fprintf(ficresprobcov, "**********\n#\n");
4556:
4557: fprintf(ficgp, "\n#********** Variable ");
4558: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4559: fprintf(ficgp, "**********\n#\n");
4560:
4561:
4562: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4563: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4564: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4565:
4566: fprintf(ficresprobcor, "\n#********** Variable ");
4567: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4568: fprintf(ficresprobcor, "**********\n#");
4569: }
4570:
4571: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4572: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4573: gp=vector(1,(nlstate)*(nlstate+ndeath));
4574: gm=vector(1,(nlstate)*(nlstate+ndeath));
4575: for (age=bage; age<=fage; age ++){
4576: cov[2]=age;
4577: if(nagesqr==1)
4578: cov[3]= age*age;
4579: for (k=1; k<=cptcovn;k++) {
4580: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4581: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4582: * 1 1 1 1 1
4583: * 2 2 1 1 1
4584: * 3 1 2 1 1
4585: */
4586: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4587: }
4588: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4589: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4590: for (k=1; k<=cptcovprod;k++)
4591: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4592:
4593:
4594: for(theta=1; theta <=npar; theta++){
4595: for(i=1; i<=npar; i++)
4596: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4597:
4598: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4599:
4600: k=0;
4601: for(i=1; i<= (nlstate); i++){
4602: for(j=1; j<=(nlstate+ndeath);j++){
4603: k=k+1;
4604: gp[k]=pmmij[i][j];
4605: }
4606: }
4607:
4608: for(i=1; i<=npar; i++)
4609: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4610:
4611: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4612: k=0;
4613: for(i=1; i<=(nlstate); i++){
4614: for(j=1; j<=(nlstate+ndeath);j++){
4615: k=k+1;
4616: gm[k]=pmmij[i][j];
4617: }
4618: }
4619:
4620: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4621: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4622: }
4623:
4624: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4625: for(theta=1; theta <=npar; theta++)
4626: trgradg[j][theta]=gradg[theta][j];
4627:
4628: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4629: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4630:
4631: pmij(pmmij,cov,ncovmodel,x,nlstate);
4632:
4633: k=0;
4634: for(i=1; i<=(nlstate); i++){
4635: for(j=1; j<=(nlstate+ndeath);j++){
4636: k=k+1;
4637: mu[k][(int) age]=pmmij[i][j];
4638: }
4639: }
4640: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4641: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4642: varpij[i][j][(int)age] = doldm[i][j];
4643:
4644: /*printf("\n%d ",(int)age);
4645: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4646: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4647: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4648: }*/
4649:
4650: fprintf(ficresprob,"\n%d ",(int)age);
4651: fprintf(ficresprobcov,"\n%d ",(int)age);
4652: fprintf(ficresprobcor,"\n%d ",(int)age);
4653:
4654: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4655: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4656: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4657: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4658: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4659: }
4660: i=0;
4661: for (k=1; k<=(nlstate);k++){
4662: for (l=1; l<=(nlstate+ndeath);l++){
4663: i++;
4664: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4665: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4666: for (j=1; j<=i;j++){
4667: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4668: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4669: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4670: }
4671: }
4672: }/* end of loop for state */
4673: } /* end of loop for age */
4674: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4675: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4676: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4677: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4678:
4679: /* Confidence intervalle of pij */
4680: /*
4681: fprintf(ficgp,"\nunset parametric;unset label");
4682: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4683: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4684: 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);
4685: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4686: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4687: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4688: */
4689:
4690: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4691: first1=1;first2=2;
4692: for (k2=1; k2<=(nlstate);k2++){
4693: for (l2=1; l2<=(nlstate+ndeath);l2++){
4694: if(l2==k2) continue;
4695: j=(k2-1)*(nlstate+ndeath)+l2;
4696: for (k1=1; k1<=(nlstate);k1++){
4697: for (l1=1; l1<=(nlstate+ndeath);l1++){
4698: if(l1==k1) continue;
4699: i=(k1-1)*(nlstate+ndeath)+l1;
4700: if(i<=j) continue;
4701: for (age=bage; age<=fage; age ++){
4702: if ((int)age %5==0){
4703: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4704: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4705: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4706: mu1=mu[i][(int) age]/stepm*YEARM ;
4707: mu2=mu[j][(int) age]/stepm*YEARM;
4708: c12=cv12/sqrt(v1*v2);
4709: /* Computing eigen value of matrix of covariance */
4710: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4711: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4712: if ((lc2 <0) || (lc1 <0) ){
4713: if(first2==1){
4714: first1=0;
4715: 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);
4716: }
4717: 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);
4718: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4719: /* lc2=fabs(lc2); */
4720: }
4721:
4722: /* Eigen vectors */
4723: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4724: /*v21=sqrt(1.-v11*v11); *//* error */
4725: v21=(lc1-v1)/cv12*v11;
4726: v12=-v21;
4727: v22=v11;
4728: tnalp=v21/v11;
4729: if(first1==1){
4730: first1=0;
4731: 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);
4732: }
4733: 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);
4734: /*printf(fignu*/
4735: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4736: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4737: if(first==1){
4738: first=0;
4739: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4740: fprintf(ficgp,"\nset parametric;unset label");
4741: 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);
4742: fprintf(ficgp,"\nset ter svg size 640, 480");
4743: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4744: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4745: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4746: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4747: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4748: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4749: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4750: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4751: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4752: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4753: 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",\
4754: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4755: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4756: }else{
4757: first=0;
4758: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4759: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4760: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4761: 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",\
4762: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4763: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4764: }/* if first */
4765: } /* age mod 5 */
4766: } /* end loop age */
4767: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4768: first=1;
4769: } /*l12 */
4770: } /* k12 */
4771: } /*l1 */
4772: }/* k1 */
4773: /* } */ /* loop covariates */
4774: }
4775: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4776: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4777: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4778: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4779: free_vector(xp,1,npar);
4780: fclose(ficresprob);
4781: fclose(ficresprobcov);
4782: fclose(ficresprobcor);
4783: fflush(ficgp);
4784: fflush(fichtmcov);
4785: }
4786:
4787:
4788: /******************* Printing html file ***********/
4789: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4790: int lastpass, int stepm, int weightopt, char model[],\
4791: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4792: int popforecast, int estepm ,\
4793: double jprev1, double mprev1,double anprev1, \
4794: double jprev2, double mprev2,double anprev2){
4795: int jj1, k1, i1, cpt;
4796:
4797: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4798: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4799: </ul>");
4800: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4801: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4802: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
4803: fprintf(fichtm,"\
4804: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4805: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
4806: fprintf(fichtm,"\
4807: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4808: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
4809: fprintf(fichtm,"\
4810: - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
4811: <a href=\"%s\">%s</a> <br>\n",
4812: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
4813: fprintf(fichtm,"\
4814: - Population projections by age and states: \
4815: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
4816:
4817: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4818:
4819: m=pow(2,cptcoveff);
4820: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4821:
4822: jj1=0;
4823: for(k1=1; k1<=m;k1++){
4824: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4825: jj1++;
4826: if (cptcovn > 0) {
4827: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4828: for (cpt=1; cpt<=cptcoveff;cpt++){
4829: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4830: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
4831: }
4832: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4833: }
4834: /* aij, bij */
4835: fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
4836: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4837: /* Pij */
4838: fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
4839: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4840: /* Quasi-incidences */
4841: fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4842: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
4843: incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
4844: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
4845: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4846: /* Survival functions (period) in state j */
4847: for(cpt=1; cpt<=nlstate;cpt++){
4848: 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> \
4849: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4850: }
4851: /* State specific survival functions (period) */
4852: for(cpt=1; cpt<=nlstate;cpt++){
4853: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
4854: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4855: <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);
4856: }
4857: /* Period (stable) prevalence in each health state */
4858: for(cpt=1; cpt<=nlstate;cpt++){
4859: 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> \
4860: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4861: }
4862: for(cpt=1; cpt<=nlstate;cpt++) {
4863: 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> \
4864: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
4865: }
4866: /* } /\* end i1 *\/ */
4867: }/* End k1 */
4868: fprintf(fichtm,"</ul>");
4869:
4870: fprintf(fichtm,"\
4871: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4872: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
4873: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
4874: But because parameters are usually highly correlated (a higher incidence of disability \
4875: and a higher incidence of recovery can give very close observed transition) it might \
4876: be very useful to look not only at linear confidence intervals estimated from the \
4877: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4878: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4879: covariance matrix of the one-step probabilities. \
4880: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
4881:
4882: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4883: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
4884: fprintf(fichtm,"\
4885: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4886: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
4887:
4888: fprintf(fichtm,"\
4889: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4890: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
4891: fprintf(fichtm,"\
4892: - 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): \
4893: <a href=\"%s\">%s</a> <br>\n</li>",
4894: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
4895: fprintf(fichtm,"\
4896: - (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): \
4897: <a href=\"%s\">%s</a> <br>\n</li>",
4898: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
4899: fprintf(fichtm,"\
4900: - 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",
4901: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
4902: fprintf(fichtm,"\
4903: - 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",
4904: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
4905: fprintf(fichtm,"\
4906: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4907: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
4908:
4909: /* if(popforecast==1) fprintf(fichtm,"\n */
4910: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4911: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4912: /* <br>",fileres,fileres,fileres,fileres); */
4913: /* else */
4914: /* 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); */
4915: fflush(fichtm);
4916: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4917:
4918: m=pow(2,cptcoveff);
4919: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4920:
4921: jj1=0;
4922: for(k1=1; k1<=m;k1++){
4923: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4924: jj1++;
4925: if (cptcovn > 0) {
4926: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4927: for (cpt=1; cpt<=cptcoveff;cpt++)
4928: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4929: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4930: }
4931: for(cpt=1; cpt<=nlstate;cpt++) {
4932: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4933: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
4934: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
4935: }
4936: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4937: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4938: true period expectancies (those weighted with period prevalences are also\
4939: drawn in addition to the population based expectancies computed using\
4940: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
4941: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
4942: /* } /\* end i1 *\/ */
4943: }/* End k1 */
4944: fprintf(fichtm,"</ul>");
4945: fflush(fichtm);
4946: }
4947:
4948: /******************* Gnuplot file **************/
4949: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4950:
4951: char dirfileres[132],optfileres[132];
4952: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4953: int ng=0;
4954: int vpopbased;
4955: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4956: /* printf("Problem with file %s",optionfilegnuplot); */
4957: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4958: /* } */
4959:
4960: /*#ifdef windows */
4961: fprintf(ficgp,"cd \"%s\" \n",pathc);
4962: /*#endif */
4963: m=pow(2,cptcoveff);
4964:
4965: /* Contribution to likelihood */
4966: /* Plot the probability implied in the likelihood */
4967: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
4968: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
4969: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
4970: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
4971: /* nice for mle=4 plot by number of matrix products.
4972: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
4973: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
4974: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
4975: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
4976: 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));
4977: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
4978: 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));
4979: for (i=1; i<= nlstate ; i ++) {
4980: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
4981: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
4982: 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);
4983: for (j=2; j<= nlstate+ndeath ; j ++) {
4984: 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);
4985: }
4986: fprintf(ficgp,";\nset out; unset ylabel;\n");
4987: }
4988: /* 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 */
4989: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
4990: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
4991: fprintf(ficgp,"\nset out;unset log\n");
4992: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
4993:
4994: strcpy(dirfileres,optionfilefiname);
4995: strcpy(optfileres,"vpl");
4996: /* 1eme*/
4997: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
4998: for (cpt=1; cpt<= nlstate ; cpt ++) {
4999: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5000: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5001: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5002: fprintf(ficgp,"set xlabel \"Age\" \n\
5003: set ylabel \"Probability\" \n\
5004: set ter svg size 640, 480\n\
5005: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5006:
5007: for (i=1; i<= nlstate ; i ++) {
5008: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5009: else fprintf(ficgp," %%*lf (%%*lf)");
5010: }
5011: 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);
5012: for (i=1; i<= nlstate ; i ++) {
5013: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5014: else fprintf(ficgp," %%*lf (%%*lf)");
5015: }
5016: 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);
5017: for (i=1; i<= nlstate ; i ++) {
5018: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5019: else fprintf(ficgp," %%*lf (%%*lf)");
5020: }
5021: 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));
5022: fprintf(ficgp,"\nset out \n");
5023: } /* k1 */
5024: } /* cpt */
5025: /*2 eme*/
5026: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
5027: for (k1=1; k1<= m ; k1 ++) {
5028: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5029: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5030: if(vpopbased==0)
5031: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5032: else
5033: fprintf(ficgp,"\nreplot ");
5034: for (i=1; i<= nlstate+1 ; i ++) {
5035: k=2*i;
5036: 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);
5037: for (j=1; j<= nlstate+1 ; j ++) {
5038: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5039: else fprintf(ficgp," %%*lf (%%*lf)");
5040: }
5041: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5042: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5043: 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);
5044: for (j=1; j<= nlstate+1 ; j ++) {
5045: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5046: else fprintf(ficgp," %%*lf (%%*lf)");
5047: }
5048: fprintf(ficgp,"\" t\"\" w l lt 0,");
5049: 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);
5050: for (j=1; j<= nlstate+1 ; j ++) {
5051: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5052: else fprintf(ficgp," %%*lf (%%*lf)");
5053: }
5054: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5055: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5056: } /* state */
5057: } /* vpopbased */
5058: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5059: } /* k1 */
5060: /*3eme*/
5061:
5062: for (k1=1; k1<= m ; k1 ++) {
5063: for (cpt=1; cpt<= nlstate ; cpt ++) {
5064: /* k=2+nlstate*(2*cpt-2); */
5065: k=2+(nlstate+1)*(cpt-1);
5066: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5067: fprintf(ficgp,"set ter svg size 640, 480\n\
5068: 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);
5069: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5070: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5071: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5072: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5073: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5074: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5075:
5076: */
5077: for (i=1; i< nlstate ; i ++) {
5078: 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);
5079: /* 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);*/
5080:
5081: }
5082: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5083: }
5084: }
5085:
5086: /* Survival functions (period) from state i in state j by initial state i */
5087: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5088: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5089: k=3;
5090: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
5091: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5092: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5093: set ter svg size 640, 480\n\
5094: unset log y\n\
5095: plot [%.f:%.f] ", ageminpar, agemaxpar);
5096: for (i=1; i<= nlstate ; i ++){
5097: if(i==1)
5098: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5099: else
5100: fprintf(ficgp,", '' ");
5101: l=(nlstate+ndeath)*(i-1)+1;
5102: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5103: for (j=2; j<= nlstate+ndeath ; j ++)
5104: fprintf(ficgp,"+$%d",k+l+j-1);
5105: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5106: } /* nlstate */
5107: fprintf(ficgp,"\nset out\n");
5108: } /* end cpt state*/
5109: } /* end covariate */
5110:
5111: /* Survival functions (period) from state i in state j by final state j */
5112: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5113: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5114: k=3;
5115: 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);
5116: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5117: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5118: set ter svg size 640, 480\n\
5119: unset log y\n\
5120: plot [%.f:%.f] ", ageminpar, agemaxpar);
5121: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5122: if(j==1)
5123: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5124: else
5125: fprintf(ficgp,", '' ");
5126: l=(nlstate+ndeath)*(cpt-1) +j;
5127: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5128: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5129: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5130: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5131: } /* nlstate */
5132: fprintf(ficgp,", '' ");
5133: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5134: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5135: l=(nlstate+ndeath)*(cpt-1) +j;
5136: if(j < nlstate)
5137: fprintf(ficgp,"$%d +",k+l);
5138: else
5139: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5140: }
5141: fprintf(ficgp,"\nset out\n");
5142: } /* end cpt state*/
5143: } /* end covariate */
5144:
5145: /* CV preval stable (period) for each covariate */
5146: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5147: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5148: k=3;
5149: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
5150: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5151: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5152: set ter svg size 640, 480\n\
5153: unset log y\n\
5154: plot [%.f:%.f] ", ageminpar, agemaxpar);
5155: for (i=1; i<= nlstate ; i ++){
5156: if(i==1)
5157: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5158: else
5159: fprintf(ficgp,", '' ");
5160: l=(nlstate+ndeath)*(i-1)+1;
5161: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5162: for (j=2; j<= nlstate ; j ++)
5163: fprintf(ficgp,"+$%d",k+l+j-1);
5164: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5165: } /* nlstate */
5166: fprintf(ficgp,"\nset out\n");
5167: } /* end cpt state*/
5168: } /* end covariate */
5169:
5170: /* proba elementaires */
5171: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5172: for(i=1,jk=1; i <=nlstate; i++){
5173: fprintf(ficgp,"# initial state %d\n",i);
5174: for(k=1; k <=(nlstate+ndeath); k++){
5175: if (k != i) {
5176: fprintf(ficgp,"# current state %d\n",k);
5177: for(j=1; j <=ncovmodel; j++){
5178: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5179: jk++;
5180: }
5181: fprintf(ficgp,"\n");
5182: }
5183: }
5184: }
5185: fprintf(ficgp,"##############\n#\n");
5186:
5187: /*goto avoid;*/
5188: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5189: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5190: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5191: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5192: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5193: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5194: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5195: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5196: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5197: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5198: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5199: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5200: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5201: fprintf(ficgp,"#\n");
5202: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5203: fprintf(ficgp,"# ng=%d\n",ng);
5204: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5205: for(jk=1; jk <=m; jk++) {
5206: fprintf(ficgp,"# jk=%d\n",jk);
5207: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5208: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5209: if (ng==1){
5210: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5211: fprintf(ficgp,"\nunset log y");
5212: }else if (ng==2){
5213: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5214: fprintf(ficgp,"\nset log y");
5215: }else if (ng==3){
5216: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5217: fprintf(ficgp,"\nset log y");
5218: }else
5219: fprintf(ficgp,"\nunset title ");
5220: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5221: i=1;
5222: for(k2=1; k2<=nlstate; k2++) {
5223: k3=i;
5224: for(k=1; k<=(nlstate+ndeath); k++) {
5225: if (k != k2){
5226: switch( ng) {
5227: case 1:
5228: if(nagesqr==0)
5229: fprintf(ficgp," p%d+p%d*x",i,i+1);
5230: else /* nagesqr =1 */
5231: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5232: break;
5233: case 2: /* ng=2 */
5234: if(nagesqr==0)
5235: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5236: else /* nagesqr =1 */
5237: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5238: break;
5239: case 3:
5240: if(nagesqr==0)
5241: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5242: else /* nagesqr =1 */
5243: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5244: break;
5245: }
5246: ij=1;/* To be checked else nbcode[0][0] wrong */
5247: for(j=3; j <=ncovmodel-nagesqr; j++) {
5248: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5249: if(ij <=cptcovage) { /* Bug valgrind */
5250: if((j-2)==Tage[ij]) { /* Bug valgrind */
5251: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5252: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5253: ij++;
5254: }
5255: }
5256: else
5257: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5258: }
5259: if(ng != 1){
5260: fprintf(ficgp,")/(1");
5261:
5262: for(k1=1; k1 <=nlstate; k1++){
5263: if(nagesqr==0)
5264: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5265: else /* nagesqr =1 */
5266: 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);
5267:
5268: ij=1;
5269: for(j=3; j <=ncovmodel-nagesqr; j++){
5270: if(ij <=cptcovage) { /* Bug valgrind */
5271: if((j-2)==Tage[ij]) { /* Bug valgrind */
5272: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5273: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5274: ij++;
5275: }
5276: }
5277: else
5278: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5279: }
5280: fprintf(ficgp,")");
5281: }
5282: fprintf(ficgp,")");
5283: if(ng ==2)
5284: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5285: else /* ng= 3 */
5286: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5287: }else{ /* end ng <> 1 */
5288: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5289: }
5290: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5291: i=i+ncovmodel;
5292: }
5293: } /* end k */
5294: } /* end k2 */
5295: fprintf(ficgp,"\n set out\n");
5296: } /* end jk */
5297: } /* end ng */
5298: /* avoid: */
5299: fflush(ficgp);
5300: } /* end gnuplot */
5301:
5302:
5303: /*************** Moving average **************/
5304: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5305:
5306: int i, cpt, cptcod;
5307: int modcovmax =1;
5308: int mobilavrange, mob;
5309: double age;
5310:
5311: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5312: a covariate has 2 modalities */
5313: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5314:
5315: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5316: if(mobilav==1) mobilavrange=5; /* default */
5317: else mobilavrange=mobilav;
5318: for (age=bage; age<=fage; age++)
5319: for (i=1; i<=nlstate;i++)
5320: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5321: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5322: /* We keep the original values on the extreme ages bage, fage and for
5323: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5324: we use a 5 terms etc. until the borders are no more concerned.
5325: */
5326: for (mob=3;mob <=mobilavrange;mob=mob+2){
5327: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5328: for (i=1; i<=nlstate;i++){
5329: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5330: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5331: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5332: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5333: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5334: }
5335: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5336: }
5337: }
5338: }/* end age */
5339: }/* end mob */
5340: }else return -1;
5341: return 0;
5342: }/* End movingaverage */
5343:
5344:
5345: /************** Forecasting ******************/
5346: 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){
5347: /* proj1, year, month, day of starting projection
5348: agemin, agemax range of age
5349: dateprev1 dateprev2 range of dates during which prevalence is computed
5350: anproj2 year of en of projection (same day and month as proj1).
5351: */
5352: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5353: double agec; /* generic age */
5354: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5355: double *popeffectif,*popcount;
5356: double ***p3mat;
5357: double ***mobaverage;
5358: char fileresf[FILENAMELENGTH];
5359:
5360: agelim=AGESUP;
5361: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5362:
5363: strcpy(fileresf,"F_");
5364: strcat(fileresf,fileresu);
5365: if((ficresf=fopen(fileresf,"w"))==NULL) {
5366: printf("Problem with forecast resultfile: %s\n", fileresf);
5367: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5368: }
5369: printf("Computing forecasting: result on file '%s' \n", fileresf);
5370: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5371:
5372: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5373:
5374: if (mobilav!=0) {
5375: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5376: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5377: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5378: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5379: }
5380: }
5381:
5382: stepsize=(int) (stepm+YEARM-1)/YEARM;
5383: if (stepm<=12) stepsize=1;
5384: if(estepm < stepm){
5385: printf ("Problem %d lower than %d\n",estepm, stepm);
5386: }
5387: else hstepm=estepm;
5388:
5389: hstepm=hstepm/stepm;
5390: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5391: fractional in yp1 */
5392: anprojmean=yp;
5393: yp2=modf((yp1*12),&yp);
5394: mprojmean=yp;
5395: yp1=modf((yp2*30.5),&yp);
5396: jprojmean=yp;
5397: if(jprojmean==0) jprojmean=1;
5398: if(mprojmean==0) jprojmean=1;
5399:
5400: i1=cptcoveff;
5401: if (cptcovn < 1){i1=1;}
5402:
5403: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5404:
5405: fprintf(ficresf,"#****** Routine prevforecast **\n");
5406:
5407: /* if (h==(int)(YEARM*yearp)){ */
5408: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5409: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5410: k=k+1;
5411: fprintf(ficresf,"\n#******");
5412: for(j=1;j<=cptcoveff;j++) {
5413: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5414: }
5415: fprintf(ficresf,"******\n");
5416: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
5417: for(j=1; j<=nlstate+ndeath;j++){
5418: for(i=1; i<=nlstate;i++)
5419: fprintf(ficresf," p%d%d",i,j);
5420: fprintf(ficresf," p.%d",j);
5421: }
5422: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5423: fprintf(ficresf,"\n");
5424: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5425:
5426: for (agec=fage; agec>=(ageminpar-1); agec--){
5427: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5428: nhstepm = nhstepm/hstepm;
5429: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5430: oldm=oldms;savm=savms;
5431: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5432:
5433: for (h=0; h<=nhstepm; h++){
5434: if (h*hstepm/YEARM*stepm ==yearp) {
5435: fprintf(ficresf,"\n");
5436: for(j=1;j<=cptcoveff;j++)
5437: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5438: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5439: }
5440: for(j=1; j<=nlstate+ndeath;j++) {
5441: ppij=0.;
5442: for(i=1; i<=nlstate;i++) {
5443: if (mobilav==1)
5444: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5445: else {
5446: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5447: }
5448: if (h*hstepm/YEARM*stepm== yearp) {
5449: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5450: }
5451: } /* end i */
5452: if (h*hstepm/YEARM*stepm==yearp) {
5453: fprintf(ficresf," %.3f", ppij);
5454: }
5455: }/* end j */
5456: } /* end h */
5457: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5458: } /* end agec */
5459: } /* end yearp */
5460: } /* end cptcod */
5461: } /* end cptcov */
5462:
5463: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5464:
5465: fclose(ficresf);
5466: }
5467:
5468: /************** Forecasting *****not tested NB*************/
5469: 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){
5470:
5471: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5472: int *popage;
5473: double calagedatem, agelim, kk1, kk2;
5474: double *popeffectif,*popcount;
5475: double ***p3mat,***tabpop,***tabpopprev;
5476: double ***mobaverage;
5477: char filerespop[FILENAMELENGTH];
5478:
5479: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5480: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5481: agelim=AGESUP;
5482: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5483:
5484: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5485:
5486:
5487: strcpy(filerespop,"POP_");
5488: strcat(filerespop,fileresu);
5489: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5490: printf("Problem with forecast resultfile: %s\n", filerespop);
5491: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5492: }
5493: printf("Computing forecasting: result on file '%s' \n", filerespop);
5494: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5495:
5496: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5497:
5498: if (mobilav!=0) {
5499: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5500: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5501: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5502: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5503: }
5504: }
5505:
5506: stepsize=(int) (stepm+YEARM-1)/YEARM;
5507: if (stepm<=12) stepsize=1;
5508:
5509: agelim=AGESUP;
5510:
5511: hstepm=1;
5512: hstepm=hstepm/stepm;
5513:
5514: if (popforecast==1) {
5515: if((ficpop=fopen(popfile,"r"))==NULL) {
5516: printf("Problem with population file : %s\n",popfile);exit(0);
5517: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5518: }
5519: popage=ivector(0,AGESUP);
5520: popeffectif=vector(0,AGESUP);
5521: popcount=vector(0,AGESUP);
5522:
5523: i=1;
5524: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5525:
5526: imx=i;
5527: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5528: }
5529:
5530: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5531: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5532: k=k+1;
5533: fprintf(ficrespop,"\n#******");
5534: for(j=1;j<=cptcoveff;j++) {
5535: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5536: }
5537: fprintf(ficrespop,"******\n");
5538: fprintf(ficrespop,"# Age");
5539: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5540: if (popforecast==1) fprintf(ficrespop," [Population]");
5541:
5542: for (cpt=0; cpt<=0;cpt++) {
5543: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5544:
5545: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5546: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5547: nhstepm = nhstepm/hstepm;
5548:
5549: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5550: oldm=oldms;savm=savms;
5551: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5552:
5553: for (h=0; h<=nhstepm; h++){
5554: if (h==(int) (calagedatem+YEARM*cpt)) {
5555: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5556: }
5557: for(j=1; j<=nlstate+ndeath;j++) {
5558: kk1=0.;kk2=0;
5559: for(i=1; i<=nlstate;i++) {
5560: if (mobilav==1)
5561: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5562: else {
5563: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5564: }
5565: }
5566: if (h==(int)(calagedatem+12*cpt)){
5567: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5568: /*fprintf(ficrespop," %.3f", kk1);
5569: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5570: }
5571: }
5572: for(i=1; i<=nlstate;i++){
5573: kk1=0.;
5574: for(j=1; j<=nlstate;j++){
5575: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5576: }
5577: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5578: }
5579:
5580: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5581: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5582: }
5583: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5584: }
5585: }
5586:
5587: /******/
5588:
5589: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5590: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5591: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5592: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5593: nhstepm = nhstepm/hstepm;
5594:
5595: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5596: oldm=oldms;savm=savms;
5597: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5598: for (h=0; h<=nhstepm; h++){
5599: if (h==(int) (calagedatem+YEARM*cpt)) {
5600: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5601: }
5602: for(j=1; j<=nlstate+ndeath;j++) {
5603: kk1=0.;kk2=0;
5604: for(i=1; i<=nlstate;i++) {
5605: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5606: }
5607: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5608: }
5609: }
5610: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5611: }
5612: }
5613: }
5614: }
5615:
5616: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5617:
5618: if (popforecast==1) {
5619: free_ivector(popage,0,AGESUP);
5620: free_vector(popeffectif,0,AGESUP);
5621: free_vector(popcount,0,AGESUP);
5622: }
5623: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5624: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5625: fclose(ficrespop);
5626: } /* End of popforecast */
5627:
5628: int fileappend(FILE *fichier, char *optionfich)
5629: {
5630: if((fichier=fopen(optionfich,"a"))==NULL) {
5631: printf("Problem with file: %s\n", optionfich);
5632: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5633: return (0);
5634: }
5635: fflush(fichier);
5636: return (1);
5637: }
5638:
5639:
5640: /**************** function prwizard **********************/
5641: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5642: {
5643:
5644: /* Wizard to print covariance matrix template */
5645:
5646: char ca[32], cb[32];
5647: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5648: int numlinepar;
5649:
5650: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5651: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5652: for(i=1; i <=nlstate; i++){
5653: jj=0;
5654: for(j=1; j <=nlstate+ndeath; j++){
5655: if(j==i) continue;
5656: jj++;
5657: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5658: printf("%1d%1d",i,j);
5659: fprintf(ficparo,"%1d%1d",i,j);
5660: for(k=1; k<=ncovmodel;k++){
5661: /* printf(" %lf",param[i][j][k]); */
5662: /* fprintf(ficparo," %lf",param[i][j][k]); */
5663: printf(" 0.");
5664: fprintf(ficparo," 0.");
5665: }
5666: printf("\n");
5667: fprintf(ficparo,"\n");
5668: }
5669: }
5670: printf("# Scales (for hessian or gradient estimation)\n");
5671: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5672: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5673: for(i=1; i <=nlstate; i++){
5674: jj=0;
5675: for(j=1; j <=nlstate+ndeath; j++){
5676: if(j==i) continue;
5677: jj++;
5678: fprintf(ficparo,"%1d%1d",i,j);
5679: printf("%1d%1d",i,j);
5680: fflush(stdout);
5681: for(k=1; k<=ncovmodel;k++){
5682: /* printf(" %le",delti3[i][j][k]); */
5683: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5684: printf(" 0.");
5685: fprintf(ficparo," 0.");
5686: }
5687: numlinepar++;
5688: printf("\n");
5689: fprintf(ficparo,"\n");
5690: }
5691: }
5692: printf("# Covariance matrix\n");
5693: /* # 121 Var(a12)\n\ */
5694: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5695: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5696: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5697: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5698: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5699: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5700: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5701: fflush(stdout);
5702: fprintf(ficparo,"# Covariance matrix\n");
5703: /* # 121 Var(a12)\n\ */
5704: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5705: /* # ...\n\ */
5706: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5707:
5708: for(itimes=1;itimes<=2;itimes++){
5709: jj=0;
5710: for(i=1; i <=nlstate; i++){
5711: for(j=1; j <=nlstate+ndeath; j++){
5712: if(j==i) continue;
5713: for(k=1; k<=ncovmodel;k++){
5714: jj++;
5715: ca[0]= k+'a'-1;ca[1]='\0';
5716: if(itimes==1){
5717: printf("#%1d%1d%d",i,j,k);
5718: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5719: }else{
5720: printf("%1d%1d%d",i,j,k);
5721: fprintf(ficparo,"%1d%1d%d",i,j,k);
5722: /* printf(" %.5le",matcov[i][j]); */
5723: }
5724: ll=0;
5725: for(li=1;li <=nlstate; li++){
5726: for(lj=1;lj <=nlstate+ndeath; lj++){
5727: if(lj==li) continue;
5728: for(lk=1;lk<=ncovmodel;lk++){
5729: ll++;
5730: if(ll<=jj){
5731: cb[0]= lk +'a'-1;cb[1]='\0';
5732: if(ll<jj){
5733: if(itimes==1){
5734: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5735: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5736: }else{
5737: printf(" 0.");
5738: fprintf(ficparo," 0.");
5739: }
5740: }else{
5741: if(itimes==1){
5742: printf(" Var(%s%1d%1d)",ca,i,j);
5743: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5744: }else{
5745: printf(" 0.");
5746: fprintf(ficparo," 0.");
5747: }
5748: }
5749: }
5750: } /* end lk */
5751: } /* end lj */
5752: } /* end li */
5753: printf("\n");
5754: fprintf(ficparo,"\n");
5755: numlinepar++;
5756: } /* end k*/
5757: } /*end j */
5758: } /* end i */
5759: } /* end itimes */
5760:
5761: } /* end of prwizard */
5762: /******************* Gompertz Likelihood ******************************/
5763: double gompertz(double x[])
5764: {
5765: double A,B,L=0.0,sump=0.,num=0.;
5766: int i,n=0; /* n is the size of the sample */
5767:
5768: for (i=0;i<=imx-1 ; i++) {
5769: sump=sump+weight[i];
5770: /* sump=sump+1;*/
5771: num=num+1;
5772: }
5773:
5774:
5775: /* for (i=0; i<=imx; i++)
5776: 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]);*/
5777:
5778: for (i=1;i<=imx ; i++)
5779: {
5780: if (cens[i] == 1 && wav[i]>1)
5781: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5782:
5783: if (cens[i] == 0 && wav[i]>1)
5784: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5785: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5786:
5787: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5788: if (wav[i] > 1 ) { /* ??? */
5789: L=L+A*weight[i];
5790: /* 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]);*/
5791: }
5792: }
5793:
5794: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5795:
5796: return -2*L*num/sump;
5797: }
5798:
5799: #ifdef GSL
5800: /******************* Gompertz_f Likelihood ******************************/
5801: double gompertz_f(const gsl_vector *v, void *params)
5802: {
5803: double A,B,LL=0.0,sump=0.,num=0.;
5804: double *x= (double *) v->data;
5805: int i,n=0; /* n is the size of the sample */
5806:
5807: for (i=0;i<=imx-1 ; i++) {
5808: sump=sump+weight[i];
5809: /* sump=sump+1;*/
5810: num=num+1;
5811: }
5812:
5813:
5814: /* for (i=0; i<=imx; i++)
5815: 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]);*/
5816: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5817: for (i=1;i<=imx ; i++)
5818: {
5819: if (cens[i] == 1 && wav[i]>1)
5820: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5821:
5822: if (cens[i] == 0 && wav[i]>1)
5823: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5824: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5825:
5826: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5827: if (wav[i] > 1 ) { /* ??? */
5828: LL=LL+A*weight[i];
5829: /* 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]);*/
5830: }
5831: }
5832:
5833: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5834: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5835:
5836: return -2*LL*num/sump;
5837: }
5838: #endif
5839:
5840: /******************* Printing html file ***********/
5841: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
5842: int lastpass, int stepm, int weightopt, char model[],\
5843: int imx, double p[],double **matcov,double agemortsup){
5844: int i,k;
5845:
5846: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5847: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5848: for (i=1;i<=2;i++)
5849: 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]));
5850: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
5851: fprintf(fichtm,"</ul>");
5852:
5853: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5854:
5855: 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>");
5856:
5857: for (k=agegomp;k<(agemortsup-2);k++)
5858: 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]);
5859:
5860:
5861: fflush(fichtm);
5862: }
5863:
5864: /******************* Gnuplot file **************/
5865: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5866:
5867: char dirfileres[132],optfileres[132];
5868:
5869: int ng;
5870:
5871:
5872: /*#ifdef windows */
5873: fprintf(ficgp,"cd \"%s\" \n",pathc);
5874: /*#endif */
5875:
5876:
5877: strcpy(dirfileres,optionfilefiname);
5878: strcpy(optfileres,"vpl");
5879: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
5880: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5881: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
5882: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5883: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5884:
5885: }
5886:
5887: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5888: {
5889:
5890: /*-------- data file ----------*/
5891: FILE *fic;
5892: char dummy[]=" ";
5893: int i=0, j=0, n=0;
5894: int linei, month, year,iout;
5895: char line[MAXLINE], linetmp[MAXLINE];
5896: char stra[MAXLINE], strb[MAXLINE];
5897: char *stratrunc;
5898: int lstra;
5899:
5900:
5901: if((fic=fopen(datafile,"r"))==NULL) {
5902: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5903: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
5904: }
5905:
5906: i=1;
5907: linei=0;
5908: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5909: linei=linei+1;
5910: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5911: if(line[j] == '\t')
5912: line[j] = ' ';
5913: }
5914: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5915: ;
5916: };
5917: line[j+1]=0; /* Trims blanks at end of line */
5918: if(line[0]=='#'){
5919: fprintf(ficlog,"Comment line\n%s\n",line);
5920: printf("Comment line\n%s\n",line);
5921: continue;
5922: }
5923: trimbb(linetmp,line); /* Trims multiple blanks in line */
5924: strcpy(line, linetmp);
5925:
5926:
5927: for (j=maxwav;j>=1;j--){
5928: cutv(stra, strb, line, ' ');
5929: if(strb[0]=='.') { /* Missing status */
5930: lval=-1;
5931: }else{
5932: errno=0;
5933: lval=strtol(strb,&endptr,10);
5934: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5935: if( strb[0]=='\0' || (*endptr != '\0')){
5936: 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);
5937: 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);
5938: return 1;
5939: }
5940: }
5941: s[j][i]=lval;
5942:
5943: strcpy(line,stra);
5944: cutv(stra, strb,line,' ');
5945: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5946: }
5947: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5948: month=99;
5949: year=9999;
5950: }else{
5951: 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);
5952: 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);
5953: return 1;
5954: }
5955: anint[j][i]= (double) year;
5956: mint[j][i]= (double)month;
5957: strcpy(line,stra);
5958: } /* ENd Waves */
5959:
5960: cutv(stra, strb,line,' ');
5961: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5962: }
5963: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5964: month=99;
5965: year=9999;
5966: }else{
5967: 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);
5968: 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);
5969: return 1;
5970: }
5971: andc[i]=(double) year;
5972: moisdc[i]=(double) month;
5973: strcpy(line,stra);
5974:
5975: cutv(stra, strb,line,' ');
5976: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5977: }
5978: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5979: month=99;
5980: year=9999;
5981: }else{
5982: 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);
5983: 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);
5984: return 1;
5985: }
5986: if (year==9999) {
5987: 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);
5988: 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);
5989: return 1;
5990:
5991: }
5992: annais[i]=(double)(year);
5993: moisnais[i]=(double)(month);
5994: strcpy(line,stra);
5995:
5996: cutv(stra, strb,line,' ');
5997: errno=0;
5998: dval=strtod(strb,&endptr);
5999: if( strb[0]=='\0' || (*endptr != '\0')){
6000: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6001: 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);
6002: fflush(ficlog);
6003: return 1;
6004: }
6005: weight[i]=dval;
6006: strcpy(line,stra);
6007:
6008: for (j=ncovcol;j>=1;j--){
6009: cutv(stra, strb,line,' ');
6010: if(strb[0]=='.') { /* Missing status */
6011: lval=-1;
6012: }else{
6013: errno=0;
6014: lval=strtol(strb,&endptr,10);
6015: if( strb[0]=='\0' || (*endptr != '\0')){
6016: 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);
6017: 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);
6018: return 1;
6019: }
6020: }
6021: if(lval <-1 || lval >1){
6022: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6023: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6024: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6025: For example, for multinomial values like 1, 2 and 3,\n \
6026: build V1=0 V2=0 for the reference value (1),\n \
6027: V1=1 V2=0 for (2) \n \
6028: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6029: output of IMaCh is often meaningless.\n \
6030: Exiting.\n",lval,linei, i,line,j);
6031: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6032: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6033: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6034: For example, for multinomial values like 1, 2 and 3,\n \
6035: build V1=0 V2=0 for the reference value (1),\n \
6036: V1=1 V2=0 for (2) \n \
6037: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6038: output of IMaCh is often meaningless.\n \
6039: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6040: return 1;
6041: }
6042: covar[j][i]=(double)(lval);
6043: strcpy(line,stra);
6044: }
6045: lstra=strlen(stra);
6046:
6047: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6048: stratrunc = &(stra[lstra-9]);
6049: num[i]=atol(stratrunc);
6050: }
6051: else
6052: num[i]=atol(stra);
6053: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6054: 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;}*/
6055:
6056: i=i+1;
6057: } /* End loop reading data */
6058:
6059: *imax=i-1; /* Number of individuals */
6060: fclose(fic);
6061:
6062: return (0);
6063: /* endread: */
6064: printf("Exiting readdata: ");
6065: fclose(fic);
6066: return (1);
6067:
6068:
6069:
6070: }
6071: void removespace(char *str) {
6072: char *p1 = str, *p2 = str;
6073: do
6074: while (*p2 == ' ')
6075: p2++;
6076: while (*p1++ == *p2++);
6077: }
6078:
6079: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
6080: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6081: * - nagesqr = 1 if age*age in the model, otherwise 0.
6082: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6083: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6084: * - cptcovage number of covariates with age*products =2
6085: * - cptcovs number of simple covariates
6086: * - 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
6087: * which is a new column after the 9 (ncovcol) variables.
6088: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6089: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6090: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6091: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6092: */
6093: {
6094: int i, j, k, ks;
6095: int j1, k1, k2;
6096: char modelsav[80];
6097: char stra[80], strb[80], strc[80], strd[80],stre[80];
6098: char *strpt;
6099:
6100: /*removespace(model);*/
6101: if (strlen(model) >1){ /* If there is at least 1 covariate */
6102: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6103: if (strstr(model,"AGE") !=0){
6104: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6105: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6106: return 1;
6107: }
6108: if (strstr(model,"v") !=0){
6109: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6110: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6111: return 1;
6112: }
6113: strcpy(modelsav,model);
6114: if ((strpt=strstr(model,"age*age")) !=0){
6115: printf(" strpt=%s, model=%s\n",strpt, model);
6116: if(strpt != model){
6117: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6118: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6119: corresponding column of parameters.\n",model);
6120: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6121: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6122: corresponding column of parameters.\n",model); fflush(ficlog);
6123: return 1;
6124: }
6125:
6126: nagesqr=1;
6127: if (strstr(model,"+age*age") !=0)
6128: substrchaine(modelsav, model, "+age*age");
6129: else if (strstr(model,"age*age+") !=0)
6130: substrchaine(modelsav, model, "age*age+");
6131: else
6132: substrchaine(modelsav, model, "age*age");
6133: }else
6134: nagesqr=0;
6135: if (strlen(modelsav) >1){
6136: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6137: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6138: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6139: cptcovt= j+1; /* Number of total covariates in the model, not including
6140: * cst, age and age*age
6141: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6142: /* including age products which are counted in cptcovage.
6143: * but the covariates which are products must be treated
6144: * separately: ncovn=4- 2=2 (V1+V3). */
6145: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6146: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6147:
6148:
6149: /* Design
6150: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6151: * < ncovcol=8 >
6152: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6153: * k= 1 2 3 4 5 6 7 8
6154: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6155: * covar[k,i], value of kth covariate if not including age for individual i:
6156: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6157: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6158: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6159: * Tage[++cptcovage]=k
6160: * if products, new covar are created after ncovcol with k1
6161: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6162: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6163: * 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
6164: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6165: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6166: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6167: * < ncovcol=8 >
6168: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6169: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6170: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6171: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6172: * p Tprod[1]@2={ 6, 5}
6173: *p Tvard[1][1]@4= {7, 8, 5, 6}
6174: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6175: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6176: *How to reorganize?
6177: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6178: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6179: * {2, 1, 4, 8, 5, 6, 3, 7}
6180: * Struct []
6181: */
6182:
6183: /* This loop fills the array Tvar from the string 'model'.*/
6184: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6185: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6186: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6187: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6188: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6189: /* k=1 Tvar[1]=2 (from V2) */
6190: /* k=5 Tvar[5] */
6191: /* for (k=1; k<=cptcovn;k++) { */
6192: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6193: /* } */
6194: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6195: /*
6196: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6197: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6198: Tvar[k]=0;
6199: cptcovage=0;
6200: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6201: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6202: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6203: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6204: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6205: /*scanf("%d",i);*/
6206: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6207: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6208: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6209: /* covar is not filled and then is empty */
6210: cptcovprod--;
6211: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6212: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6213: cptcovage++; /* Sums the number of covariates which include age as a product */
6214: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6215: /*printf("stre=%s ", stre);*/
6216: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6217: cptcovprod--;
6218: cutl(stre,strb,strc,'V');
6219: Tvar[k]=atoi(stre);
6220: cptcovage++;
6221: Tage[cptcovage]=k;
6222: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6223: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6224: cptcovn++;
6225: cptcovprodnoage++;k1++;
6226: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6227: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6228: because this model-covariate is a construction we invent a new column
6229: ncovcol + k1
6230: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6231: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6232: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6233: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6234: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6235: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6236: k2=k2+2;
6237: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6238: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6239: for (i=1; i<=lastobs;i++){
6240: /* Computes the new covariate which is a product of
6241: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6242: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6243: }
6244: } /* End age is not in the model */
6245: } /* End if model includes a product */
6246: else { /* no more sum */
6247: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6248: /* scanf("%d",i);*/
6249: cutl(strd,strc,strb,'V');
6250: ks++; /**< Number of simple covariates */
6251: cptcovn++;
6252: Tvar[k]=atoi(strd);
6253: }
6254: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6255: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6256: scanf("%d",i);*/
6257: } /* end of loop + on total covariates */
6258: } /* end if strlen(modelsave == 0) age*age might exist */
6259: } /* end if strlen(model == 0) */
6260:
6261: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6262: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6263:
6264: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6265: printf("cptcovprod=%d ", cptcovprod);
6266: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6267:
6268: scanf("%d ",i);*/
6269:
6270:
6271: return (0); /* with covar[new additional covariate if product] and Tage if age */
6272: /*endread:*/
6273: printf("Exiting decodemodel: ");
6274: return (1);
6275: }
6276:
6277: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6278: {
6279: int i, m;
6280:
6281: for (i=1; i<=imx; i++) {
6282: for(m=2; (m<= maxwav); m++) {
6283: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6284: anint[m][i]=9999;
6285: s[m][i]=-1;
6286: }
6287: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6288: *nberr = *nberr + 1;
6289: 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);
6290: 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);
6291: s[m][i]=-1;
6292: }
6293: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6294: (*nberr)++;
6295: 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]);
6296: 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]);
6297: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6298: }
6299: }
6300: }
6301:
6302: for (i=1; i<=imx; i++) {
6303: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6304: for(m=firstpass; (m<= lastpass); m++){
6305: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6306: if (s[m][i] >= nlstate+1) {
6307: if(agedc[i]>0){
6308: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6309: agev[m][i]=agedc[i];
6310: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6311: }else {
6312: if ((int)andc[i]!=9999){
6313: nbwarn++;
6314: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6315: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6316: agev[m][i]=-1;
6317: }
6318: }
6319: } /* agedc > 0 */
6320: }
6321: else if(s[m][i] !=9){ /* Standard case, age in fractional
6322: years but with the precision of a month */
6323: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6324: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6325: agev[m][i]=1;
6326: else if(agev[m][i] < *agemin){
6327: *agemin=agev[m][i];
6328: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6329: }
6330: else if(agev[m][i] >*agemax){
6331: *agemax=agev[m][i];
6332: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6333: }
6334: /*agev[m][i]=anint[m][i]-annais[i];*/
6335: /* agev[m][i] = age[i]+2*m;*/
6336: }
6337: else { /* =9 */
6338: agev[m][i]=1;
6339: s[m][i]=-1;
6340: }
6341: }
6342: else /*= 0 Unknown */
6343: agev[m][i]=1;
6344: }
6345:
6346: }
6347: for (i=1; i<=imx; i++) {
6348: for(m=firstpass; (m<=lastpass); m++){
6349: if (s[m][i] > (nlstate+ndeath)) {
6350: (*nberr)++;
6351: 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);
6352: 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);
6353: return 1;
6354: }
6355: }
6356: }
6357:
6358: /*for (i=1; i<=imx; i++){
6359: for (m=firstpass; (m<lastpass); m++){
6360: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6361: }
6362:
6363: }*/
6364:
6365:
6366: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6367: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6368:
6369: return (0);
6370: /* endread:*/
6371: printf("Exiting calandcheckages: ");
6372: return (1);
6373: }
6374:
6375: #if defined(_MSC_VER)
6376: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6377: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6378: //#include "stdafx.h"
6379: //#include <stdio.h>
6380: //#include <tchar.h>
6381: //#include <windows.h>
6382: //#include <iostream>
6383: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6384:
6385: LPFN_ISWOW64PROCESS fnIsWow64Process;
6386:
6387: BOOL IsWow64()
6388: {
6389: BOOL bIsWow64 = FALSE;
6390:
6391: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6392: // (HANDLE, PBOOL);
6393:
6394: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6395:
6396: HMODULE module = GetModuleHandle(_T("kernel32"));
6397: const char funcName[] = "IsWow64Process";
6398: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6399: GetProcAddress(module, funcName);
6400:
6401: if (NULL != fnIsWow64Process)
6402: {
6403: if (!fnIsWow64Process(GetCurrentProcess(),
6404: &bIsWow64))
6405: //throw std::exception("Unknown error");
6406: printf("Unknown error\n");
6407: }
6408: return bIsWow64 != FALSE;
6409: }
6410: #endif
6411:
6412: void syscompilerinfo(int logged)
6413: {
6414: /* #include "syscompilerinfo.h"*/
6415: /* command line Intel compiler 32bit windows, XP compatible:*/
6416: /* /GS /W3 /Gy
6417: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6418: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6419: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6420: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6421: */
6422: /* 64 bits */
6423: /*
6424: /GS /W3 /Gy
6425: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6426: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6427: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6428: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6429: /* Optimization are useless and O3 is slower than O2 */
6430: /*
6431: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6432: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6433: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6434: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6435: */
6436: /* Link is */ /* /OUT:"visual studio
6437: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6438: /PDB:"visual studio
6439: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6440: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6441: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6442: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6443: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6444: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6445: uiAccess='false'"
6446: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6447: /NOLOGO /TLBID:1
6448: */
6449: #if defined __INTEL_COMPILER
6450: #if defined(__GNUC__)
6451: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6452: #endif
6453: #elif defined(__GNUC__)
6454: #ifndef __APPLE__
6455: #include <gnu/libc-version.h> /* Only on gnu */
6456: #endif
6457: struct utsname sysInfo;
6458: int cross = CROSS;
6459: if (cross){
6460: printf("Cross-");
6461: if(logged) fprintf(ficlog, "Cross-");
6462: }
6463: #endif
6464:
6465: #include <stdint.h>
6466:
6467: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6468: #if defined(__clang__)
6469: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6470: #endif
6471: #if defined(__ICC) || defined(__INTEL_COMPILER)
6472: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6473: #endif
6474: #if defined(__GNUC__) || defined(__GNUG__)
6475: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6476: #endif
6477: #if defined(__HP_cc) || defined(__HP_aCC)
6478: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6479: #endif
6480: #if defined(__IBMC__) || defined(__IBMCPP__)
6481: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6482: #endif
6483: #if defined(_MSC_VER)
6484: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6485: #endif
6486: #if defined(__PGI)
6487: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6488: #endif
6489: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6490: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6491: #endif
6492: printf(" for "); if (logged) fprintf(ficlog, " for ");
6493:
6494: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6495: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6496: // Windows (x64 and x86)
6497: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6498: #elif __unix__ // all unices, not all compilers
6499: // Unix
6500: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6501: #elif __linux__
6502: // linux
6503: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6504: #elif __APPLE__
6505: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6506: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6507: #endif
6508:
6509: /* __MINGW32__ */
6510: /* __CYGWIN__ */
6511: /* __MINGW64__ */
6512: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6513: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6514: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6515: /* _WIN64 // Defined for applications for Win64. */
6516: /* _M_X64 // Defined for compilations that target x64 processors. */
6517: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6518:
6519: #if UINTPTR_MAX == 0xffffffff
6520: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6521: #elif UINTPTR_MAX == 0xffffffffffffffff
6522: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6523: #else
6524: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6525: #endif
6526:
6527: #if defined(__GNUC__)
6528: # if defined(__GNUC_PATCHLEVEL__)
6529: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6530: + __GNUC_MINOR__ * 100 \
6531: + __GNUC_PATCHLEVEL__)
6532: # else
6533: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6534: + __GNUC_MINOR__ * 100)
6535: # endif
6536: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6537: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6538:
6539: if (uname(&sysInfo) != -1) {
6540: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6541: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6542: }
6543: else
6544: perror("uname() error");
6545: //#ifndef __INTEL_COMPILER
6546: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6547: printf("GNU libc version: %s\n", gnu_get_libc_version());
6548: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6549: #endif
6550: #endif
6551:
6552: // void main()
6553: // {
6554: #if defined(_MSC_VER)
6555: if (IsWow64()){
6556: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6557: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6558: }
6559: else{
6560: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6561: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6562: }
6563: // printf("\nPress Enter to continue...");
6564: // getchar();
6565: // }
6566:
6567: #endif
6568:
6569:
6570: }
6571:
6572: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
6573: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6574: int i, j, k, i1 ;
6575: /* double ftolpl = 1.e-10; */
6576: double age, agebase, agelim;
6577: double tot;
6578:
6579: strcpy(filerespl,"PL_");
6580: strcat(filerespl,fileresu);
6581: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6582: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6583: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6584: }
6585: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6586: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6587: pstamp(ficrespl);
6588: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6589: fprintf(ficrespl,"#Age ");
6590: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6591: fprintf(ficrespl,"\n");
6592:
6593: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6594:
6595: agebase=ageminpar;
6596: agelim=agemaxpar;
6597:
6598: i1=pow(2,cptcoveff);
6599: if (cptcovn < 1){i1=1;}
6600:
6601: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6602: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6603: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6604: k=k+1;
6605: /* to clean */
6606: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6607: fprintf(ficrespl,"#******");
6608: printf("#******");
6609: fprintf(ficlog,"#******");
6610: for(j=1;j<=cptcoveff;j++) {
6611: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6612: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6613: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6614: }
6615: fprintf(ficrespl,"******\n");
6616: printf("******\n");
6617: fprintf(ficlog,"******\n");
6618:
6619: fprintf(ficrespl,"#Age ");
6620: for(j=1;j<=cptcoveff;j++) {
6621: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6622: }
6623: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6624: fprintf(ficrespl,"Total Years_to_converge\n");
6625:
6626: for (age=agebase; age<=agelim; age++){
6627: /* for (age=agebase; age<=agebase; age++){ */
6628: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
6629: fprintf(ficrespl,"%.0f ",age );
6630: for(j=1;j<=cptcoveff;j++)
6631: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6632: tot=0.;
6633: for(i=1; i<=nlstate;i++){
6634: tot += prlim[i][i];
6635: fprintf(ficrespl," %.5f", prlim[i][i]);
6636: }
6637: fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
6638: } /* Age */
6639: /* was end of cptcod */
6640: } /* cptcov */
6641: return 0;
6642: }
6643:
6644: int hPijx(double *p, int bage, int fage){
6645: /*------------- h Pij x at various ages ------------*/
6646:
6647: int stepsize;
6648: int agelim;
6649: int hstepm;
6650: int nhstepm;
6651: int h, i, i1, j, k;
6652:
6653: double agedeb;
6654: double ***p3mat;
6655:
6656: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
6657: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6658: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6659: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6660: }
6661: printf("Computing pij: result on file '%s' \n", filerespij);
6662: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6663:
6664: stepsize=(int) (stepm+YEARM-1)/YEARM;
6665: /*if (stepm<=24) stepsize=2;*/
6666:
6667: agelim=AGESUP;
6668: hstepm=stepsize*YEARM; /* Every year of age */
6669: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6670:
6671: /* hstepm=1; aff par mois*/
6672: pstamp(ficrespij);
6673: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6674: i1= pow(2,cptcoveff);
6675: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6676: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6677: /* k=k+1; */
6678: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6679: fprintf(ficrespij,"\n#****** ");
6680: for(j=1;j<=cptcoveff;j++)
6681: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6682: fprintf(ficrespij,"******\n");
6683:
6684: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6685: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6686: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6687:
6688: /* nhstepm=nhstepm*YEARM; aff par mois*/
6689:
6690: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6691: oldm=oldms;savm=savms;
6692: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6693: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6694: for(i=1; i<=nlstate;i++)
6695: for(j=1; j<=nlstate+ndeath;j++)
6696: fprintf(ficrespij," %1d-%1d",i,j);
6697: fprintf(ficrespij,"\n");
6698: for (h=0; h<=nhstepm; h++){
6699: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6700: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
6701: for(i=1; i<=nlstate;i++)
6702: for(j=1; j<=nlstate+ndeath;j++)
6703: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
6704: fprintf(ficrespij,"\n");
6705: }
6706: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6707: fprintf(ficrespij,"\n");
6708: }
6709: /*}*/
6710: }
6711: return 0;
6712: }
6713:
6714:
6715: /***********************************************/
6716: /**************** Main Program *****************/
6717: /***********************************************/
6718:
6719: int main(int argc, char *argv[])
6720: {
6721: #ifdef GSL
6722: const gsl_multimin_fminimizer_type *T;
6723: size_t iteri = 0, it;
6724: int rval = GSL_CONTINUE;
6725: int status = GSL_SUCCESS;
6726: double ssval;
6727: #endif
6728: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
6729: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6730: int ncvyearnp=0;
6731: int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
6732: int jj, ll, li, lj, lk;
6733: int numlinepar=0; /* Current linenumber of parameter file */
6734: int num_filled;
6735: int itimes;
6736: int NDIM=2;
6737: int vpopbased=0;
6738:
6739: char ca[32], cb[32];
6740: /* FILE *fichtm; *//* Html File */
6741: /* FILE *ficgp;*/ /*Gnuplot File */
6742: struct stat info;
6743: double agedeb=0.;
6744:
6745: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
6746:
6747: double fret;
6748: double dum=0.; /* Dummy variable */
6749: double ***p3mat;
6750: double ***mobaverage;
6751:
6752: char line[MAXLINE];
6753: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6754:
6755: char model[MAXLINE], modeltemp[MAXLINE];
6756: char pathr[MAXLINE], pathimach[MAXLINE];
6757: char *tok, *val; /* pathtot */
6758: int firstobs=1, lastobs=10;
6759: int c, h , cpt, c2;
6760: int jl=0;
6761: int i1, j1, jk, stepsize=0;
6762: int count=0;
6763:
6764: int *tab;
6765: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6766: int mobilav=0,popforecast=0;
6767: int hstepm=0, nhstepm=0;
6768: int agemortsup;
6769: float sumlpop=0.;
6770: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6771: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6772:
6773: double bage=0, fage=110., age, agelim=0., agebase=0.;
6774: double ftolpl=FTOL;
6775: double **prlim;
6776: double ***param; /* Matrix of parameters */
6777: double *p;
6778: double **matcov; /* Matrix of covariance */
6779: double **hess; /* Hessian matrix */
6780: double ***delti3; /* Scale */
6781: double *delti; /* Scale */
6782: double ***eij, ***vareij;
6783: double **varpl; /* Variances of prevalence limits by age */
6784: double *epj, vepp;
6785:
6786: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6787: double **ximort;
6788: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
6789: int *dcwave;
6790:
6791: char z[1]="c";
6792:
6793: /*char *strt;*/
6794: char strtend[80];
6795:
6796:
6797: /* setlocale (LC_ALL, ""); */
6798: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6799: /* textdomain (PACKAGE); */
6800: /* setlocale (LC_CTYPE, ""); */
6801: /* setlocale (LC_MESSAGES, ""); */
6802:
6803: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
6804: rstart_time = time(NULL);
6805: /* (void) gettimeofday(&start_time,&tzp);*/
6806: start_time = *localtime(&rstart_time);
6807: curr_time=start_time;
6808: /*tml = *localtime(&start_time.tm_sec);*/
6809: /* strcpy(strstart,asctime(&tml)); */
6810: strcpy(strstart,asctime(&start_time));
6811:
6812: /* printf("Localtime (at start)=%s",strstart); */
6813: /* tp.tm_sec = tp.tm_sec +86400; */
6814: /* tm = *localtime(&start_time.tm_sec); */
6815: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6816: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6817: /* tmg.tm_hour=tmg.tm_hour + 1; */
6818: /* tp.tm_sec = mktime(&tmg); */
6819: /* strt=asctime(&tmg); */
6820: /* printf("Time(after) =%s",strstart); */
6821: /* (void) time (&time_value);
6822: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6823: * tm = *localtime(&time_value);
6824: * strstart=asctime(&tm);
6825: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6826: */
6827:
6828: nberr=0; /* Number of errors and warnings */
6829: nbwarn=0;
6830: #ifdef WIN32
6831: _getcwd(pathcd, size);
6832: #else
6833: getcwd(pathcd, size);
6834: #endif
6835: syscompilerinfo(0);
6836: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
6837: if(argc <=1){
6838: printf("\nEnter the parameter file name: ");
6839: if(!fgets(pathr,FILENAMELENGTH,stdin)){
6840: printf("ERROR Empty parameter file name\n");
6841: goto end;
6842: }
6843: i=strlen(pathr);
6844: if(pathr[i-1]=='\n')
6845: pathr[i-1]='\0';
6846: i=strlen(pathr);
6847: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
6848: pathr[i-1]='\0';
6849: }
6850: i=strlen(pathr);
6851: if( i==0 ){
6852: printf("ERROR Empty parameter file name\n");
6853: goto end;
6854: }
6855: for (tok = pathr; tok != NULL; ){
6856: printf("Pathr |%s|\n",pathr);
6857: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6858: printf("val= |%s| pathr=%s\n",val,pathr);
6859: strcpy (pathtot, val);
6860: if(pathr[0] == '\0') break; /* Dirty */
6861: }
6862: }
6863: else{
6864: strcpy(pathtot,argv[1]);
6865: }
6866: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6867: /*cygwin_split_path(pathtot,path,optionfile);
6868: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6869: /* cutv(path,optionfile,pathtot,'\\');*/
6870:
6871: /* Split argv[0], imach program to get pathimach */
6872: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6873: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6874: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6875: /* strcpy(pathimach,argv[0]); */
6876: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6877: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6878: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6879: #ifdef WIN32
6880: _chdir(path); /* Can be a relative path */
6881: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6882: #else
6883: chdir(path); /* Can be a relative path */
6884: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6885: #endif
6886: printf("Current directory %s!\n",pathcd);
6887: strcpy(command,"mkdir ");
6888: strcat(command,optionfilefiname);
6889: if((outcmd=system(command)) != 0){
6890: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6891: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6892: /* fclose(ficlog); */
6893: /* exit(1); */
6894: }
6895: /* if((imk=mkdir(optionfilefiname))<0){ */
6896: /* perror("mkdir"); */
6897: /* } */
6898:
6899: /*-------- arguments in the command line --------*/
6900:
6901: /* Main Log file */
6902: strcat(filelog, optionfilefiname);
6903: strcat(filelog,".log"); /* */
6904: if((ficlog=fopen(filelog,"w"))==NULL) {
6905: printf("Problem with logfile %s\n",filelog);
6906: goto end;
6907: }
6908: fprintf(ficlog,"Log filename:%s\n",filelog);
6909: fprintf(ficlog,"Version %s %s",version,fullversion);
6910: fprintf(ficlog,"\nEnter the parameter file name: \n");
6911: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6912: path=%s \n\
6913: optionfile=%s\n\
6914: optionfilext=%s\n\
6915: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6916:
6917: syscompilerinfo(1);
6918:
6919: printf("Local time (at start):%s",strstart);
6920: fprintf(ficlog,"Local time (at start): %s",strstart);
6921: fflush(ficlog);
6922: /* (void) gettimeofday(&curr_time,&tzp); */
6923: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6924:
6925: /* */
6926: strcpy(fileres,"r");
6927: strcat(fileres, optionfilefiname);
6928: strcat(fileresu, optionfilefiname); /* Without r in front */
6929: strcat(fileres,".txt"); /* Other files have txt extension */
6930: strcat(fileresu,".txt"); /* Other files have txt extension */
6931:
6932: /* Main ---------arguments file --------*/
6933:
6934: if((ficpar=fopen(optionfile,"r"))==NULL) {
6935: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6936: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6937: fflush(ficlog);
6938: /* goto end; */
6939: exit(70);
6940: }
6941:
6942:
6943:
6944: strcpy(filereso,"o");
6945: strcat(filereso,fileresu);
6946: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6947: printf("Problem with Output resultfile: %s\n", filereso);
6948: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6949: fflush(ficlog);
6950: goto end;
6951: }
6952:
6953: /* Reads comments: lines beginning with '#' */
6954: numlinepar=0;
6955:
6956: /* First parameter line */
6957: while(fgets(line, MAXLINE, ficpar)) {
6958: /* If line starts with a # it is a comment */
6959: if (line[0] == '#') {
6960: numlinepar++;
6961: fputs(line,stdout);
6962: fputs(line,ficparo);
6963: fputs(line,ficlog);
6964: continue;
6965: }else
6966: break;
6967: }
6968: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6969: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6970: if (num_filled != 5) {
6971: printf("Should be 5 parameters\n");
6972: }
6973: numlinepar++;
6974: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6975: }
6976: /* Second parameter line */
6977: while(fgets(line, MAXLINE, ficpar)) {
6978: /* If line starts with a # it is a comment */
6979: if (line[0] == '#') {
6980: numlinepar++;
6981: fputs(line,stdout);
6982: fputs(line,ficparo);
6983: fputs(line,ficlog);
6984: continue;
6985: }else
6986: break;
6987: }
6988: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6989: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
6990: if (num_filled != 8) {
6991: printf("Not 8\n");
6992: }
6993: 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);
6994: }
6995: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
6996: ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
6997: /* Third parameter line */
6998: while(fgets(line, MAXLINE, ficpar)) {
6999: /* If line starts with a # it is a comment */
7000: if (line[0] == '#') {
7001: numlinepar++;
7002: fputs(line,stdout);
7003: fputs(line,ficparo);
7004: fputs(line,ficlog);
7005: continue;
7006: }else
7007: break;
7008: }
7009: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7010: if (num_filled == 0)
7011: model[0]='\0';
7012: else if (num_filled != 1){
7013: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7014: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7015: model[0]='\0';
7016: goto end;
7017: }
7018: else{
7019: if (model[0]=='+'){
7020: for(i=1; i<=strlen(model);i++)
7021: modeltemp[i-1]=model[i];
7022: strcpy(model,modeltemp);
7023: }
7024: }
7025: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
7026: printf("model=1+age+%s\n",model);fflush(stdout);
7027: }
7028: /* 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); */
7029: /* numlinepar=numlinepar+3; /\* In general *\/ */
7030: /* 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); */
7031: 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);
7032: 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);
7033: fflush(ficlog);
7034: /* if(model[0]=='#'|| model[0]== '\0'){ */
7035: if(model[0]=='#'){
7036: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7037: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7038: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7039: if(mle != -1){
7040: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7041: exit(1);
7042: }
7043: }
7044: while((c=getc(ficpar))=='#' && c!= EOF){
7045: ungetc(c,ficpar);
7046: fgets(line, MAXLINE, ficpar);
7047: numlinepar++;
7048: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7049: z[0]=line[1];
7050: }
7051: /* printf("****line [1] = %c \n",line[1]); */
7052: fputs(line, stdout);
7053: //puts(line);
7054: fputs(line,ficparo);
7055: fputs(line,ficlog);
7056: }
7057: ungetc(c,ficpar);
7058:
7059:
7060: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
7061: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7062: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7063: v1+v2*age+v2*v3 makes cptcovn = 3
7064: */
7065: if (strlen(model)>1)
7066: 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*/
7067: else
7068: ncovmodel=2; /* Constant and age */
7069: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7070: npar= nforce*ncovmodel; /* Number of parameters like aij*/
7071: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7072: 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);
7073: 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);
7074: fflush(stdout);
7075: fclose (ficlog);
7076: goto end;
7077: }
7078: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7079: delti=delti3[1][1];
7080: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7081: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7082: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7083: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7084: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7085: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7086: fclose (ficparo);
7087: fclose (ficlog);
7088: goto end;
7089: exit(0);
7090: }
7091: else if(mle==-3) { /* Main Wizard */
7092: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7093: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7094: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7095: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7096: matcov=matrix(1,npar,1,npar);
7097: hess=matrix(1,npar,1,npar);
7098: }
7099: else{
7100: /* Read guessed parameters */
7101: /* Reads comments: lines beginning with '#' */
7102: while((c=getc(ficpar))=='#' && c!= EOF){
7103: ungetc(c,ficpar);
7104: fgets(line, MAXLINE, ficpar);
7105: numlinepar++;
7106: fputs(line,stdout);
7107: fputs(line,ficparo);
7108: fputs(line,ficlog);
7109: }
7110: ungetc(c,ficpar);
7111:
7112: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7113: for(i=1; i <=nlstate; i++){
7114: j=0;
7115: for(jj=1; jj <=nlstate+ndeath; jj++){
7116: if(jj==i) continue;
7117: j++;
7118: fscanf(ficpar,"%1d%1d",&i1,&j1);
7119: if ((i1 != i) || (j1 != jj)){
7120: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7121: It might be a problem of design; if ncovcol and the model are correct\n \
7122: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7123: exit(1);
7124: }
7125: fprintf(ficparo,"%1d%1d",i1,j1);
7126: if(mle==1)
7127: printf("%1d%1d",i,jj);
7128: fprintf(ficlog,"%1d%1d",i,jj);
7129: for(k=1; k<=ncovmodel;k++){
7130: fscanf(ficpar," %lf",¶m[i][j][k]);
7131: if(mle==1){
7132: printf(" %lf",param[i][j][k]);
7133: fprintf(ficlog," %lf",param[i][j][k]);
7134: }
7135: else
7136: fprintf(ficlog," %lf",param[i][j][k]);
7137: fprintf(ficparo," %lf",param[i][j][k]);
7138: }
7139: fscanf(ficpar,"\n");
7140: numlinepar++;
7141: if(mle==1)
7142: printf("\n");
7143: fprintf(ficlog,"\n");
7144: fprintf(ficparo,"\n");
7145: }
7146: }
7147: fflush(ficlog);
7148:
7149: /* Reads scales values */
7150: p=param[1][1];
7151:
7152: /* Reads comments: lines beginning with '#' */
7153: while((c=getc(ficpar))=='#' && c!= EOF){
7154: ungetc(c,ficpar);
7155: fgets(line, MAXLINE, ficpar);
7156: numlinepar++;
7157: fputs(line,stdout);
7158: fputs(line,ficparo);
7159: fputs(line,ficlog);
7160: }
7161: ungetc(c,ficpar);
7162:
7163: for(i=1; i <=nlstate; i++){
7164: for(j=1; j <=nlstate+ndeath-1; j++){
7165: fscanf(ficpar,"%1d%1d",&i1,&j1);
7166: if ( (i1-i) * (j1-j) != 0){
7167: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7168: exit(1);
7169: }
7170: printf("%1d%1d",i,j);
7171: fprintf(ficparo,"%1d%1d",i1,j1);
7172: fprintf(ficlog,"%1d%1d",i1,j1);
7173: for(k=1; k<=ncovmodel;k++){
7174: fscanf(ficpar,"%le",&delti3[i][j][k]);
7175: printf(" %le",delti3[i][j][k]);
7176: fprintf(ficparo," %le",delti3[i][j][k]);
7177: fprintf(ficlog," %le",delti3[i][j][k]);
7178: }
7179: fscanf(ficpar,"\n");
7180: numlinepar++;
7181: printf("\n");
7182: fprintf(ficparo,"\n");
7183: fprintf(ficlog,"\n");
7184: }
7185: }
7186: fflush(ficlog);
7187:
7188: /* Reads covariance matrix */
7189: delti=delti3[1][1];
7190:
7191:
7192: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7193:
7194: /* Reads comments: lines beginning with '#' */
7195: while((c=getc(ficpar))=='#' && c!= EOF){
7196: ungetc(c,ficpar);
7197: fgets(line, MAXLINE, ficpar);
7198: numlinepar++;
7199: fputs(line,stdout);
7200: fputs(line,ficparo);
7201: fputs(line,ficlog);
7202: }
7203: ungetc(c,ficpar);
7204:
7205: matcov=matrix(1,npar,1,npar);
7206: hess=matrix(1,npar,1,npar);
7207: for(i=1; i <=npar; i++)
7208: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7209:
7210: /* Scans npar lines */
7211: for(i=1; i <=npar; i++){
7212: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7213: if(count != 3){
7214: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7215: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7216: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7217: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7218: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7219: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7220: exit(1);
7221: }else
7222: if(mle==1)
7223: printf("%1d%1d%1d",i1,j1,jk);
7224: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7225: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7226: for(j=1; j <=i; j++){
7227: fscanf(ficpar," %le",&matcov[i][j]);
7228: if(mle==1){
7229: printf(" %.5le",matcov[i][j]);
7230: }
7231: fprintf(ficlog," %.5le",matcov[i][j]);
7232: fprintf(ficparo," %.5le",matcov[i][j]);
7233: }
7234: fscanf(ficpar,"\n");
7235: numlinepar++;
7236: if(mle==1)
7237: printf("\n");
7238: fprintf(ficlog,"\n");
7239: fprintf(ficparo,"\n");
7240: }
7241: /* End of read covariance matrix npar lines */
7242: for(i=1; i <=npar; i++)
7243: for(j=i+1;j<=npar;j++)
7244: matcov[i][j]=matcov[j][i];
7245:
7246: if(mle==1)
7247: printf("\n");
7248: fprintf(ficlog,"\n");
7249:
7250: fflush(ficlog);
7251:
7252: /*-------- Rewriting parameter file ----------*/
7253: strcpy(rfileres,"r"); /* "Rparameterfile */
7254: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7255: strcat(rfileres,"."); /* */
7256: strcat(rfileres,optionfilext); /* Other files have txt extension */
7257: if((ficres =fopen(rfileres,"w"))==NULL) {
7258: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7259: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7260: }
7261: fprintf(ficres,"#%s\n",version);
7262: } /* End of mle != -3 */
7263:
7264: /* Main data
7265: */
7266: n= lastobs;
7267: num=lvector(1,n);
7268: moisnais=vector(1,n);
7269: annais=vector(1,n);
7270: moisdc=vector(1,n);
7271: andc=vector(1,n);
7272: agedc=vector(1,n);
7273: cod=ivector(1,n);
7274: weight=vector(1,n);
7275: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7276: mint=matrix(1,maxwav,1,n);
7277: anint=matrix(1,maxwav,1,n);
7278: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7279: tab=ivector(1,NCOVMAX);
7280: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7281: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7282:
7283: /* Reads data from file datafile */
7284: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7285: goto end;
7286:
7287: /* Calculation of the number of parameters from char model */
7288: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7289: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7290: k=3 V4 Tvar[k=3]= 4 (from V4)
7291: k=2 V1 Tvar[k=2]= 1 (from V1)
7292: k=1 Tvar[1]=2 (from V2)
7293: */
7294: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7295: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7296: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7297: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7298: */
7299: /* For model-covariate k tells which data-covariate to use but
7300: because this model-covariate is a construction we invent a new column
7301: ncovcol + k1
7302: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7303: Tvar[3=V1*V4]=4+1 etc */
7304: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7305: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7306: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7307: */
7308: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7309: 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
7310: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7311: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7312: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7313: 4 covariates (3 plus signs)
7314: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7315: */
7316:
7317: /* Main decodemodel */
7318:
7319:
7320: if(decodemodel(model, lastobs) == 1)
7321: goto end;
7322:
7323: if((double)(lastobs-imx)/(double)imx > 1.10){
7324: nbwarn++;
7325: 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);
7326: 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);
7327: }
7328: /* if(mle==1){*/
7329: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7330: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7331: }
7332:
7333: /*-calculation of age at interview from date of interview and age at death -*/
7334: agev=matrix(1,maxwav,1,imx);
7335:
7336: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7337: goto end;
7338:
7339:
7340: agegomp=(int)agemin;
7341: free_vector(moisnais,1,n);
7342: free_vector(annais,1,n);
7343: /* free_matrix(mint,1,maxwav,1,n);
7344: free_matrix(anint,1,maxwav,1,n);*/
7345: free_vector(moisdc,1,n);
7346: free_vector(andc,1,n);
7347: /* */
7348:
7349: wav=ivector(1,imx);
7350: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7351: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7352: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7353:
7354: /* Concatenates waves */
7355: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7356: /* */
7357:
7358: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7359:
7360: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7361: ncodemax[1]=1;
7362: Ndum =ivector(-1,NCOVMAX);
7363: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7364: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7365: /* Nbcode gives the value of the lth modality of jth covariate, in
7366: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7367: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
7368:
7369: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7370: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7371: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7372: h=0;
7373:
7374:
7375: /*if (cptcovn > 0) */
7376:
7377:
7378: m=pow(2,cptcoveff);
7379:
7380: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7381: * For k=4 covariates, h goes from 1 to 2**k
7382: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
7383: * h\k 1 2 3 4
7384: *______________________________
7385: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7386: * 2 2 1 1 1
7387: * 3 i=2 1 2 1 1
7388: * 4 2 2 1 1
7389: * 5 i=3 1 i=2 1 2 1
7390: * 6 2 1 2 1
7391: * 7 i=4 1 2 2 1
7392: * 8 2 2 2 1
7393: * 9 i=5 1 i=3 1 i=2 1 2
7394: * 10 2 1 1 2
7395: * 11 i=6 1 2 1 2
7396: * 12 2 2 1 2
7397: * 13 i=7 1 i=4 1 2 2
7398: * 14 2 1 2 2
7399: * 15 i=8 1 2 2 2
7400: * 16 2 2 2 2
7401: */
7402: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7403: /* /\* printf("h=%2d ", h); *\/ */
7404: /* /\* for(k=1; k <=10; k++){ *\/ */
7405: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7406: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7407: /* /\* } *\/ */
7408: /* /\* printf("\n"); *\/ */
7409: /* } */
7410: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7411: /* 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 *\/ */
7412: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7413: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7414: /* h++; */
7415: /* if (h>m) */
7416: /* h=1; */
7417: /* codtab[h][k]=j; */
7418: /* /\* codtab[12][3]=1; *\/ */
7419: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7420: /* /\* 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]]); *\/ */
7421: /* } */
7422: /* } */
7423: /* } */
7424: /* } */
7425: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7426: codtab[1][2]=1;codtab[2][2]=2; */
7427: /* for(i=1; i <=m ;i++){ */
7428: /* for(k=1; k <=cptcovn; k++){ */
7429: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7430: /* } */
7431: /* printf("\n"); */
7432: /* } */
7433: /* scanf("%d",i);*/
7434:
7435: free_ivector(Ndum,-1,NCOVMAX);
7436:
7437:
7438:
7439: /* Initialisation of ----------- gnuplot -------------*/
7440: strcpy(optionfilegnuplot,optionfilefiname);
7441: if(mle==-3)
7442: strcat(optionfilegnuplot,"-MORT_");
7443: strcat(optionfilegnuplot,".gp");
7444:
7445: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7446: printf("Problem with file %s",optionfilegnuplot);
7447: }
7448: else{
7449: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7450: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7451: //fprintf(ficgp,"set missing 'NaNq'\n");
7452: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7453: }
7454: /* fclose(ficgp);*/
7455:
7456:
7457: /* Initialisation of --------- index.htm --------*/
7458:
7459: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7460: if(mle==-3)
7461: strcat(optionfilehtm,"-MORT_");
7462: strcat(optionfilehtm,".htm");
7463: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7464: printf("Problem with %s \n",optionfilehtm);
7465: exit(0);
7466: }
7467:
7468: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7469: strcat(optionfilehtmcov,"-cov.htm");
7470: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7471: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7472: }
7473: else{
7474: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7475: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7476: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7477: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7478: }
7479:
7480: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br> \
7481: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7482: <font size=\"2\">IMaCh-%s <br> %s</font> \
7483: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7484: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7485: \n\
7486: <hr size=\"2\" color=\"#EC5E5E\">\
7487: <ul><li><h4>Parameter files</h4>\n\
7488: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7489: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7490: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7491: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7492: - Date and time at start: %s</ul>\n",\
7493: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7494: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7495: fileres,fileres,\
7496: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7497: fflush(fichtm);
7498:
7499: strcpy(pathr,path);
7500: strcat(pathr,optionfilefiname);
7501: #ifdef WIN32
7502: _chdir(optionfilefiname); /* Move to directory named optionfile */
7503: #else
7504: chdir(optionfilefiname); /* Move to directory named optionfile */
7505: #endif
7506:
7507:
7508: /* Calculates basic frequencies. Computes observed prevalence at single age
7509: and prints on file fileres'p'. */
7510: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7511:
7512: fprintf(fichtm,"\n");
7513: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7514: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7515: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7516: imx,agemin,agemax,jmin,jmax,jmean);
7517: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7518: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7519: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7520: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7521: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7522:
7523:
7524: /* For Powell, parameters are in a vector p[] starting at p[1]
7525: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7526: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7527:
7528: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7529: /* For mortality only */
7530: if (mle==-3){
7531: ximort=matrix(1,NDIM,1,NDIM);
7532: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7533: cens=ivector(1,n);
7534: ageexmed=vector(1,n);
7535: agecens=vector(1,n);
7536: dcwave=ivector(1,n);
7537:
7538: for (i=1; i<=imx; i++){
7539: dcwave[i]=-1;
7540: for (m=firstpass; m<=lastpass; m++)
7541: if (s[m][i]>nlstate) {
7542: dcwave[i]=m;
7543: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7544: break;
7545: }
7546: }
7547:
7548: for (i=1; i<=imx; i++) {
7549: if (wav[i]>0){
7550: ageexmed[i]=agev[mw[1][i]][i];
7551: j=wav[i];
7552: agecens[i]=1.;
7553:
7554: if (ageexmed[i]> 1 && wav[i] > 0){
7555: agecens[i]=agev[mw[j][i]][i];
7556: cens[i]= 1;
7557: }else if (ageexmed[i]< 1)
7558: cens[i]= -1;
7559: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7560: cens[i]=0 ;
7561: }
7562: else cens[i]=-1;
7563: }
7564:
7565: for (i=1;i<=NDIM;i++) {
7566: for (j=1;j<=NDIM;j++)
7567: ximort[i][j]=(i == j ? 1.0 : 0.0);
7568: }
7569:
7570: /*p[1]=0.0268; p[NDIM]=0.083;*/
7571: /*printf("%lf %lf", p[1], p[2]);*/
7572:
7573:
7574: #ifdef GSL
7575: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
7576: #else
7577: printf("Powell\n"); fprintf(ficlog,"Powell\n");
7578: #endif
7579: strcpy(filerespow,"POW-MORT_");
7580: strcat(filerespow,fileresu);
7581: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7582: printf("Problem with resultfile: %s\n", filerespow);
7583: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7584: }
7585: #ifdef GSL
7586: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
7587: #else
7588: fprintf(ficrespow,"# Powell\n# iter -2*LL");
7589: #endif
7590: /* for (i=1;i<=nlstate;i++)
7591: for(j=1;j<=nlstate+ndeath;j++)
7592: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7593: */
7594: fprintf(ficrespow,"\n");
7595: #ifdef GSL
7596: /* gsl starts here */
7597: T = gsl_multimin_fminimizer_nmsimplex;
7598: gsl_multimin_fminimizer *sfm = NULL;
7599: gsl_vector *ss, *x;
7600: gsl_multimin_function minex_func;
7601:
7602: /* Initial vertex size vector */
7603: ss = gsl_vector_alloc (NDIM);
7604:
7605: if (ss == NULL){
7606: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7607: }
7608: /* Set all step sizes to 1 */
7609: gsl_vector_set_all (ss, 0.001);
7610:
7611: /* Starting point */
7612:
7613: x = gsl_vector_alloc (NDIM);
7614:
7615: if (x == NULL){
7616: gsl_vector_free(ss);
7617: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7618: }
7619:
7620: /* Initialize method and iterate */
7621: /* p[1]=0.0268; p[NDIM]=0.083; */
7622: /* gsl_vector_set(x, 0, 0.0268); */
7623: /* gsl_vector_set(x, 1, 0.083); */
7624: gsl_vector_set(x, 0, p[1]);
7625: gsl_vector_set(x, 1, p[2]);
7626:
7627: minex_func.f = &gompertz_f;
7628: minex_func.n = NDIM;
7629: minex_func.params = (void *)&p; /* ??? */
7630:
7631: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7632: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7633:
7634: printf("Iterations beginning .....\n\n");
7635: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7636:
7637: iteri=0;
7638: while (rval == GSL_CONTINUE){
7639: iteri++;
7640: status = gsl_multimin_fminimizer_iterate(sfm);
7641:
7642: if (status) printf("error: %s\n", gsl_strerror (status));
7643: fflush(0);
7644:
7645: if (status)
7646: break;
7647:
7648: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7649: ssval = gsl_multimin_fminimizer_size (sfm);
7650:
7651: if (rval == GSL_SUCCESS)
7652: printf ("converged to a local maximum at\n");
7653:
7654: printf("%5d ", iteri);
7655: for (it = 0; it < NDIM; it++){
7656: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7657: }
7658: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7659: }
7660:
7661: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7662:
7663: gsl_vector_free(x); /* initial values */
7664: gsl_vector_free(ss); /* inital step size */
7665: for (it=0; it<NDIM; it++){
7666: p[it+1]=gsl_vector_get(sfm->x,it);
7667: fprintf(ficrespow," %.12lf", p[it]);
7668: }
7669: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7670: #endif
7671: #ifdef POWELL
7672: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7673: #endif
7674: fclose(ficrespow);
7675:
7676: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
7677:
7678: for(i=1; i <=NDIM; i++)
7679: for(j=i+1;j<=NDIM;j++)
7680: matcov[i][j]=matcov[j][i];
7681:
7682: printf("\nCovariance matrix\n ");
7683: fprintf(ficlog,"\nCovariance matrix\n ");
7684: for(i=1; i <=NDIM; i++) {
7685: for(j=1;j<=NDIM;j++){
7686: printf("%f ",matcov[i][j]);
7687: fprintf(ficlog,"%f ",matcov[i][j]);
7688: }
7689: printf("\n "); fprintf(ficlog,"\n ");
7690: }
7691:
7692: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7693: for (i=1;i<=NDIM;i++) {
7694: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7695: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7696: }
7697: lsurv=vector(1,AGESUP);
7698: lpop=vector(1,AGESUP);
7699: tpop=vector(1,AGESUP);
7700: lsurv[agegomp]=100000;
7701:
7702: for (k=agegomp;k<=AGESUP;k++) {
7703: agemortsup=k;
7704: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7705: }
7706:
7707: for (k=agegomp;k<agemortsup;k++)
7708: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7709:
7710: for (k=agegomp;k<agemortsup;k++){
7711: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7712: sumlpop=sumlpop+lpop[k];
7713: }
7714:
7715: tpop[agegomp]=sumlpop;
7716: for (k=agegomp;k<(agemortsup-3);k++){
7717: /* tpop[k+1]=2;*/
7718: tpop[k+1]=tpop[k]-lpop[k];
7719: }
7720:
7721:
7722: printf("\nAge lx qx dx Lx Tx e(x)\n");
7723: for (k=agegomp;k<(agemortsup-2);k++)
7724: 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]);
7725:
7726:
7727: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7728: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7729: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7730: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7731: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7732: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7733: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7734: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7735: }else
7736: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7737: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
7738: stepm, weightopt,\
7739: model,imx,p,matcov,agemortsup);
7740:
7741: free_vector(lsurv,1,AGESUP);
7742: free_vector(lpop,1,AGESUP);
7743: free_vector(tpop,1,AGESUP);
7744: #ifdef GSL
7745: free_ivector(cens,1,n);
7746: free_vector(agecens,1,n);
7747: free_ivector(dcwave,1,n);
7748: free_matrix(ximort,1,NDIM,1,NDIM);
7749: #endif
7750: } /* Endof if mle==-3 mortality only */
7751: /* Standard */
7752: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
7753: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7754: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7755: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7756: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7757: for (k=1; k<=npar;k++)
7758: printf(" %d %8.5f",k,p[k]);
7759: printf("\n");
7760: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
7761: /* mlikeli uses func not funcone */
7762: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7763: }
7764: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
7765: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7766: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7767: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7768: }
7769: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
7770: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7771: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7772: for (k=1; k<=npar;k++)
7773: printf(" %d %8.5f",k,p[k]);
7774: printf("\n");
7775:
7776: /*--------- results files --------------*/
7777: 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);
7778:
7779:
7780: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7781: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7782: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7783: for(i=1,jk=1; i <=nlstate; i++){
7784: for(k=1; k <=(nlstate+ndeath); k++){
7785: if (k != i) {
7786: printf("%d%d ",i,k);
7787: fprintf(ficlog,"%d%d ",i,k);
7788: fprintf(ficres,"%1d%1d ",i,k);
7789: for(j=1; j <=ncovmodel; j++){
7790: printf("%12.7f ",p[jk]);
7791: fprintf(ficlog,"%12.7f ",p[jk]);
7792: fprintf(ficres,"%12.7f ",p[jk]);
7793: jk++;
7794: }
7795: printf("\n");
7796: fprintf(ficlog,"\n");
7797: fprintf(ficres,"\n");
7798: }
7799: }
7800: }
7801: if(mle != 0){
7802: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
7803: ftolhess=ftol; /* Usually correct */
7804: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
7805: 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");
7806: 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");
7807: for(i=1,jk=1; i <=nlstate; i++){
7808: for(k=1; k <=(nlstate+ndeath); k++){
7809: if (k != i) {
7810: printf("%d%d ",i,k);
7811: fprintf(ficlog,"%d%d ",i,k);
7812: for(j=1; j <=ncovmodel; j++){
7813: 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]));
7814: 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]));
7815: jk++;
7816: }
7817: printf("\n");
7818: fprintf(ficlog,"\n");
7819: }
7820: }
7821: }
7822: } /* end of hesscov and Wald tests */
7823:
7824: /* */
7825: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7826: printf("# Scales (for hessian or gradient estimation)\n");
7827: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7828: for(i=1,jk=1; i <=nlstate; i++){
7829: for(j=1; j <=nlstate+ndeath; j++){
7830: if (j!=i) {
7831: fprintf(ficres,"%1d%1d",i,j);
7832: printf("%1d%1d",i,j);
7833: fprintf(ficlog,"%1d%1d",i,j);
7834: for(k=1; k<=ncovmodel;k++){
7835: printf(" %.5e",delti[jk]);
7836: fprintf(ficlog," %.5e",delti[jk]);
7837: fprintf(ficres," %.5e",delti[jk]);
7838: jk++;
7839: }
7840: printf("\n");
7841: fprintf(ficlog,"\n");
7842: fprintf(ficres,"\n");
7843: }
7844: }
7845: }
7846:
7847: 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");
7848: if(mle >= 1) /* To big for the screen */
7849: 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");
7850: 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");
7851: /* # 121 Var(a12)\n\ */
7852: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7853: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7854: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7855: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7856: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7857: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7858: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7859:
7860:
7861: /* Just to have a covariance matrix which will be more understandable
7862: even is we still don't want to manage dictionary of variables
7863: */
7864: for(itimes=1;itimes<=2;itimes++){
7865: jj=0;
7866: for(i=1; i <=nlstate; i++){
7867: for(j=1; j <=nlstate+ndeath; j++){
7868: if(j==i) continue;
7869: for(k=1; k<=ncovmodel;k++){
7870: jj++;
7871: ca[0]= k+'a'-1;ca[1]='\0';
7872: if(itimes==1){
7873: if(mle>=1)
7874: printf("#%1d%1d%d",i,j,k);
7875: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7876: fprintf(ficres,"#%1d%1d%d",i,j,k);
7877: }else{
7878: if(mle>=1)
7879: printf("%1d%1d%d",i,j,k);
7880: fprintf(ficlog,"%1d%1d%d",i,j,k);
7881: fprintf(ficres,"%1d%1d%d",i,j,k);
7882: }
7883: ll=0;
7884: for(li=1;li <=nlstate; li++){
7885: for(lj=1;lj <=nlstate+ndeath; lj++){
7886: if(lj==li) continue;
7887: for(lk=1;lk<=ncovmodel;lk++){
7888: ll++;
7889: if(ll<=jj){
7890: cb[0]= lk +'a'-1;cb[1]='\0';
7891: if(ll<jj){
7892: if(itimes==1){
7893: if(mle>=1)
7894: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7895: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7896: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7897: }else{
7898: if(mle>=1)
7899: printf(" %.5e",matcov[jj][ll]);
7900: fprintf(ficlog," %.5e",matcov[jj][ll]);
7901: fprintf(ficres," %.5e",matcov[jj][ll]);
7902: }
7903: }else{
7904: if(itimes==1){
7905: if(mle>=1)
7906: printf(" Var(%s%1d%1d)",ca,i,j);
7907: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7908: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7909: }else{
7910: if(mle>=1)
7911: printf(" %.7e",matcov[jj][ll]);
7912: fprintf(ficlog," %.7e",matcov[jj][ll]);
7913: fprintf(ficres," %.7e",matcov[jj][ll]);
7914: }
7915: }
7916: }
7917: } /* end lk */
7918: } /* end lj */
7919: } /* end li */
7920: if(mle>=1)
7921: printf("\n");
7922: fprintf(ficlog,"\n");
7923: fprintf(ficres,"\n");
7924: numlinepar++;
7925: } /* end k*/
7926: } /*end j */
7927: } /* end i */
7928: } /* end itimes */
7929:
7930: fflush(ficlog);
7931: fflush(ficres);
7932:
7933: while((c=getc(ficpar))=='#' && c!= EOF){
7934: ungetc(c,ficpar);
7935: fgets(line, MAXLINE, ficpar);
7936: fputs(line,stdout);
7937: fputs(line,ficparo);
7938: }
7939: ungetc(c,ficpar);
7940:
7941: estepm=0;
7942: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7943: if (estepm==0 || estepm < stepm) estepm=stepm;
7944: if (fage <= 2) {
7945: bage = ageminpar;
7946: fage = agemaxpar;
7947: }
7948:
7949: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7950: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7951: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7952:
7953: /* Other stuffs, more or less useful */
7954: while((c=getc(ficpar))=='#' && c!= EOF){
7955: ungetc(c,ficpar);
7956: fgets(line, MAXLINE, ficpar);
7957: fputs(line,stdout);
7958: fputs(line,ficparo);
7959: }
7960: ungetc(c,ficpar);
7961:
7962: 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);
7963: 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);
7964: 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);
7965: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7966: 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);
7967:
7968: while((c=getc(ficpar))=='#' && c!= EOF){
7969: ungetc(c,ficpar);
7970: fgets(line, MAXLINE, ficpar);
7971: fputs(line,stdout);
7972: fputs(line,ficparo);
7973: }
7974: ungetc(c,ficpar);
7975:
7976:
7977: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7978: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7979:
7980: fscanf(ficpar,"pop_based=%d\n",&popbased);
7981: fprintf(ficlog,"pop_based=%d\n",popbased);
7982: fprintf(ficparo,"pop_based=%d\n",popbased);
7983: fprintf(ficres,"pop_based=%d\n",popbased);
7984:
7985: while((c=getc(ficpar))=='#' && c!= EOF){
7986: ungetc(c,ficpar);
7987: fgets(line, MAXLINE, ficpar);
7988: fputs(line,stdout);
7989: fputs(line,ficparo);
7990: }
7991: ungetc(c,ficpar);
7992:
7993: 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);
7994: 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);
7995: 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);
7996: 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);
7997: 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);
7998: /* day and month of proj2 are not used but only year anproj2.*/
7999:
8000:
8001:
8002: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8003: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
8004:
8005: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8006: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8007: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8008: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8009: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8010: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8011: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8012: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8013: }else
8014: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8015:
8016: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
8017: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
8018: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
8019:
8020: /*------------ free_vector -------------*/
8021: /* chdir(path); */
8022:
8023: free_ivector(wav,1,imx);
8024: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
8025: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
8026: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
8027: free_lvector(num,1,n);
8028: free_vector(agedc,1,n);
8029: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8030: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8031: fclose(ficparo);
8032: fclose(ficres);
8033:
8034:
8035: /* Other results (useful)*/
8036:
8037:
8038: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
8039: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8040: prlim=matrix(1,nlstate,1,nlstate);
8041: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, ncvyear);
8042: fclose(ficrespl);
8043:
8044: #ifdef FREEEXIT2
8045: #include "freeexit2.h"
8046: #endif
8047:
8048: /*------------- h Pij x at various ages ------------*/
8049: /*#include "hpijx.h"*/
8050: hPijx(p, bage, fage);
8051: fclose(ficrespij);
8052:
8053: /*-------------- Variance of one-step probabilities---*/
8054: k=1;
8055: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8056:
8057:
8058: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8059: for(i=1;i<=AGESUP;i++)
8060: for(j=1;j<=NCOVMAX;j++)
8061: for(k=1;k<=NCOVMAX;k++)
8062: probs[i][j][k]=0.;
8063:
8064: /*---------- Forecasting ------------------*/
8065: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8066: if(prevfcast==1){
8067: /* if(stepm ==1){*/
8068: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
8069: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8070: /* } */
8071: /* else{ */
8072: /* erreur=108; */
8073: /* 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); */
8074: /* 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); */
8075: /* } */
8076: }
8077:
8078: /* ------ Other prevalence ratios------------ */
8079:
8080: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8081:
8082: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8083: /* 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",\
8084: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8085: */
8086:
8087: if (mobilav!=0) {
8088: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8089: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8090: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8091: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8092: }
8093: }
8094:
8095:
8096: /*---------- Health expectancies, no variances ------------*/
8097:
8098: strcpy(filerese,"E_");
8099: strcat(filerese,fileresu);
8100: if((ficreseij=fopen(filerese,"w"))==NULL) {
8101: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8102: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8103: }
8104: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8105: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
8106: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8107: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8108:
8109: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8110: fprintf(ficreseij,"\n#****** ");
8111: for(j=1;j<=cptcoveff;j++) {
8112: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8113: }
8114: fprintf(ficreseij,"******\n");
8115:
8116: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8117: oldm=oldms;savm=savms;
8118: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8119:
8120: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8121: /*}*/
8122: }
8123: fclose(ficreseij);
8124: printf("done evsij\n");fflush(stdout);
8125: fprintf(ficlog,"done evsij\n");fflush(ficlog);
8126:
8127: /*---------- Health expectancies and variances ------------*/
8128:
8129:
8130: strcpy(filerest,"T_");
8131: strcat(filerest,fileresu);
8132: if((ficrest=fopen(filerest,"w"))==NULL) {
8133: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8134: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8135: }
8136: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8137: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
8138:
8139:
8140: strcpy(fileresstde,"STDE_");
8141: strcat(fileresstde,fileresu);
8142: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8143: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8144: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8145: }
8146: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8147: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8148:
8149: strcpy(filerescve,"CVE_");
8150: strcat(filerescve,fileresu);
8151: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8152: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8153: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8154: }
8155: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8156: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8157:
8158: strcpy(fileresv,"V_");
8159: strcat(fileresv,fileresu);
8160: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8161: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8162: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8163: }
8164: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8165: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
8166:
8167: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8168: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8169:
8170: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8171: fprintf(ficrest,"\n#****** ");
8172: for(j=1;j<=cptcoveff;j++)
8173: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8174: fprintf(ficrest,"******\n");
8175:
8176: fprintf(ficresstdeij,"\n#****** ");
8177: fprintf(ficrescveij,"\n#****** ");
8178: for(j=1;j<=cptcoveff;j++) {
8179: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8180: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8181: }
8182: fprintf(ficresstdeij,"******\n");
8183: fprintf(ficrescveij,"******\n");
8184:
8185: fprintf(ficresvij,"\n#****** ");
8186: for(j=1;j<=cptcoveff;j++)
8187: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8188: fprintf(ficresvij,"******\n");
8189:
8190: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8191: oldm=oldms;savm=savms;
8192: printf(" cvevsij %d, ",k);
8193: fprintf(ficlog, " cvevsij %d, ",k);
8194: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8195: printf(" end cvevsij \n ");
8196: fprintf(ficlog, " end cvevsij \n ");
8197:
8198: /*
8199: */
8200: /* goto endfree; */
8201:
8202: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8203: pstamp(ficrest);
8204:
8205:
8206: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8207: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8208: cptcod= 0; /* To be deleted */
8209: printf("varevsij %d \n",vpopbased);
8210: fprintf(ficlog, "varevsij %d \n",vpopbased);
8211: 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 */
8212: 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 ");
8213: if(vpopbased==1)
8214: 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);
8215: else
8216: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8217: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8218: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8219: fprintf(ficrest,"\n");
8220: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8221: epj=vector(1,nlstate+1);
8222: printf("Computing age specific period (stable) prevalences in each health state \n");
8223: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8224: for(age=bage; age <=fage ;age++){
8225: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
8226: if (vpopbased==1) {
8227: if(mobilav ==0){
8228: for(i=1; i<=nlstate;i++)
8229: prlim[i][i]=probs[(int)age][i][k];
8230: }else{ /* mobilav */
8231: for(i=1; i<=nlstate;i++)
8232: prlim[i][i]=mobaverage[(int)age][i][k];
8233: }
8234: }
8235:
8236: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8237: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8238: /* printf(" age %4.0f ",age); */
8239: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8240: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8241: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8242: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8243: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8244: }
8245: epj[nlstate+1] +=epj[j];
8246: }
8247: /* printf(" age %4.0f \n",age); */
8248:
8249: for(i=1, vepp=0.;i <=nlstate;i++)
8250: for(j=1;j <=nlstate;j++)
8251: vepp += vareij[i][j][(int)age];
8252: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8253: for(j=1;j <=nlstate;j++){
8254: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8255: }
8256: fprintf(ficrest,"\n");
8257: }
8258: } /* End vpopbased */
8259: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8260: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8261: free_vector(epj,1,nlstate+1);
8262: printf("done \n");fflush(stdout);
8263: fprintf(ficlog,"done\n");fflush(ficlog);
8264:
8265: /*}*/
8266: } /* End k */
8267: free_vector(weight,1,n);
8268: free_imatrix(Tvard,1,NCOVMAX,1,2);
8269: free_imatrix(s,1,maxwav+1,1,n);
8270: free_matrix(anint,1,maxwav,1,n);
8271: free_matrix(mint,1,maxwav,1,n);
8272: free_ivector(cod,1,n);
8273: free_ivector(tab,1,NCOVMAX);
8274: fclose(ficresstdeij);
8275: fclose(ficrescveij);
8276: fclose(ficresvij);
8277: fclose(ficrest);
8278: printf("done Health expectancies\n");fflush(stdout);
8279: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
8280: fclose(ficpar);
8281:
8282: /*------- Variance of period (stable) prevalence------*/
8283:
8284: strcpy(fileresvpl,"VPL_");
8285: strcat(fileresvpl,fileresu);
8286: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8287: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8288: exit(0);
8289: }
8290: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8291: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
8292:
8293: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8294: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8295:
8296: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8297: fprintf(ficresvpl,"\n#****** ");
8298: for(j=1;j<=cptcoveff;j++)
8299: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8300: fprintf(ficresvpl,"******\n");
8301:
8302: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8303: oldm=oldms;savm=savms;
8304: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
8305: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8306: /*}*/
8307: }
8308:
8309: fclose(ficresvpl);
8310: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8311: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
8312:
8313: /*---------- End : free ----------------*/
8314: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8315: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8316: } /* mle==-3 arrives here for freeing */
8317: /* endfree:*/
8318: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8319: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8320: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8321: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8322: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8323: free_matrix(covar,0,NCOVMAX,1,n);
8324: free_matrix(matcov,1,npar,1,npar);
8325: free_matrix(hess,1,npar,1,npar);
8326: /*free_vector(delti,1,npar);*/
8327: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8328: free_matrix(agev,1,maxwav,1,imx);
8329: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8330:
8331: free_ivector(ncodemax,1,NCOVMAX);
8332: free_ivector(ncodemaxwundef,1,NCOVMAX);
8333: free_ivector(Tvar,1,NCOVMAX);
8334: free_ivector(Tprod,1,NCOVMAX);
8335: free_ivector(Tvaraff,1,NCOVMAX);
8336: free_ivector(Tage,1,NCOVMAX);
8337:
8338: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8339: /* free_imatrix(codtab,1,100,1,10); */
8340: fflush(fichtm);
8341: fflush(ficgp);
8342:
8343:
8344: if((nberr >0) || (nbwarn>0)){
8345: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8346: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8347: }else{
8348: printf("End of Imach\n");
8349: fprintf(ficlog,"End of Imach\n");
8350: }
8351: printf("See log file on %s\n",filelog);
8352: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8353: /*(void) gettimeofday(&end_time,&tzp);*/
8354: rend_time = time(NULL);
8355: end_time = *localtime(&rend_time);
8356: /* tml = *localtime(&end_time.tm_sec); */
8357: strcpy(strtend,asctime(&end_time));
8358: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8359: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8360: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8361:
8362: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8363: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8364: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8365: /* printf("Total time was %d uSec.\n", total_usecs);*/
8366: /* if(fileappend(fichtm,optionfilehtm)){ */
8367: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8368: fclose(fichtm);
8369: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8370: fclose(fichtmcov);
8371: fclose(ficgp);
8372: fclose(ficlog);
8373: /*------ End -----------*/
8374:
8375:
8376: printf("Before Current directory %s!\n",pathcd);
8377: #ifdef WIN32
8378: if (_chdir(pathcd) != 0)
8379: printf("Can't move to directory %s!\n",path);
8380: if(_getcwd(pathcd,MAXLINE) > 0)
8381: #else
8382: if(chdir(pathcd) != 0)
8383: printf("Can't move to directory %s!\n", path);
8384: if (getcwd(pathcd, MAXLINE) > 0)
8385: #endif
8386: printf("Current directory %s!\n",pathcd);
8387: /*strcat(plotcmd,CHARSEPARATOR);*/
8388: sprintf(plotcmd,"gnuplot");
8389: #ifdef _WIN32
8390: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8391: #endif
8392: if(!stat(plotcmd,&info)){
8393: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8394: if(!stat(getenv("GNUPLOTBIN"),&info)){
8395: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8396: }else
8397: strcpy(pplotcmd,plotcmd);
8398: #ifdef __unix
8399: strcpy(plotcmd,GNUPLOTPROGRAM);
8400: if(!stat(plotcmd,&info)){
8401: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8402: }else
8403: strcpy(pplotcmd,plotcmd);
8404: #endif
8405: }else
8406: strcpy(pplotcmd,plotcmd);
8407:
8408: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8409: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8410:
8411: if((outcmd=system(plotcmd)) != 0){
8412: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8413: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8414: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8415: if((outcmd=system(plotcmd)) != 0)
8416: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8417: }
8418: printf(" Successful, please wait...");
8419: while (z[0] != 'q') {
8420: /* chdir(path); */
8421: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8422: scanf("%s",z);
8423: /* if (z[0] == 'c') system("./imach"); */
8424: if (z[0] == 'e') {
8425: #ifdef __APPLE__
8426: sprintf(pplotcmd, "open %s", optionfilehtm);
8427: #elif __linux
8428: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8429: #else
8430: sprintf(pplotcmd, "%s", optionfilehtm);
8431: #endif
8432: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8433: system(pplotcmd);
8434: }
8435: else if (z[0] == 'g') system(plotcmd);
8436: else if (z[0] == 'q') exit(0);
8437: }
8438: end:
8439: while (z[0] != 'q') {
8440: printf("\nType q for exiting: "); fflush(stdout);
8441: scanf("%s",z);
8442: }
8443: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>