1: /* $Id: imach.c,v 1.191 2015/07/14 10:00:33 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.191 2015/07/14 10:00:33 brouard
5: Summary: Some fixes
6:
7: Revision 1.190 2015/05/05 08:51:13 brouard
8: Summary: Adding digits in output parameters (7 digits instead of 6)
9:
10: Fix 1+age+.
11:
12: Revision 1.189 2015/04/30 14:45:16 brouard
13: Summary: 0.98q2
14:
15: Revision 1.188 2015/04/30 08:27:53 brouard
16: *** empty log message ***
17:
18: Revision 1.187 2015/04/29 09:11:15 brouard
19: *** empty log message ***
20:
21: Revision 1.186 2015/04/23 12:01:52 brouard
22: Summary: V1*age is working now, version 0.98q1
23:
24: Some codes had been disabled in order to simplify and Vn*age was
25: working in the optimization phase, ie, giving correct MLE parameters,
26: but, as usual, outputs were not correct and program core dumped.
27:
28: Revision 1.185 2015/03/11 13:26:42 brouard
29: Summary: Inclusion of compile and links command line for Intel Compiler
30:
31: Revision 1.184 2015/03/11 11:52:39 brouard
32: Summary: Back from Windows 8. Intel Compiler
33:
34: Revision 1.183 2015/03/10 20:34:32 brouard
35: Summary: 0.98q0, trying with directest, mnbrak fixed
36:
37: We use directest instead of original Powell test; probably no
38: incidence on the results, but better justifications;
39: We fixed Numerical Recipes mnbrak routine which was wrong and gave
40: wrong results.
41:
42: Revision 1.182 2015/02/12 08:19:57 brouard
43: Summary: Trying to keep directest which seems simpler and more general
44: Author: Nicolas Brouard
45:
46: Revision 1.181 2015/02/11 23:22:24 brouard
47: Summary: Comments on Powell added
48:
49: Author:
50:
51: Revision 1.180 2015/02/11 17:33:45 brouard
52: Summary: Finishing move from main to function (hpijx and prevalence_limit)
53:
54: Revision 1.179 2015/01/04 09:57:06 brouard
55: Summary: back to OS/X
56:
57: Revision 1.178 2015/01/04 09:35:48 brouard
58: *** empty log message ***
59:
60: Revision 1.177 2015/01/03 18:40:56 brouard
61: Summary: Still testing ilc32 on OSX
62:
63: Revision 1.176 2015/01/03 16:45:04 brouard
64: *** empty log message ***
65:
66: Revision 1.175 2015/01/03 16:33:42 brouard
67: *** empty log message ***
68:
69: Revision 1.174 2015/01/03 16:15:49 brouard
70: Summary: Still in cross-compilation
71:
72: Revision 1.173 2015/01/03 12:06:26 brouard
73: Summary: trying to detect cross-compilation
74:
75: Revision 1.172 2014/12/27 12:07:47 brouard
76: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
77:
78: Revision 1.171 2014/12/23 13:26:59 brouard
79: Summary: Back from Visual C
80:
81: Still problem with utsname.h on Windows
82:
83: Revision 1.170 2014/12/23 11:17:12 brouard
84: Summary: Cleaning some \%% back to %%
85:
86: The escape was mandatory for a specific compiler (which one?), but too many warnings.
87:
88: Revision 1.169 2014/12/22 23:08:31 brouard
89: Summary: 0.98p
90:
91: Outputs some informations on compiler used, OS etc. Testing on different platforms.
92:
93: Revision 1.168 2014/12/22 15:17:42 brouard
94: Summary: update
95:
96: Revision 1.167 2014/12/22 13:50:56 brouard
97: Summary: Testing uname and compiler version and if compiled 32 or 64
98:
99: Testing on Linux 64
100:
101: Revision 1.166 2014/12/22 11:40:47 brouard
102: *** empty log message ***
103:
104: Revision 1.165 2014/12/16 11:20:36 brouard
105: Summary: After compiling on Visual C
106:
107: * imach.c (Module): Merging 1.61 to 1.162
108:
109: Revision 1.164 2014/12/16 10:52:11 brouard
110: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
111:
112: * imach.c (Module): Merging 1.61 to 1.162
113:
114: Revision 1.163 2014/12/16 10:30:11 brouard
115: * imach.c (Module): Merging 1.61 to 1.162
116:
117: Revision 1.162 2014/09/25 11:43:39 brouard
118: Summary: temporary backup 0.99!
119:
120: Revision 1.1 2014/09/16 11:06:58 brouard
121: Summary: With some code (wrong) for nlopt
122:
123: Author:
124:
125: Revision 1.161 2014/09/15 20:41:41 brouard
126: Summary: Problem with macro SQR on Intel compiler
127:
128: Revision 1.160 2014/09/02 09:24:05 brouard
129: *** empty log message ***
130:
131: Revision 1.159 2014/09/01 10:34:10 brouard
132: Summary: WIN32
133: Author: Brouard
134:
135: Revision 1.158 2014/08/27 17:11:51 brouard
136: *** empty log message ***
137:
138: Revision 1.157 2014/08/27 16:26:55 brouard
139: Summary: Preparing windows Visual studio version
140: Author: Brouard
141:
142: In order to compile on Visual studio, time.h is now correct and time_t
143: and tm struct should be used. difftime should be used but sometimes I
144: just make the differences in raw time format (time(&now).
145: Trying to suppress #ifdef LINUX
146: Add xdg-open for __linux in order to open default browser.
147:
148: Revision 1.156 2014/08/25 20:10:10 brouard
149: *** empty log message ***
150:
151: Revision 1.155 2014/08/25 18:32:34 brouard
152: Summary: New compile, minor changes
153: Author: Brouard
154:
155: Revision 1.154 2014/06/20 17:32:08 brouard
156: Summary: Outputs now all graphs of convergence to period prevalence
157:
158: Revision 1.153 2014/06/20 16:45:46 brouard
159: Summary: If 3 live state, convergence to period prevalence on same graph
160: Author: Brouard
161:
162: Revision 1.152 2014/06/18 17:54:09 brouard
163: Summary: open browser, use gnuplot on same dir than imach if not found in the path
164:
165: Revision 1.151 2014/06/18 16:43:30 brouard
166: *** empty log message ***
167:
168: Revision 1.150 2014/06/18 16:42:35 brouard
169: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
170: Author: brouard
171:
172: Revision 1.149 2014/06/18 15:51:14 brouard
173: Summary: Some fixes in parameter files errors
174: Author: Nicolas Brouard
175:
176: Revision 1.148 2014/06/17 17:38:48 brouard
177: Summary: Nothing new
178: Author: Brouard
179:
180: Just a new packaging for OS/X version 0.98nS
181:
182: Revision 1.147 2014/06/16 10:33:11 brouard
183: *** empty log message ***
184:
185: Revision 1.146 2014/06/16 10:20:28 brouard
186: Summary: Merge
187: Author: Brouard
188:
189: Merge, before building revised version.
190:
191: Revision 1.145 2014/06/10 21:23:15 brouard
192: Summary: Debugging with valgrind
193: Author: Nicolas Brouard
194:
195: Lot of changes in order to output the results with some covariates
196: After the Edimburgh REVES conference 2014, it seems mandatory to
197: improve the code.
198: No more memory valgrind error but a lot has to be done in order to
199: continue the work of splitting the code into subroutines.
200: Also, decodemodel has been improved. Tricode is still not
201: optimal. nbcode should be improved. Documentation has been added in
202: the source code.
203:
204: Revision 1.143 2014/01/26 09:45:38 brouard
205: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
206:
207: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
208: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
209:
210: Revision 1.142 2014/01/26 03:57:36 brouard
211: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
212:
213: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
214:
215: Revision 1.141 2014/01/26 02:42:01 brouard
216: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
217:
218: Revision 1.140 2011/09/02 10:37:54 brouard
219: Summary: times.h is ok with mingw32 now.
220:
221: Revision 1.139 2010/06/14 07:50:17 brouard
222: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
223: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
224:
225: Revision 1.138 2010/04/30 18:19:40 brouard
226: *** empty log message ***
227:
228: Revision 1.137 2010/04/29 18:11:38 brouard
229: (Module): Checking covariates for more complex models
230: than V1+V2. A lot of change to be done. Unstable.
231:
232: Revision 1.136 2010/04/26 20:30:53 brouard
233: (Module): merging some libgsl code. Fixing computation
234: of likelione (using inter/intrapolation if mle = 0) in order to
235: get same likelihood as if mle=1.
236: Some cleaning of code and comments added.
237:
238: Revision 1.135 2009/10/29 15:33:14 brouard
239: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
240:
241: Revision 1.134 2009/10/29 13:18:53 brouard
242: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
243:
244: Revision 1.133 2009/07/06 10:21:25 brouard
245: just nforces
246:
247: Revision 1.132 2009/07/06 08:22:05 brouard
248: Many tings
249:
250: Revision 1.131 2009/06/20 16:22:47 brouard
251: Some dimensions resccaled
252:
253: Revision 1.130 2009/05/26 06:44:34 brouard
254: (Module): Max Covariate is now set to 20 instead of 8. A
255: lot of cleaning with variables initialized to 0. Trying to make
256: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
257:
258: Revision 1.129 2007/08/31 13:49:27 lievre
259: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
260:
261: Revision 1.128 2006/06/30 13:02:05 brouard
262: (Module): Clarifications on computing e.j
263:
264: Revision 1.127 2006/04/28 18:11:50 brouard
265: (Module): Yes the sum of survivors was wrong since
266: imach-114 because nhstepm was no more computed in the age
267: loop. Now we define nhstepma in the age loop.
268: (Module): In order to speed up (in case of numerous covariates) we
269: compute health expectancies (without variances) in a first step
270: and then all the health expectancies with variances or standard
271: deviation (needs data from the Hessian matrices) which slows the
272: computation.
273: In the future we should be able to stop the program is only health
274: expectancies and graph are needed without standard deviations.
275:
276: Revision 1.126 2006/04/28 17:23:28 brouard
277: (Module): Yes the sum of survivors was wrong since
278: imach-114 because nhstepm was no more computed in the age
279: loop. Now we define nhstepma in the age loop.
280: Version 0.98h
281:
282: Revision 1.125 2006/04/04 15:20:31 lievre
283: Errors in calculation of health expectancies. Age was not initialized.
284: Forecasting file added.
285:
286: Revision 1.124 2006/03/22 17:13:53 lievre
287: Parameters are printed with %lf instead of %f (more numbers after the comma).
288: The log-likelihood is printed in the log file
289:
290: Revision 1.123 2006/03/20 10:52:43 brouard
291: * imach.c (Module): <title> changed, corresponds to .htm file
292: name. <head> headers where missing.
293:
294: * imach.c (Module): Weights can have a decimal point as for
295: English (a comma might work with a correct LC_NUMERIC environment,
296: otherwise the weight is truncated).
297: Modification of warning when the covariates values are not 0 or
298: 1.
299: Version 0.98g
300:
301: Revision 1.122 2006/03/20 09:45:41 brouard
302: (Module): Weights can have a decimal point as for
303: English (a comma might work with a correct LC_NUMERIC environment,
304: otherwise the weight is truncated).
305: Modification of warning when the covariates values are not 0 or
306: 1.
307: Version 0.98g
308:
309: Revision 1.121 2006/03/16 17:45:01 lievre
310: * imach.c (Module): Comments concerning covariates added
311:
312: * imach.c (Module): refinements in the computation of lli if
313: status=-2 in order to have more reliable computation if stepm is
314: not 1 month. Version 0.98f
315:
316: Revision 1.120 2006/03/16 15:10:38 lievre
317: (Module): refinements in the computation of lli if
318: status=-2 in order to have more reliable computation if stepm is
319: not 1 month. Version 0.98f
320:
321: Revision 1.119 2006/03/15 17:42:26 brouard
322: (Module): Bug if status = -2, the loglikelihood was
323: computed as likelihood omitting the logarithm. Version O.98e
324:
325: Revision 1.118 2006/03/14 18:20:07 brouard
326: (Module): varevsij Comments added explaining the second
327: table of variances if popbased=1 .
328: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
329: (Module): Function pstamp added
330: (Module): Version 0.98d
331:
332: Revision 1.117 2006/03/14 17:16:22 brouard
333: (Module): varevsij Comments added explaining the second
334: table of variances if popbased=1 .
335: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
336: (Module): Function pstamp added
337: (Module): Version 0.98d
338:
339: Revision 1.116 2006/03/06 10:29:27 brouard
340: (Module): Variance-covariance wrong links and
341: varian-covariance of ej. is needed (Saito).
342:
343: Revision 1.115 2006/02/27 12:17:45 brouard
344: (Module): One freematrix added in mlikeli! 0.98c
345:
346: Revision 1.114 2006/02/26 12:57:58 brouard
347: (Module): Some improvements in processing parameter
348: filename with strsep.
349:
350: Revision 1.113 2006/02/24 14:20:24 brouard
351: (Module): Memory leaks checks with valgrind and:
352: datafile was not closed, some imatrix were not freed and on matrix
353: allocation too.
354:
355: Revision 1.112 2006/01/30 09:55:26 brouard
356: (Module): Back to gnuplot.exe instead of wgnuplot.exe
357:
358: Revision 1.111 2006/01/25 20:38:18 brouard
359: (Module): Lots of cleaning and bugs added (Gompertz)
360: (Module): Comments can be added in data file. Missing date values
361: can be a simple dot '.'.
362:
363: Revision 1.110 2006/01/25 00:51:50 brouard
364: (Module): Lots of cleaning and bugs added (Gompertz)
365:
366: Revision 1.109 2006/01/24 19:37:15 brouard
367: (Module): Comments (lines starting with a #) are allowed in data.
368:
369: Revision 1.108 2006/01/19 18:05:42 lievre
370: Gnuplot problem appeared...
371: To be fixed
372:
373: Revision 1.107 2006/01/19 16:20:37 brouard
374: Test existence of gnuplot in imach path
375:
376: Revision 1.106 2006/01/19 13:24:36 brouard
377: Some cleaning and links added in html output
378:
379: Revision 1.105 2006/01/05 20:23:19 lievre
380: *** empty log message ***
381:
382: Revision 1.104 2005/09/30 16:11:43 lievre
383: (Module): sump fixed, loop imx fixed, and simplifications.
384: (Module): If the status is missing at the last wave but we know
385: that the person is alive, then we can code his/her status as -2
386: (instead of missing=-1 in earlier versions) and his/her
387: contributions to the likelihood is 1 - Prob of dying from last
388: health status (= 1-p13= p11+p12 in the easiest case of somebody in
389: the healthy state at last known wave). Version is 0.98
390:
391: Revision 1.103 2005/09/30 15:54:49 lievre
392: (Module): sump fixed, loop imx fixed, and simplifications.
393:
394: Revision 1.102 2004/09/15 17:31:30 brouard
395: Add the possibility to read data file including tab characters.
396:
397: Revision 1.101 2004/09/15 10:38:38 brouard
398: Fix on curr_time
399:
400: Revision 1.100 2004/07/12 18:29:06 brouard
401: Add version for Mac OS X. Just define UNIX in Makefile
402:
403: Revision 1.99 2004/06/05 08:57:40 brouard
404: *** empty log message ***
405:
406: Revision 1.98 2004/05/16 15:05:56 brouard
407: New version 0.97 . First attempt to estimate force of mortality
408: directly from the data i.e. without the need of knowing the health
409: state at each age, but using a Gompertz model: log u =a + b*age .
410: This is the basic analysis of mortality and should be done before any
411: other analysis, in order to test if the mortality estimated from the
412: cross-longitudinal survey is different from the mortality estimated
413: from other sources like vital statistic data.
414:
415: The same imach parameter file can be used but the option for mle should be -3.
416:
417: Agnès, who wrote this part of the code, tried to keep most of the
418: former routines in order to include the new code within the former code.
419:
420: The output is very simple: only an estimate of the intercept and of
421: the slope with 95% confident intervals.
422:
423: Current limitations:
424: A) Even if you enter covariates, i.e. with the
425: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
426: B) There is no computation of Life Expectancy nor Life Table.
427:
428: Revision 1.97 2004/02/20 13:25:42 lievre
429: Version 0.96d. Population forecasting command line is (temporarily)
430: suppressed.
431:
432: Revision 1.96 2003/07/15 15:38:55 brouard
433: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
434: rewritten within the same printf. Workaround: many printfs.
435:
436: Revision 1.95 2003/07/08 07:54:34 brouard
437: * imach.c (Repository):
438: (Repository): Using imachwizard code to output a more meaningful covariance
439: matrix (cov(a12,c31) instead of numbers.
440:
441: Revision 1.94 2003/06/27 13:00:02 brouard
442: Just cleaning
443:
444: Revision 1.93 2003/06/25 16:33:55 brouard
445: (Module): On windows (cygwin) function asctime_r doesn't
446: exist so I changed back to asctime which exists.
447: (Module): Version 0.96b
448:
449: Revision 1.92 2003/06/25 16:30:45 brouard
450: (Module): On windows (cygwin) function asctime_r doesn't
451: exist so I changed back to asctime which exists.
452:
453: Revision 1.91 2003/06/25 15:30:29 brouard
454: * imach.c (Repository): Duplicated warning errors corrected.
455: (Repository): Elapsed time after each iteration is now output. It
456: helps to forecast when convergence will be reached. Elapsed time
457: is stamped in powell. We created a new html file for the graphs
458: concerning matrix of covariance. It has extension -cov.htm.
459:
460: Revision 1.90 2003/06/24 12:34:15 brouard
461: (Module): Some bugs corrected for windows. Also, when
462: mle=-1 a template is output in file "or"mypar.txt with the design
463: of the covariance matrix to be input.
464:
465: Revision 1.89 2003/06/24 12:30:52 brouard
466: (Module): Some bugs corrected for windows. Also, when
467: mle=-1 a template is output in file "or"mypar.txt with the design
468: of the covariance matrix to be input.
469:
470: Revision 1.88 2003/06/23 17:54:56 brouard
471: * 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.
472:
473: Revision 1.87 2003/06/18 12:26:01 brouard
474: Version 0.96
475:
476: Revision 1.86 2003/06/17 20:04:08 brouard
477: (Module): Change position of html and gnuplot routines and added
478: routine fileappend.
479:
480: Revision 1.85 2003/06/17 13:12:43 brouard
481: * imach.c (Repository): Check when date of death was earlier that
482: current date of interview. It may happen when the death was just
483: prior to the death. In this case, dh was negative and likelihood
484: was wrong (infinity). We still send an "Error" but patch by
485: assuming that the date of death was just one stepm after the
486: interview.
487: (Repository): Because some people have very long ID (first column)
488: we changed int to long in num[] and we added a new lvector for
489: memory allocation. But we also truncated to 8 characters (left
490: truncation)
491: (Repository): No more line truncation errors.
492:
493: Revision 1.84 2003/06/13 21:44:43 brouard
494: * imach.c (Repository): Replace "freqsummary" at a correct
495: place. It differs from routine "prevalence" which may be called
496: many times. Probs is memory consuming and must be used with
497: parcimony.
498: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
499:
500: Revision 1.83 2003/06/10 13:39:11 lievre
501: *** empty log message ***
502:
503: Revision 1.82 2003/06/05 15:57:20 brouard
504: Add log in imach.c and fullversion number is now printed.
505:
506: */
507: /*
508: Interpolated Markov Chain
509:
510: Short summary of the programme:
511:
512: This program computes Healthy Life Expectancies from
513: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
514: first survey ("cross") where individuals from different ages are
515: interviewed on their health status or degree of disability (in the
516: case of a health survey which is our main interest) -2- at least a
517: second wave of interviews ("longitudinal") which measure each change
518: (if any) in individual health status. Health expectancies are
519: computed from the time spent in each health state according to a
520: model. More health states you consider, more time is necessary to reach the
521: Maximum Likelihood of the parameters involved in the model. The
522: simplest model is the multinomial logistic model where pij is the
523: probability to be observed in state j at the second wave
524: conditional to be observed in state i at the first wave. Therefore
525: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
526: 'age' is age and 'sex' is a covariate. If you want to have a more
527: complex model than "constant and age", you should modify the program
528: where the markup *Covariates have to be included here again* invites
529: you to do it. More covariates you add, slower the
530: convergence.
531:
532: The advantage of this computer programme, compared to a simple
533: multinomial logistic model, is clear when the delay between waves is not
534: identical for each individual. Also, if a individual missed an
535: intermediate interview, the information is lost, but taken into
536: account using an interpolation or extrapolation.
537:
538: hPijx is the probability to be observed in state i at age x+h
539: conditional to the observed state i at age x. The delay 'h' can be
540: split into an exact number (nh*stepm) of unobserved intermediate
541: states. This elementary transition (by month, quarter,
542: semester or year) is modelled as a multinomial logistic. The hPx
543: matrix is simply the matrix product of nh*stepm elementary matrices
544: and the contribution of each individual to the likelihood is simply
545: hPijx.
546:
547: Also this programme outputs the covariance matrix of the parameters but also
548: of the life expectancies. It also computes the period (stable) prevalence.
549:
550: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
551: Institut national d'études démographiques, Paris.
552: This software have been partly granted by Euro-REVES, a concerted action
553: from the European Union.
554: It is copyrighted identically to a GNU software product, ie programme and
555: software can be distributed freely for non commercial use. Latest version
556: can be accessed at http://euroreves.ined.fr/imach .
557:
558: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
559: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
560:
561: **********************************************************************/
562: /*
563: main
564: read parameterfile
565: read datafile
566: concatwav
567: freqsummary
568: if (mle >= 1)
569: mlikeli
570: print results files
571: if mle==1
572: computes hessian
573: read end of parameter file: agemin, agemax, bage, fage, estepm
574: begin-prev-date,...
575: open gnuplot file
576: open html file
577: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
578: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
579: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
580: freexexit2 possible for memory heap.
581:
582: h Pij x | pij_nom ficrestpij
583: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
584: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
585: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
586:
587: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
588: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
589: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
590: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
591: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
592:
593: forecasting if prevfcast==1 prevforecast call prevalence()
594: health expectancies
595: Variance-covariance of DFLE
596: prevalence()
597: movingaverage()
598: varevsij()
599: if popbased==1 varevsij(,popbased)
600: total life expectancies
601: Variance of period (stable) prevalence
602: end
603: */
604:
605: /* #define DEBUG */
606: /* #define DEBUGBRENT */
607: #define POWELL /* Instead of NLOPT */
608: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
609: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
610:
611: #include <math.h>
612: #include <stdio.h>
613: #include <stdlib.h>
614: #include <string.h>
615:
616: #ifdef _WIN32
617: #include <io.h>
618: #include <windows.h>
619: #include <tchar.h>
620: #else
621: #include <unistd.h>
622: #endif
623:
624: #include <limits.h>
625: #include <sys/types.h>
626:
627: #if defined(__GNUC__)
628: #include <sys/utsname.h> /* Doesn't work on Windows */
629: #endif
630:
631: #include <sys/stat.h>
632: #include <errno.h>
633: /* extern int errno; */
634:
635: /* #ifdef LINUX */
636: /* #include <time.h> */
637: /* #include "timeval.h" */
638: /* #else */
639: /* #include <sys/time.h> */
640: /* #endif */
641:
642: #include <time.h>
643:
644: #ifdef GSL
645: #include <gsl/gsl_errno.h>
646: #include <gsl/gsl_multimin.h>
647: #endif
648:
649:
650: #ifdef NLOPT
651: #include <nlopt.h>
652: typedef struct {
653: double (* function)(double [] );
654: } myfunc_data ;
655: #endif
656:
657: /* #include <libintl.h> */
658: /* #define _(String) gettext (String) */
659:
660: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
661:
662: #define GNUPLOTPROGRAM "gnuplot"
663: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
664: #define FILENAMELENGTH 132
665:
666: #define GLOCK_ERROR_NOPATH -1 /* empty path */
667: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
668:
669: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
670: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
671:
672: #define NINTERVMAX 8
673: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
674: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
675: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
676: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
677: #define MAXN 20000
678: #define YEARM 12. /**< Number of months per year */
679: #define AGESUP 130
680: #define AGEBASE 40
681: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
682: #ifdef _WIN32
683: #define DIRSEPARATOR '\\'
684: #define CHARSEPARATOR "\\"
685: #define ODIRSEPARATOR '/'
686: #else
687: #define DIRSEPARATOR '/'
688: #define CHARSEPARATOR "/"
689: #define ODIRSEPARATOR '\\'
690: #endif
691:
692: /* $Id: imach.c,v 1.191 2015/07/14 10:00:33 brouard Exp $ */
693: /* $State: Exp $ */
694:
695: char version[]="Imach version 0.98q2, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
696: char fullversion[]="$Revision: 1.191 $ $Date: 2015/07/14 10:00:33 $";
697: char strstart[80];
698: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
699: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
700: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
701: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
702: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
703: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
704: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
705: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
706: int cptcovprodnoage=0; /**< Number of covariate products without age */
707: int cptcoveff=0; /* Total number of covariates to vary for printing results */
708: int cptcov=0; /* Working variable */
709: int npar=NPARMAX;
710: int nlstate=2; /* Number of live states */
711: int ndeath=1; /* Number of dead states */
712: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
713: int popbased=0;
714:
715: int *wav; /* Number of waves for this individuual 0 is possible */
716: int maxwav=0; /* Maxim number of waves */
717: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
718: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
719: int gipmx=0, gsw=0; /* Global variables on the number of contributions
720: to the likelihood and the sum of weights (done by funcone)*/
721: int mle=1, weightopt=0;
722: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
723: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
724: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
725: * wave mi and wave mi+1 is not an exact multiple of stepm. */
726: int countcallfunc=0; /* Count the number of calls to func */
727: double jmean=1; /* Mean space between 2 waves */
728: double **matprod2(); /* test */
729: double **oldm, **newm, **savm; /* Working pointers to matrices */
730: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
731: /*FILE *fic ; */ /* Used in readdata only */
732: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
733: FILE *ficlog, *ficrespow;
734: int globpr=0; /* Global variable for printing or not */
735: double fretone; /* Only one call to likelihood */
736: long ipmx=0; /* Number of contributions */
737: double sw; /* Sum of weights */
738: char filerespow[FILENAMELENGTH];
739: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
740: FILE *ficresilk;
741: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
742: FILE *ficresprobmorprev;
743: FILE *fichtm, *fichtmcov; /* Html File */
744: FILE *ficreseij;
745: char filerese[FILENAMELENGTH];
746: FILE *ficresstdeij;
747: char fileresstde[FILENAMELENGTH];
748: FILE *ficrescveij;
749: char filerescve[FILENAMELENGTH];
750: FILE *ficresvij;
751: char fileresv[FILENAMELENGTH];
752: FILE *ficresvpl;
753: char fileresvpl[FILENAMELENGTH];
754: char title[MAXLINE];
755: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
756: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
757: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
758: char command[FILENAMELENGTH];
759: int outcmd=0;
760:
761: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
762:
763: char filelog[FILENAMELENGTH]; /* Log file */
764: char filerest[FILENAMELENGTH];
765: char fileregp[FILENAMELENGTH];
766: char popfile[FILENAMELENGTH];
767:
768: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
769:
770: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
771: /* struct timezone tzp; */
772: /* extern int gettimeofday(); */
773: struct tm tml, *gmtime(), *localtime();
774:
775: extern time_t time();
776:
777: struct tm start_time, end_time, curr_time, last_time, forecast_time;
778: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
779: struct tm tm;
780:
781: char strcurr[80], strfor[80];
782:
783: char *endptr;
784: long lval;
785: double dval;
786:
787: #define NR_END 1
788: #define FREE_ARG char*
789: #define FTOL 1.0e-10
790:
791: #define NRANSI
792: #define ITMAX 200
793:
794: #define TOL 2.0e-4
795:
796: #define CGOLD 0.3819660
797: #define ZEPS 1.0e-10
798: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
799:
800: #define GOLD 1.618034
801: #define GLIMIT 100.0
802: #define TINY 1.0e-20
803:
804: static double maxarg1,maxarg2;
805: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
806: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
807:
808: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
809: #define rint(a) floor(a+0.5)
810: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
811: #define mytinydouble 1.0e-16
812: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
813: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
814: /* static double dsqrarg; */
815: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
816: static double sqrarg;
817: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
818: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
819: int agegomp= AGEGOMP;
820:
821: int imx;
822: int stepm=1;
823: /* Stepm, step in month: minimum step interpolation*/
824:
825: int estepm;
826: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
827:
828: int m,nb;
829: long *num;
830: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
831: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
832: double **pmmij, ***probs;
833: double *ageexmed,*agecens;
834: double dateintmean=0;
835:
836: double *weight;
837: int **s; /* Status */
838: double *agedc;
839: double **covar; /**< covar[j,i], value of jth covariate for individual i,
840: * covar=matrix(0,NCOVMAX,1,n);
841: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
842: double idx;
843: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
844: int *Ndum; /** Freq of modality (tricode */
845: int **codtab; /**< codtab=imatrix(1,100,1,10); */
846: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
847: double *lsurv, *lpop, *tpop;
848:
849: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
850: double ftolhess; /**< Tolerance for computing hessian */
851:
852: /**************** split *************************/
853: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
854: {
855: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
856: the name of the file (name), its extension only (ext) and its first part of the name (finame)
857: */
858: char *ss; /* pointer */
859: int l1=0, l2=0; /* length counters */
860:
861: l1 = strlen(path ); /* length of path */
862: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
863: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
864: if ( ss == NULL ) { /* no directory, so determine current directory */
865: strcpy( name, path ); /* we got the fullname name because no directory */
866: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
867: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
868: /* get current working directory */
869: /* extern char* getcwd ( char *buf , int len);*/
870: #ifdef WIN32
871: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
872: #else
873: if (getcwd(dirc, FILENAME_MAX) == NULL) {
874: #endif
875: return( GLOCK_ERROR_GETCWD );
876: }
877: /* got dirc from getcwd*/
878: printf(" DIRC = %s \n",dirc);
879: } else { /* strip direcotry from path */
880: ss++; /* after this, the filename */
881: l2 = strlen( ss ); /* length of filename */
882: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
883: strcpy( name, ss ); /* save file name */
884: strncpy( dirc, path, l1 - l2 ); /* now the directory */
885: dirc[l1-l2] = '\0'; /* add zero */
886: printf(" DIRC2 = %s \n",dirc);
887: }
888: /* We add a separator at the end of dirc if not exists */
889: l1 = strlen( dirc ); /* length of directory */
890: if( dirc[l1-1] != DIRSEPARATOR ){
891: dirc[l1] = DIRSEPARATOR;
892: dirc[l1+1] = 0;
893: printf(" DIRC3 = %s \n",dirc);
894: }
895: ss = strrchr( name, '.' ); /* find last / */
896: if (ss >0){
897: ss++;
898: strcpy(ext,ss); /* save extension */
899: l1= strlen( name);
900: l2= strlen(ss)+1;
901: strncpy( finame, name, l1-l2);
902: finame[l1-l2]= 0;
903: }
904:
905: return( 0 ); /* we're done */
906: }
907:
908:
909: /******************************************/
910:
911: void replace_back_to_slash(char *s, char*t)
912: {
913: int i;
914: int lg=0;
915: i=0;
916: lg=strlen(t);
917: for(i=0; i<= lg; i++) {
918: (s[i] = t[i]);
919: if (t[i]== '\\') s[i]='/';
920: }
921: }
922:
923: char *trimbb(char *out, char *in)
924: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
925: char *s;
926: s=out;
927: while (*in != '\0'){
928: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
929: in++;
930: }
931: *out++ = *in++;
932: }
933: *out='\0';
934: return s;
935: }
936:
937: /* char *substrchaine(char *out, char *in, char *chain) */
938: /* { */
939: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
940: /* char *s, *t; */
941: /* t=in;s=out; */
942: /* while ((*in != *chain) && (*in != '\0')){ */
943: /* *out++ = *in++; */
944: /* } */
945:
946: /* /\* *in matches *chain *\/ */
947: /* while ((*in++ == *chain++) && (*in != '\0')){ */
948: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
949: /* } */
950: /* in--; chain--; */
951: /* while ( (*in != '\0')){ */
952: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
953: /* *out++ = *in++; */
954: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
955: /* } */
956: /* *out='\0'; */
957: /* out=s; */
958: /* return out; */
959: /* } */
960: char *substrchaine(char *out, char *in, char *chain)
961: {
962: /* Substract chain 'chain' from 'in', return and output 'out' */
963: /* in="V1+V1*age+age*age+V2", chain="age*age" */
964:
965: char *strloc;
966:
967: strcpy (out, in);
968: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
969: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
970: if(strloc != NULL){
971: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
972: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
973: /* strcpy (strloc, strloc +strlen(chain));*/
974: }
975: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
976: return out;
977: }
978:
979:
980: char *cutl(char *blocc, char *alocc, char *in, char occ)
981: {
982: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
983: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
984: gives blocc="abcdef" and alocc="ghi2j".
985: If occ is not found blocc is null and alocc is equal to in. Returns blocc
986: */
987: char *s, *t;
988: t=in;s=in;
989: while ((*in != occ) && (*in != '\0')){
990: *alocc++ = *in++;
991: }
992: if( *in == occ){
993: *(alocc)='\0';
994: s=++in;
995: }
996:
997: if (s == t) {/* occ not found */
998: *(alocc-(in-s))='\0';
999: in=s;
1000: }
1001: while ( *in != '\0'){
1002: *blocc++ = *in++;
1003: }
1004:
1005: *blocc='\0';
1006: return t;
1007: }
1008: char *cutv(char *blocc, char *alocc, char *in, char occ)
1009: {
1010: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1011: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1012: gives blocc="abcdef2ghi" and alocc="j".
1013: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1014: */
1015: char *s, *t;
1016: t=in;s=in;
1017: while (*in != '\0'){
1018: while( *in == occ){
1019: *blocc++ = *in++;
1020: s=in;
1021: }
1022: *blocc++ = *in++;
1023: }
1024: if (s == t) /* occ not found */
1025: *(blocc-(in-s))='\0';
1026: else
1027: *(blocc-(in-s)-1)='\0';
1028: in=s;
1029: while ( *in != '\0'){
1030: *alocc++ = *in++;
1031: }
1032:
1033: *alocc='\0';
1034: return s;
1035: }
1036:
1037: int nbocc(char *s, char occ)
1038: {
1039: int i,j=0;
1040: int lg=20;
1041: i=0;
1042: lg=strlen(s);
1043: for(i=0; i<= lg; i++) {
1044: if (s[i] == occ ) j++;
1045: }
1046: return j;
1047: }
1048:
1049: /* void cutv(char *u,char *v, char*t, char occ) */
1050: /* { */
1051: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1052: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1053: /* gives u="abcdef2ghi" and v="j" *\/ */
1054: /* int i,lg,j,p=0; */
1055: /* i=0; */
1056: /* lg=strlen(t); */
1057: /* for(j=0; j<=lg-1; j++) { */
1058: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1059: /* } */
1060:
1061: /* for(j=0; j<p; j++) { */
1062: /* (u[j] = t[j]); */
1063: /* } */
1064: /* u[p]='\0'; */
1065:
1066: /* for(j=0; j<= lg; j++) { */
1067: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1068: /* } */
1069: /* } */
1070:
1071: #ifdef _WIN32
1072: char * strsep(char **pp, const char *delim)
1073: {
1074: char *p, *q;
1075:
1076: if ((p = *pp) == NULL)
1077: return 0;
1078: if ((q = strpbrk (p, delim)) != NULL)
1079: {
1080: *pp = q + 1;
1081: *q = '\0';
1082: }
1083: else
1084: *pp = 0;
1085: return p;
1086: }
1087: #endif
1088:
1089: /********************** nrerror ********************/
1090:
1091: void nrerror(char error_text[])
1092: {
1093: fprintf(stderr,"ERREUR ...\n");
1094: fprintf(stderr,"%s\n",error_text);
1095: exit(EXIT_FAILURE);
1096: }
1097: /*********************** vector *******************/
1098: double *vector(int nl, int nh)
1099: {
1100: double *v;
1101: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1102: if (!v) nrerror("allocation failure in vector");
1103: return v-nl+NR_END;
1104: }
1105:
1106: /************************ free vector ******************/
1107: void free_vector(double*v, int nl, int nh)
1108: {
1109: free((FREE_ARG)(v+nl-NR_END));
1110: }
1111:
1112: /************************ivector *******************************/
1113: int *ivector(long nl,long nh)
1114: {
1115: int *v;
1116: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1117: if (!v) nrerror("allocation failure in ivector");
1118: return v-nl+NR_END;
1119: }
1120:
1121: /******************free ivector **************************/
1122: void free_ivector(int *v, long nl, long nh)
1123: {
1124: free((FREE_ARG)(v+nl-NR_END));
1125: }
1126:
1127: /************************lvector *******************************/
1128: long *lvector(long nl,long nh)
1129: {
1130: long *v;
1131: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1132: if (!v) nrerror("allocation failure in ivector");
1133: return v-nl+NR_END;
1134: }
1135:
1136: /******************free lvector **************************/
1137: void free_lvector(long *v, long nl, long nh)
1138: {
1139: free((FREE_ARG)(v+nl-NR_END));
1140: }
1141:
1142: /******************* imatrix *******************************/
1143: int **imatrix(long nrl, long nrh, long ncl, long nch)
1144: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1145: {
1146: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1147: int **m;
1148:
1149: /* allocate pointers to rows */
1150: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1151: if (!m) nrerror("allocation failure 1 in matrix()");
1152: m += NR_END;
1153: m -= nrl;
1154:
1155:
1156: /* allocate rows and set pointers to them */
1157: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1158: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1159: m[nrl] += NR_END;
1160: m[nrl] -= ncl;
1161:
1162: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1163:
1164: /* return pointer to array of pointers to rows */
1165: return m;
1166: }
1167:
1168: /****************** free_imatrix *************************/
1169: void free_imatrix(m,nrl,nrh,ncl,nch)
1170: int **m;
1171: long nch,ncl,nrh,nrl;
1172: /* free an int matrix allocated by imatrix() */
1173: {
1174: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1175: free((FREE_ARG) (m+nrl-NR_END));
1176: }
1177:
1178: /******************* matrix *******************************/
1179: double **matrix(long nrl, long nrh, long ncl, long nch)
1180: {
1181: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1182: double **m;
1183:
1184: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1185: if (!m) nrerror("allocation failure 1 in matrix()");
1186: m += NR_END;
1187: m -= nrl;
1188:
1189: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1190: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1191: m[nrl] += NR_END;
1192: m[nrl] -= ncl;
1193:
1194: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1195: return m;
1196: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1197: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1198: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1199: */
1200: }
1201:
1202: /*************************free matrix ************************/
1203: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1204: {
1205: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1206: free((FREE_ARG)(m+nrl-NR_END));
1207: }
1208:
1209: /******************* ma3x *******************************/
1210: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1211: {
1212: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1213: double ***m;
1214:
1215: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1216: if (!m) nrerror("allocation failure 1 in matrix()");
1217: m += NR_END;
1218: m -= nrl;
1219:
1220: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1221: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1222: m[nrl] += NR_END;
1223: m[nrl] -= ncl;
1224:
1225: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1226:
1227: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1228: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1229: m[nrl][ncl] += NR_END;
1230: m[nrl][ncl] -= nll;
1231: for (j=ncl+1; j<=nch; j++)
1232: m[nrl][j]=m[nrl][j-1]+nlay;
1233:
1234: for (i=nrl+1; i<=nrh; i++) {
1235: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1236: for (j=ncl+1; j<=nch; j++)
1237: m[i][j]=m[i][j-1]+nlay;
1238: }
1239: return m;
1240: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1241: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1242: */
1243: }
1244:
1245: /*************************free ma3x ************************/
1246: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1247: {
1248: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1249: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1250: free((FREE_ARG)(m+nrl-NR_END));
1251: }
1252:
1253: /*************** function subdirf ***********/
1254: char *subdirf(char fileres[])
1255: {
1256: /* Caution optionfilefiname is hidden */
1257: strcpy(tmpout,optionfilefiname);
1258: strcat(tmpout,"/"); /* Add to the right */
1259: strcat(tmpout,fileres);
1260: return tmpout;
1261: }
1262:
1263: /*************** function subdirf2 ***********/
1264: char *subdirf2(char fileres[], char *preop)
1265: {
1266:
1267: /* Caution optionfilefiname is hidden */
1268: strcpy(tmpout,optionfilefiname);
1269: strcat(tmpout,"/");
1270: strcat(tmpout,preop);
1271: strcat(tmpout,fileres);
1272: return tmpout;
1273: }
1274:
1275: /*************** function subdirf3 ***********/
1276: char *subdirf3(char fileres[], char *preop, char *preop2)
1277: {
1278:
1279: /* Caution optionfilefiname is hidden */
1280: strcpy(tmpout,optionfilefiname);
1281: strcat(tmpout,"/");
1282: strcat(tmpout,preop);
1283: strcat(tmpout,preop2);
1284: strcat(tmpout,fileres);
1285: return tmpout;
1286: }
1287:
1288: char *asc_diff_time(long time_sec, char ascdiff[])
1289: {
1290: long sec_left, days, hours, minutes;
1291: days = (time_sec) / (60*60*24);
1292: sec_left = (time_sec) % (60*60*24);
1293: hours = (sec_left) / (60*60) ;
1294: sec_left = (sec_left) %(60*60);
1295: minutes = (sec_left) /60;
1296: sec_left = (sec_left) % (60);
1297: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1298: return ascdiff;
1299: }
1300:
1301: /***************** f1dim *************************/
1302: extern int ncom;
1303: extern double *pcom,*xicom;
1304: extern double (*nrfunc)(double []);
1305:
1306: double f1dim(double x)
1307: {
1308: int j;
1309: double f;
1310: double *xt;
1311:
1312: xt=vector(1,ncom);
1313: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1314: f=(*nrfunc)(xt);
1315: free_vector(xt,1,ncom);
1316: return f;
1317: }
1318:
1319: /*****************brent *************************/
1320: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1321: {
1322: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1323: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1324: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1325: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1326: * returned function value.
1327: */
1328: int iter;
1329: double a,b,d,etemp;
1330: double fu=0,fv,fw,fx;
1331: double ftemp=0.;
1332: double p,q,r,tol1,tol2,u,v,w,x,xm;
1333: double e=0.0;
1334:
1335: a=(ax < cx ? ax : cx);
1336: b=(ax > cx ? ax : cx);
1337: x=w=v=bx;
1338: fw=fv=fx=(*f)(x);
1339: for (iter=1;iter<=ITMAX;iter++) {
1340: xm=0.5*(a+b);
1341: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1342: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1343: printf(".");fflush(stdout);
1344: fprintf(ficlog,".");fflush(ficlog);
1345: #ifdef DEBUGBRENT
1346: 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);
1347: 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);
1348: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1349: #endif
1350: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1351: *xmin=x;
1352: return fx;
1353: }
1354: ftemp=fu;
1355: if (fabs(e) > tol1) {
1356: r=(x-w)*(fx-fv);
1357: q=(x-v)*(fx-fw);
1358: p=(x-v)*q-(x-w)*r;
1359: q=2.0*(q-r);
1360: if (q > 0.0) p = -p;
1361: q=fabs(q);
1362: etemp=e;
1363: e=d;
1364: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1365: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1366: else {
1367: d=p/q;
1368: u=x+d;
1369: if (u-a < tol2 || b-u < tol2)
1370: d=SIGN(tol1,xm-x);
1371: }
1372: } else {
1373: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1374: }
1375: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1376: fu=(*f)(u);
1377: if (fu <= fx) {
1378: if (u >= x) a=x; else b=x;
1379: SHFT(v,w,x,u)
1380: SHFT(fv,fw,fx,fu)
1381: } else {
1382: if (u < x) a=u; else b=u;
1383: if (fu <= fw || w == x) {
1384: v=w;
1385: w=u;
1386: fv=fw;
1387: fw=fu;
1388: } else if (fu <= fv || v == x || v == w) {
1389: v=u;
1390: fv=fu;
1391: }
1392: }
1393: }
1394: nrerror("Too many iterations in brent");
1395: *xmin=x;
1396: return fx;
1397: }
1398:
1399: /****************** mnbrak ***********************/
1400:
1401: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1402: double (*func)(double))
1403: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1404: the downhill direction (defined by the function as evaluated at the initial points) and returns
1405: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1406: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1407: */
1408: double ulim,u,r,q, dum;
1409: double fu;
1410:
1411: double scale=10.;
1412: int iterscale=0;
1413:
1414: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1415: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1416:
1417:
1418: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1419: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1420: /* *bx = *ax - (*ax - *bx)/scale; */
1421: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1422: /* } */
1423:
1424: if (*fb > *fa) {
1425: SHFT(dum,*ax,*bx,dum)
1426: SHFT(dum,*fb,*fa,dum)
1427: }
1428: *cx=(*bx)+GOLD*(*bx-*ax);
1429: *fc=(*func)(*cx);
1430: #ifdef DEBUG
1431: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1432: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1433: #endif
1434: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1435: r=(*bx-*ax)*(*fb-*fc);
1436: q=(*bx-*cx)*(*fb-*fa);
1437: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1438: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1439: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1440: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1441: fu=(*func)(u);
1442: #ifdef DEBUG
1443: /* f(x)=A(x-u)**2+f(u) */
1444: double A, fparabu;
1445: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1446: fparabu= *fa - A*(*ax-u)*(*ax-u);
1447: 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);
1448: 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);
1449: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1450: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1451: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1452: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1453: #endif
1454: #ifdef MNBRAKORIGINAL
1455: #else
1456: /* if (fu > *fc) { */
1457: /* #ifdef DEBUG */
1458: /* printf("mnbrak4 fu > fc \n"); */
1459: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1460: /* #endif */
1461: /* /\* 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 *\\/ *\/ */
1462: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1463: /* dum=u; /\* Shifting c and u *\/ */
1464: /* u = *cx; */
1465: /* *cx = dum; */
1466: /* dum = fu; */
1467: /* fu = *fc; */
1468: /* *fc =dum; */
1469: /* } else { /\* end *\/ */
1470: /* #ifdef DEBUG */
1471: /* printf("mnbrak3 fu < fc \n"); */
1472: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1473: /* #endif */
1474: /* dum=u; /\* Shifting c and u *\/ */
1475: /* u = *cx; */
1476: /* *cx = dum; */
1477: /* dum = fu; */
1478: /* fu = *fc; */
1479: /* *fc =dum; */
1480: /* } */
1481: #ifdef DEBUG
1482: printf("mnbrak34 fu < or >= fc \n");
1483: fprintf(ficlog, "mnbrak34 fu < fc\n");
1484: #endif
1485: dum=u; /* Shifting c and u */
1486: u = *cx;
1487: *cx = dum;
1488: dum = fu;
1489: fu = *fc;
1490: *fc =dum;
1491: #endif
1492: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1493: #ifdef DEBUG
1494: printf("mnbrak2 u after c but before ulim\n");
1495: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1496: #endif
1497: fu=(*func)(u);
1498: if (fu < *fc) {
1499: #ifdef DEBUG
1500: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1501: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1502: #endif
1503: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1504: SHFT(*fb,*fc,fu,(*func)(u))
1505: }
1506: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1507: #ifdef DEBUG
1508: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1509: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1510: #endif
1511: u=ulim;
1512: fu=(*func)(u);
1513: } else { /* u could be left to b (if r > q parabola has a maximum) */
1514: #ifdef DEBUG
1515: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1516: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1517: #endif
1518: u=(*cx)+GOLD*(*cx-*bx);
1519: fu=(*func)(u);
1520: } /* end tests */
1521: SHFT(*ax,*bx,*cx,u)
1522: SHFT(*fa,*fb,*fc,fu)
1523: #ifdef DEBUG
1524: 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);
1525: 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);
1526: #endif
1527: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1528: }
1529:
1530: /*************** linmin ************************/
1531: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1532: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1533: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1534: the value of func at the returned location p . This is actually all accomplished by calling the
1535: routines mnbrak and brent .*/
1536: int ncom;
1537: double *pcom,*xicom;
1538: double (*nrfunc)(double []);
1539:
1540: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1541: {
1542: double brent(double ax, double bx, double cx,
1543: double (*f)(double), double tol, double *xmin);
1544: double f1dim(double x);
1545: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1546: double *fc, double (*func)(double));
1547: int j;
1548: double xx,xmin,bx,ax;
1549: double fx,fb,fa;
1550:
1551: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1552:
1553: ncom=n;
1554: pcom=vector(1,n);
1555: xicom=vector(1,n);
1556: nrfunc=func;
1557: for (j=1;j<=n;j++) {
1558: pcom[j]=p[j];
1559: xicom[j]=xi[j];
1560: }
1561:
1562: axs=0.0;
1563: xxss=1; /* 1 and using scale */
1564: xxs=1;
1565: do{
1566: ax=0.;
1567: xx= xxs;
1568: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1569: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1570: /* 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)) */
1571: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1572: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1573: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1574: /* 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]]*/
1575: if (fx != fx){
1576: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1577: 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);
1578: }
1579: }while(fx != fx);
1580:
1581: #ifdef DEBUGLINMIN
1582: 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);
1583: #endif
1584: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1585: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1586: /* fmin = f(p[j] + xmin * xi[j]) */
1587: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1588: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1589: #ifdef DEBUG
1590: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1591: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1592: #endif
1593: #ifdef DEBUGLINMIN
1594: printf("linmin end ");
1595: #endif
1596: for (j=1;j<=n;j++) {
1597: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1598: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1599: /* if(xxs <1.0) */
1600: /* 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 ); */
1601: p[j] += xi[j]; /* Parameters values are updated accordingly */
1602: }
1603: /* printf("\n"); */
1604: #ifdef DEBUGLINMIN
1605: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1606: for (j=1;j<=n;j++) {
1607: printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
1608: if(j % ncovmodel == 0)
1609: printf("\n");
1610: }
1611: #endif
1612: free_vector(xicom,1,n);
1613: free_vector(pcom,1,n);
1614: }
1615:
1616:
1617: /*************** powell ************************/
1618: /*
1619: Minimization of a function func of n variables. Input consists of an initial starting point
1620: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1621: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1622: such that failure to decrease by more than this amount on one iteration signals doneness. On
1623: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1624: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1625: */
1626: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1627: double (*func)(double []))
1628: {
1629: void linmin(double p[], double xi[], int n, double *fret,
1630: double (*func)(double []));
1631: int i,ibig,j;
1632: double del,t,*pt,*ptt,*xit;
1633: double directest;
1634: double fp,fptt;
1635: double *xits;
1636: int niterf, itmp;
1637:
1638: pt=vector(1,n);
1639: ptt=vector(1,n);
1640: xit=vector(1,n);
1641: xits=vector(1,n);
1642: *fret=(*func)(p);
1643: for (j=1;j<=n;j++) pt[j]=p[j];
1644: rcurr_time = time(NULL);
1645: for (*iter=1;;++(*iter)) {
1646: fp=(*fret); /* From former iteration or initial value */
1647: ibig=0;
1648: del=0.0;
1649: rlast_time=rcurr_time;
1650: /* (void) gettimeofday(&curr_time,&tzp); */
1651: rcurr_time = time(NULL);
1652: curr_time = *localtime(&rcurr_time);
1653: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1654: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1655: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1656: for (i=1;i<=n;i++) {
1657: printf(" %d %.12f",i, p[i]);
1658: fprintf(ficlog," %d %.12lf",i, p[i]);
1659: fprintf(ficrespow," %.12lf", p[i]);
1660: }
1661: printf("\n");
1662: fprintf(ficlog,"\n");
1663: fprintf(ficrespow,"\n");fflush(ficrespow);
1664: if(*iter <=3){
1665: tml = *localtime(&rcurr_time);
1666: strcpy(strcurr,asctime(&tml));
1667: rforecast_time=rcurr_time;
1668: itmp = strlen(strcurr);
1669: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1670: strcurr[itmp-1]='\0';
1671: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1672: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1673: for(niterf=10;niterf<=30;niterf+=10){
1674: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1675: forecast_time = *localtime(&rforecast_time);
1676: strcpy(strfor,asctime(&forecast_time));
1677: itmp = strlen(strfor);
1678: if(strfor[itmp-1]=='\n')
1679: strfor[itmp-1]='\0';
1680: 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);
1681: 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);
1682: }
1683: }
1684: for (i=1;i<=n;i++) { /* For each direction i */
1685: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1686: fptt=(*fret);
1687: #ifdef DEBUG
1688: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1689: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1690: #endif
1691: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1692: fprintf(ficlog,"%d",i);fflush(ficlog);
1693: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1694: /* Outputs are fret(new point p) p is updated and xit rescaled */
1695: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1696: /* because that direction will be replaced unless the gain del is small */
1697: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1698: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1699: /* with the new direction. */
1700: del=fabs(fptt-(*fret));
1701: ibig=i;
1702: }
1703: #ifdef DEBUG
1704: printf("%d %.12e",i,(*fret));
1705: fprintf(ficlog,"%d %.12e",i,(*fret));
1706: for (j=1;j<=n;j++) {
1707: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1708: printf(" x(%d)=%.12e",j,xit[j]);
1709: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1710: }
1711: for(j=1;j<=n;j++) {
1712: printf(" p(%d)=%.12e",j,p[j]);
1713: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1714: }
1715: printf("\n");
1716: fprintf(ficlog,"\n");
1717: #endif
1718: } /* end loop on each direction i */
1719: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1720: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1721: /* New value of last point Pn is not computed, P(n-1) */
1722: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1723: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1724: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1725: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1726: /* decreased of more than 3.84 */
1727: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1728: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1729: /* By adding 10 parameters more the gain should be 18.31 */
1730:
1731: /* Starting the program with initial values given by a former maximization will simply change */
1732: /* the scales of the directions and the directions, because the are reset to canonical directions */
1733: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1734: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1735: #ifdef DEBUG
1736: int k[2],l;
1737: k[0]=1;
1738: k[1]=-1;
1739: printf("Max: %.12e",(*func)(p));
1740: fprintf(ficlog,"Max: %.12e",(*func)(p));
1741: for (j=1;j<=n;j++) {
1742: printf(" %.12e",p[j]);
1743: fprintf(ficlog," %.12e",p[j]);
1744: }
1745: printf("\n");
1746: fprintf(ficlog,"\n");
1747: for(l=0;l<=1;l++) {
1748: for (j=1;j<=n;j++) {
1749: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1750: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1751: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1752: }
1753: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1754: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1755: }
1756: #endif
1757:
1758:
1759: free_vector(xit,1,n);
1760: free_vector(xits,1,n);
1761: free_vector(ptt,1,n);
1762: free_vector(pt,1,n);
1763: return;
1764: }
1765: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1766: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1767: ptt[j]=2.0*p[j]-pt[j];
1768: xit[j]=p[j]-pt[j];
1769: pt[j]=p[j];
1770: }
1771: fptt=(*func)(ptt); /* f_3 */
1772: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1773: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1774: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1775: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1776: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1777: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1778: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1779: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1780: #ifdef NRCORIGINAL
1781: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1782: #else
1783: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1784: t= t- del*SQR(fp-fptt);
1785: #endif
1786: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1787: #ifdef DEBUG
1788: 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);
1789: 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);
1790: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1791: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1792: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1793: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1794: 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);
1795: 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);
1796: #endif
1797: #ifdef POWELLORIGINAL
1798: if (t < 0.0) { /* Then we use it for new direction */
1799: #else
1800: if (directest*t < 0.0) { /* Contradiction between both tests */
1801: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1802: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1803: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1804: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1805: }
1806: if (directest < 0.0) { /* Then we use it for new direction */
1807: #endif
1808: #ifdef DEBUGLINMIN
1809: printf("Before linmin in direction P%d-P0\n",n);
1810: for (j=1;j<=n;j++) {
1811: printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1812: if(j % ncovmodel == 0)
1813: printf("\n");
1814: }
1815: #endif
1816: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1817: #ifdef DEBUGLINMIN
1818: for (j=1;j<=n;j++) {
1819: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1820: if(j % ncovmodel == 0)
1821: printf("\n");
1822: }
1823: #endif
1824: for (j=1;j<=n;j++) {
1825: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1826: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1827: }
1828: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1829: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1830:
1831: #ifdef DEBUG
1832: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1833: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1834: for(j=1;j<=n;j++){
1835: printf(" %.12e",xit[j]);
1836: fprintf(ficlog," %.12e",xit[j]);
1837: }
1838: printf("\n");
1839: fprintf(ficlog,"\n");
1840: #endif
1841: } /* end of t negative */
1842: } /* end if (fptt < fp) */
1843: }
1844: }
1845:
1846: /**** Prevalence limit (stable or period prevalence) ****************/
1847:
1848: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1849: {
1850: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1851: matrix by transitions matrix until convergence is reached */
1852:
1853: int i, ii,j,k;
1854: double min, max, maxmin, maxmax,sumnew=0.;
1855: /* double **matprod2(); */ /* test */
1856: double **out, cov[NCOVMAX+1], **pmij();
1857: double **newm;
1858: double agefin, delaymax=50 ; /* Max number of years to converge */
1859:
1860: for (ii=1;ii<=nlstate+ndeath;ii++)
1861: for (j=1;j<=nlstate+ndeath;j++){
1862: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1863: }
1864:
1865: cov[1]=1.;
1866:
1867: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1868: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1869: newm=savm;
1870: /* Covariates have to be included here again */
1871: cov[2]=agefin;
1872: if(nagesqr==1)
1873: cov[3]= agefin*agefin;;
1874: for (k=1; k<=cptcovn;k++) {
1875: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1876: /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
1877: }
1878: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1879: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1880: for (k=1; k<=cptcovprod;k++) /* Useless */
1881: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1882:
1883: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1884: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1885: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1886: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1887: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1888: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1889:
1890: savm=oldm;
1891: oldm=newm;
1892: maxmax=0.;
1893: for(j=1;j<=nlstate;j++){
1894: min=1.;
1895: max=0.;
1896: for(i=1; i<=nlstate; i++) {
1897: sumnew=0;
1898: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1899: prlim[i][j]= newm[i][j]/(1-sumnew);
1900: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1901: max=FMAX(max,prlim[i][j]);
1902: min=FMIN(min,prlim[i][j]);
1903: }
1904: maxmin=max-min;
1905: maxmax=FMAX(maxmax,maxmin);
1906: } /* j loop */
1907: if(maxmax < ftolpl){
1908: return prlim;
1909: }
1910: } /* age loop */
1911: return prlim; /* should not reach here */
1912: }
1913:
1914: /*************** transition probabilities ***************/
1915:
1916: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1917: {
1918: /* According to parameters values stored in x and the covariate's values stored in cov,
1919: computes the probability to be observed in state j being in state i by appying the
1920: model to the ncovmodel covariates (including constant and age).
1921: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1922: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1923: ncth covariate in the global vector x is given by the formula:
1924: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1925: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1926: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1927: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1928: Outputs ps[i][j] the probability to be observed in j being in j according to
1929: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1930: */
1931: double s1, lnpijopii;
1932: /*double t34;*/
1933: int i,j, nc, ii, jj;
1934:
1935: for(i=1; i<= nlstate; i++){
1936: for(j=1; j<i;j++){
1937: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1938: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1939: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1940: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1941: }
1942: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1943: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1944: }
1945: for(j=i+1; j<=nlstate+ndeath;j++){
1946: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1947: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1948: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1949: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1950: }
1951: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1952: }
1953: }
1954:
1955: for(i=1; i<= nlstate; i++){
1956: s1=0;
1957: for(j=1; j<i; j++){
1958: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1959: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1960: }
1961: for(j=i+1; j<=nlstate+ndeath; j++){
1962: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1963: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1964: }
1965: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1966: ps[i][i]=1./(s1+1.);
1967: /* Computing other pijs */
1968: for(j=1; j<i; j++)
1969: ps[i][j]= exp(ps[i][j])*ps[i][i];
1970: for(j=i+1; j<=nlstate+ndeath; j++)
1971: ps[i][j]= exp(ps[i][j])*ps[i][i];
1972: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1973: } /* end i */
1974:
1975: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1976: for(jj=1; jj<= nlstate+ndeath; jj++){
1977: ps[ii][jj]=0;
1978: ps[ii][ii]=1;
1979: }
1980: }
1981:
1982:
1983: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1984: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1985: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1986: /* } */
1987: /* printf("\n "); */
1988: /* } */
1989: /* printf("\n ");printf("%lf ",cov[2]);*/
1990: /*
1991: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1992: goto end;*/
1993: return ps;
1994: }
1995:
1996: /**************** Product of 2 matrices ******************/
1997:
1998: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1999: {
2000: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2001: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2002: /* in, b, out are matrice of pointers which should have been initialized
2003: before: only the contents of out is modified. The function returns
2004: a pointer to pointers identical to out */
2005: int i, j, k;
2006: for(i=nrl; i<= nrh; i++)
2007: for(k=ncolol; k<=ncoloh; k++){
2008: out[i][k]=0.;
2009: for(j=ncl; j<=nch; j++)
2010: out[i][k] +=in[i][j]*b[j][k];
2011: }
2012: return out;
2013: }
2014:
2015:
2016: /************* Higher Matrix Product ***************/
2017:
2018: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2019: {
2020: /* Computes the transition matrix starting at age 'age' over
2021: 'nhstepm*hstepm*stepm' months (i.e. until
2022: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2023: nhstepm*hstepm matrices.
2024: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2025: (typically every 2 years instead of every month which is too big
2026: for the memory).
2027: Model is determined by parameters x and covariates have to be
2028: included manually here.
2029:
2030: */
2031:
2032: int i, j, d, h, k;
2033: double **out, cov[NCOVMAX+1];
2034: double **newm;
2035: double agexact;
2036:
2037: /* Hstepm could be zero and should return the unit matrix */
2038: for (i=1;i<=nlstate+ndeath;i++)
2039: for (j=1;j<=nlstate+ndeath;j++){
2040: oldm[i][j]=(i==j ? 1.0 : 0.0);
2041: po[i][j][0]=(i==j ? 1.0 : 0.0);
2042: }
2043: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2044: for(h=1; h <=nhstepm; h++){
2045: for(d=1; d <=hstepm; d++){
2046: newm=savm;
2047: /* Covariates have to be included here again */
2048: cov[1]=1.;
2049: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2050: cov[2]=agexact;
2051: if(nagesqr==1)
2052: cov[3]= agexact*agexact;
2053: for (k=1; k<=cptcovn;k++)
2054: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
2055: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2056: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2057: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
2058: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2059: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
2060:
2061:
2062: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2063: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2064: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2065: pmij(pmmij,cov,ncovmodel,x,nlstate));
2066: savm=oldm;
2067: oldm=newm;
2068: }
2069: for(i=1; i<=nlstate+ndeath; i++)
2070: for(j=1;j<=nlstate+ndeath;j++) {
2071: po[i][j][h]=newm[i][j];
2072: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2073: }
2074: /*printf("h=%d ",h);*/
2075: } /* end h */
2076: /* printf("\n H=%d \n",h); */
2077: return po;
2078: }
2079:
2080: #ifdef NLOPT
2081: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2082: double fret;
2083: double *xt;
2084: int j;
2085: myfunc_data *d2 = (myfunc_data *) pd;
2086: /* xt = (p1-1); */
2087: xt=vector(1,n);
2088: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2089:
2090: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2091: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2092: printf("Function = %.12lf ",fret);
2093: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2094: printf("\n");
2095: free_vector(xt,1,n);
2096: return fret;
2097: }
2098: #endif
2099:
2100: /*************** log-likelihood *************/
2101: double func( double *x)
2102: {
2103: int i, ii, j, k, mi, d, kk;
2104: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2105: double **out;
2106: double sw; /* Sum of weights */
2107: double lli; /* Individual log likelihood */
2108: int s1, s2;
2109: double bbh, survp;
2110: long ipmx;
2111: double agexact;
2112: /*extern weight */
2113: /* We are differentiating ll according to initial status */
2114: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2115: /*for(i=1;i<imx;i++)
2116: printf(" %d\n",s[4][i]);
2117: */
2118:
2119: ++countcallfunc;
2120:
2121: cov[1]=1.;
2122:
2123: for(k=1; k<=nlstate; k++) ll[k]=0.;
2124:
2125: if(mle==1){
2126: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2127: /* Computes the values of the ncovmodel covariates of the model
2128: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2129: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2130: to be observed in j being in i according to the model.
2131: */
2132: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2133: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2134: }
2135: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2136: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2137: has been calculated etc */
2138: for(mi=1; mi<= wav[i]-1; mi++){
2139: for (ii=1;ii<=nlstate+ndeath;ii++)
2140: for (j=1;j<=nlstate+ndeath;j++){
2141: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2142: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2143: }
2144: for(d=0; d<dh[mi][i]; d++){
2145: newm=savm;
2146: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2147: cov[2]=agexact;
2148: if(nagesqr==1)
2149: cov[3]= agexact*agexact;
2150: for (kk=1; kk<=cptcovage;kk++) {
2151: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2152: }
2153: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2154: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2155: savm=oldm;
2156: oldm=newm;
2157: } /* end mult */
2158:
2159: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2160: /* But now since version 0.9 we anticipate for bias at large stepm.
2161: * If stepm is larger than one month (smallest stepm) and if the exact delay
2162: * (in months) between two waves is not a multiple of stepm, we rounded to
2163: * the nearest (and in case of equal distance, to the lowest) interval but now
2164: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2165: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2166: * probability in order to take into account the bias as a fraction of the way
2167: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2168: * -stepm/2 to stepm/2 .
2169: * For stepm=1 the results are the same as for previous versions of Imach.
2170: * For stepm > 1 the results are less biased than in previous versions.
2171: */
2172: s1=s[mw[mi][i]][i];
2173: s2=s[mw[mi+1][i]][i];
2174: bbh=(double)bh[mi][i]/(double)stepm;
2175: /* bias bh is positive if real duration
2176: * is higher than the multiple of stepm and negative otherwise.
2177: */
2178: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2179: if( s2 > nlstate){
2180: /* i.e. if s2 is a death state and if the date of death is known
2181: then the contribution to the likelihood is the probability to
2182: die between last step unit time and current step unit time,
2183: which is also equal to probability to die before dh
2184: minus probability to die before dh-stepm .
2185: In version up to 0.92 likelihood was computed
2186: as if date of death was unknown. Death was treated as any other
2187: health state: the date of the interview describes the actual state
2188: and not the date of a change in health state. The former idea was
2189: to consider that at each interview the state was recorded
2190: (healthy, disable or death) and IMaCh was corrected; but when we
2191: introduced the exact date of death then we should have modified
2192: the contribution of an exact death to the likelihood. This new
2193: contribution is smaller and very dependent of the step unit
2194: stepm. It is no more the probability to die between last interview
2195: and month of death but the probability to survive from last
2196: interview up to one month before death multiplied by the
2197: probability to die within a month. Thanks to Chris
2198: Jackson for correcting this bug. Former versions increased
2199: mortality artificially. The bad side is that we add another loop
2200: which slows down the processing. The difference can be up to 10%
2201: lower mortality.
2202: */
2203: /* If, at the beginning of the maximization mostly, the
2204: cumulative probability or probability to be dead is
2205: constant (ie = 1) over time d, the difference is equal to
2206: 0. out[s1][3] = savm[s1][3]: probability, being at state
2207: s1 at precedent wave, to be dead a month before current
2208: wave is equal to probability, being at state s1 at
2209: precedent wave, to be dead at mont of the current
2210: wave. Then the observed probability (that this person died)
2211: is null according to current estimated parameter. In fact,
2212: it should be very low but not zero otherwise the log go to
2213: infinity.
2214: */
2215: /* #ifdef INFINITYORIGINAL */
2216: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2217: /* #else */
2218: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2219: /* lli=log(mytinydouble); */
2220: /* else */
2221: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2222: /* #endif */
2223: lli=log(out[s1][s2] - savm[s1][s2]);
2224:
2225: } else if (s2==-2) {
2226: for (j=1,survp=0. ; j<=nlstate; j++)
2227: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2228: /*survp += out[s1][j]; */
2229: lli= log(survp);
2230: }
2231:
2232: else if (s2==-4) {
2233: for (j=3,survp=0. ; j<=nlstate; j++)
2234: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2235: lli= log(survp);
2236: }
2237:
2238: else if (s2==-5) {
2239: for (j=1,survp=0. ; j<=2; j++)
2240: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2241: lli= log(survp);
2242: }
2243:
2244: else{
2245: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2246: /* 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 */
2247: }
2248: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2249: /*if(lli ==000.0)*/
2250: /*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); */
2251: ipmx +=1;
2252: sw += weight[i];
2253: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2254: /* if (lli < log(mytinydouble)){ */
2255: /* 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); */
2256: /* 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]); */
2257: /* } */
2258: } /* end of wave */
2259: } /* end of individual */
2260: } else if(mle==2){
2261: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2262: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2263: for(mi=1; mi<= wav[i]-1; mi++){
2264: for (ii=1;ii<=nlstate+ndeath;ii++)
2265: for (j=1;j<=nlstate+ndeath;j++){
2266: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2267: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2268: }
2269: for(d=0; d<=dh[mi][i]; d++){
2270: newm=savm;
2271: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2272: cov[2]=agexact;
2273: if(nagesqr==1)
2274: cov[3]= agexact*agexact;
2275: for (kk=1; kk<=cptcovage;kk++) {
2276: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2277: }
2278: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2279: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2280: savm=oldm;
2281: oldm=newm;
2282: } /* end mult */
2283:
2284: s1=s[mw[mi][i]][i];
2285: s2=s[mw[mi+1][i]][i];
2286: bbh=(double)bh[mi][i]/(double)stepm;
2287: 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 */
2288: ipmx +=1;
2289: sw += weight[i];
2290: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2291: } /* end of wave */
2292: } /* end of individual */
2293: } else if(mle==3){ /* exponential inter-extrapolation */
2294: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2295: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2296: for(mi=1; mi<= wav[i]-1; mi++){
2297: for (ii=1;ii<=nlstate+ndeath;ii++)
2298: for (j=1;j<=nlstate+ndeath;j++){
2299: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2300: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2301: }
2302: for(d=0; d<dh[mi][i]; d++){
2303: newm=savm;
2304: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2305: cov[2]=agexact;
2306: if(nagesqr==1)
2307: cov[3]= agexact*agexact;
2308: for (kk=1; kk<=cptcovage;kk++) {
2309: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2310: }
2311: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2312: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2313: savm=oldm;
2314: oldm=newm;
2315: } /* end mult */
2316:
2317: s1=s[mw[mi][i]][i];
2318: s2=s[mw[mi+1][i]][i];
2319: bbh=(double)bh[mi][i]/(double)stepm;
2320: 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 */
2321: ipmx +=1;
2322: sw += weight[i];
2323: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2324: } /* end of wave */
2325: } /* end of individual */
2326: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2327: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2328: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2329: for(mi=1; mi<= wav[i]-1; mi++){
2330: for (ii=1;ii<=nlstate+ndeath;ii++)
2331: for (j=1;j<=nlstate+ndeath;j++){
2332: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2333: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2334: }
2335: for(d=0; d<dh[mi][i]; d++){
2336: newm=savm;
2337: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2338: cov[2]=agexact;
2339: if(nagesqr==1)
2340: cov[3]= agexact*agexact;
2341: for (kk=1; kk<=cptcovage;kk++) {
2342: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2343: }
2344:
2345: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2346: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2347: savm=oldm;
2348: oldm=newm;
2349: } /* end mult */
2350:
2351: s1=s[mw[mi][i]][i];
2352: s2=s[mw[mi+1][i]][i];
2353: if( s2 > nlstate){
2354: lli=log(out[s1][s2] - savm[s1][s2]);
2355: }else{
2356: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2357: }
2358: ipmx +=1;
2359: sw += weight[i];
2360: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2361: /* 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]); */
2362: } /* end of wave */
2363: } /* end of individual */
2364: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2365: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2366: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2367: for(mi=1; mi<= wav[i]-1; mi++){
2368: for (ii=1;ii<=nlstate+ndeath;ii++)
2369: for (j=1;j<=nlstate+ndeath;j++){
2370: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2371: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2372: }
2373: for(d=0; d<dh[mi][i]; d++){
2374: newm=savm;
2375: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2376: cov[2]=agexact;
2377: if(nagesqr==1)
2378: cov[3]= agexact*agexact;
2379: for (kk=1; kk<=cptcovage;kk++) {
2380: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2381: }
2382:
2383: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2384: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2385: savm=oldm;
2386: oldm=newm;
2387: } /* end mult */
2388:
2389: s1=s[mw[mi][i]][i];
2390: s2=s[mw[mi+1][i]][i];
2391: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2392: ipmx +=1;
2393: sw += weight[i];
2394: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2395: /*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]);*/
2396: } /* end of wave */
2397: } /* end of individual */
2398: } /* End of if */
2399: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2400: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2401: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2402: return -l;
2403: }
2404:
2405: /*************** log-likelihood *************/
2406: double funcone( double *x)
2407: {
2408: /* Same as likeli but slower because of a lot of printf and if */
2409: int i, ii, j, k, mi, d, kk;
2410: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2411: double **out;
2412: double lli; /* Individual log likelihood */
2413: double llt;
2414: int s1, s2;
2415: double bbh, survp;
2416: double agexact;
2417: /*extern weight */
2418: /* We are differentiating ll according to initial status */
2419: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2420: /*for(i=1;i<imx;i++)
2421: printf(" %d\n",s[4][i]);
2422: */
2423: cov[1]=1.;
2424:
2425: for(k=1; k<=nlstate; k++) ll[k]=0.;
2426:
2427: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2428: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2429: for(mi=1; mi<= wav[i]-1; mi++){
2430: for (ii=1;ii<=nlstate+ndeath;ii++)
2431: for (j=1;j<=nlstate+ndeath;j++){
2432: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2433: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2434: }
2435: for(d=0; d<dh[mi][i]; d++){
2436: newm=savm;
2437: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2438: cov[2]=agexact;
2439: if(nagesqr==1)
2440: cov[3]= agexact*agexact;
2441: for (kk=1; kk<=cptcovage;kk++) {
2442: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2443: }
2444:
2445: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2446: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2447: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2448: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2449: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2450: savm=oldm;
2451: oldm=newm;
2452: } /* end mult */
2453:
2454: s1=s[mw[mi][i]][i];
2455: s2=s[mw[mi+1][i]][i];
2456: bbh=(double)bh[mi][i]/(double)stepm;
2457: /* bias is positive if real duration
2458: * is higher than the multiple of stepm and negative otherwise.
2459: */
2460: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2461: lli=log(out[s1][s2] - savm[s1][s2]);
2462: } else if (s2==-2) {
2463: for (j=1,survp=0. ; j<=nlstate; j++)
2464: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2465: lli= log(survp);
2466: }else if (mle==1){
2467: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2468: } else if(mle==2){
2469: 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 */
2470: } else if(mle==3){ /* exponential inter-extrapolation */
2471: 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 */
2472: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2473: lli=log(out[s1][s2]); /* Original formula */
2474: } else{ /* mle=0 back to 1 */
2475: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2476: /*lli=log(out[s1][s2]); */ /* Original formula */
2477: } /* End of if */
2478: ipmx +=1;
2479: sw += weight[i];
2480: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2481: /*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]); */
2482: if(globpr){
2483: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2484: %11.6f %11.6f %11.6f ", \
2485: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2486: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2487: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2488: llt +=ll[k]*gipmx/gsw;
2489: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2490: }
2491: fprintf(ficresilk," %10.6f\n", -llt);
2492: }
2493: } /* end of wave */
2494: } /* end of individual */
2495: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2496: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2497: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2498: if(globpr==0){ /* First time we count the contributions and weights */
2499: gipmx=ipmx;
2500: gsw=sw;
2501: }
2502: return -l;
2503: }
2504:
2505:
2506: /*************** function likelione ***********/
2507: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2508: {
2509: /* This routine should help understanding what is done with
2510: the selection of individuals/waves and
2511: to check the exact contribution to the likelihood.
2512: Plotting could be done.
2513: */
2514: int k;
2515:
2516: if(*globpri !=0){ /* Just counts and sums, no printings */
2517: strcpy(fileresilk,"ilk");
2518: strcat(fileresilk,fileres);
2519: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2520: printf("Problem with resultfile: %s\n", fileresilk);
2521: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2522: }
2523: fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
2524: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2525: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2526: for(k=1; k<=nlstate; k++)
2527: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2528: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2529: }
2530:
2531: *fretone=(*funcone)(p);
2532: if(*globpri !=0){
2533: fclose(ficresilk);
2534: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2535: fflush(fichtm);
2536: }
2537: return;
2538: }
2539:
2540:
2541: /*********** Maximum Likelihood Estimation ***************/
2542:
2543: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2544: {
2545: int i,j, iter=0;
2546: double **xi;
2547: double fret;
2548: double fretone; /* Only one call to likelihood */
2549: /* char filerespow[FILENAMELENGTH];*/
2550:
2551: #ifdef NLOPT
2552: int creturn;
2553: nlopt_opt opt;
2554: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2555: double *lb;
2556: double minf; /* the minimum objective value, upon return */
2557: double * p1; /* Shifted parameters from 0 instead of 1 */
2558: myfunc_data dinst, *d = &dinst;
2559: #endif
2560:
2561:
2562: xi=matrix(1,npar,1,npar);
2563: for (i=1;i<=npar;i++)
2564: for (j=1;j<=npar;j++)
2565: xi[i][j]=(i==j ? 1.0 : 0.0);
2566: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2567: strcpy(filerespow,"pow");
2568: strcat(filerespow,fileres);
2569: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2570: printf("Problem with resultfile: %s\n", filerespow);
2571: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2572: }
2573: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2574: for (i=1;i<=nlstate;i++)
2575: for(j=1;j<=nlstate+ndeath;j++)
2576: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2577: fprintf(ficrespow,"\n");
2578: #ifdef POWELL
2579: powell(p,xi,npar,ftol,&iter,&fret,func);
2580: #endif
2581:
2582: #ifdef NLOPT
2583: #ifdef NEWUOA
2584: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2585: #else
2586: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2587: #endif
2588: lb=vector(0,npar-1);
2589: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2590: nlopt_set_lower_bounds(opt, lb);
2591: nlopt_set_initial_step1(opt, 0.1);
2592:
2593: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2594: d->function = func;
2595: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2596: nlopt_set_min_objective(opt, myfunc, d);
2597: nlopt_set_xtol_rel(opt, ftol);
2598: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2599: printf("nlopt failed! %d\n",creturn);
2600: }
2601: else {
2602: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2603: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2604: iter=1; /* not equal */
2605: }
2606: nlopt_destroy(opt);
2607: #endif
2608: free_matrix(xi,1,npar,1,npar);
2609: fclose(ficrespow);
2610: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2611: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2612: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2613:
2614: }
2615:
2616: /**** Computes Hessian and covariance matrix ***/
2617: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2618: {
2619: double **a,**y,*x,pd;
2620: double **hess;
2621: int i, j;
2622: int *indx;
2623:
2624: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2625: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2626: void lubksb(double **a, int npar, int *indx, double b[]) ;
2627: void ludcmp(double **a, int npar, int *indx, double *d) ;
2628: double gompertz(double p[]);
2629: hess=matrix(1,npar,1,npar);
2630:
2631: printf("\nCalculation of the hessian matrix. Wait...\n");
2632: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2633: for (i=1;i<=npar;i++){
2634: printf("%d",i);fflush(stdout);
2635: fprintf(ficlog,"%d",i);fflush(ficlog);
2636:
2637: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2638:
2639: /* printf(" %f ",p[i]);
2640: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2641: }
2642:
2643: for (i=1;i<=npar;i++) {
2644: for (j=1;j<=npar;j++) {
2645: if (j>i) {
2646: printf(".%d%d",i,j);fflush(stdout);
2647: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2648: hess[i][j]=hessij(p,delti,i,j,func,npar);
2649:
2650: hess[j][i]=hess[i][j];
2651: /*printf(" %lf ",hess[i][j]);*/
2652: }
2653: }
2654: }
2655: printf("\n");
2656: fprintf(ficlog,"\n");
2657:
2658: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2659: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2660:
2661: a=matrix(1,npar,1,npar);
2662: y=matrix(1,npar,1,npar);
2663: x=vector(1,npar);
2664: indx=ivector(1,npar);
2665: for (i=1;i<=npar;i++)
2666: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2667: ludcmp(a,npar,indx,&pd);
2668:
2669: for (j=1;j<=npar;j++) {
2670: for (i=1;i<=npar;i++) x[i]=0;
2671: x[j]=1;
2672: lubksb(a,npar,indx,x);
2673: for (i=1;i<=npar;i++){
2674: matcov[i][j]=x[i];
2675: }
2676: }
2677:
2678: printf("\n#Hessian matrix#\n");
2679: fprintf(ficlog,"\n#Hessian matrix#\n");
2680: for (i=1;i<=npar;i++) {
2681: for (j=1;j<=npar;j++) {
2682: printf("%.3e ",hess[i][j]);
2683: fprintf(ficlog,"%.3e ",hess[i][j]);
2684: }
2685: printf("\n");
2686: fprintf(ficlog,"\n");
2687: }
2688:
2689: /* Recompute Inverse */
2690: for (i=1;i<=npar;i++)
2691: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2692: ludcmp(a,npar,indx,&pd);
2693:
2694: /* printf("\n#Hessian matrix recomputed#\n");
2695:
2696: for (j=1;j<=npar;j++) {
2697: for (i=1;i<=npar;i++) x[i]=0;
2698: x[j]=1;
2699: lubksb(a,npar,indx,x);
2700: for (i=1;i<=npar;i++){
2701: y[i][j]=x[i];
2702: printf("%.3e ",y[i][j]);
2703: fprintf(ficlog,"%.3e ",y[i][j]);
2704: }
2705: printf("\n");
2706: fprintf(ficlog,"\n");
2707: }
2708: */
2709:
2710: free_matrix(a,1,npar,1,npar);
2711: free_matrix(y,1,npar,1,npar);
2712: free_vector(x,1,npar);
2713: free_ivector(indx,1,npar);
2714: free_matrix(hess,1,npar,1,npar);
2715:
2716:
2717: }
2718:
2719: /*************** hessian matrix ****************/
2720: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2721: {
2722: int i;
2723: int l=1, lmax=20;
2724: double k1,k2;
2725: double p2[MAXPARM+1]; /* identical to x */
2726: double res;
2727: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2728: double fx;
2729: int k=0,kmax=10;
2730: double l1;
2731:
2732: fx=func(x);
2733: for (i=1;i<=npar;i++) p2[i]=x[i];
2734: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2735: l1=pow(10,l);
2736: delts=delt;
2737: for(k=1 ; k <kmax; k=k+1){
2738: delt = delta*(l1*k);
2739: p2[theta]=x[theta] +delt;
2740: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2741: p2[theta]=x[theta]-delt;
2742: k2=func(p2)-fx;
2743: /*res= (k1-2.0*fx+k2)/delt/delt; */
2744: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2745:
2746: #ifdef DEBUGHESS
2747: 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);
2748: 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);
2749: #endif
2750: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2751: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2752: k=kmax;
2753: }
2754: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2755: k=kmax; l=lmax*10;
2756: }
2757: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2758: delts=delt;
2759: }
2760: }
2761: }
2762: delti[theta]=delts;
2763: return res;
2764:
2765: }
2766:
2767: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2768: {
2769: int i;
2770: int l=1, lmax=20;
2771: double k1,k2,k3,k4,res,fx;
2772: double p2[MAXPARM+1];
2773: int k;
2774:
2775: fx=func(x);
2776: for (k=1; k<=2; k++) {
2777: for (i=1;i<=npar;i++) p2[i]=x[i];
2778: p2[thetai]=x[thetai]+delti[thetai]/k;
2779: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2780: k1=func(p2)-fx;
2781:
2782: p2[thetai]=x[thetai]+delti[thetai]/k;
2783: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2784: k2=func(p2)-fx;
2785:
2786: p2[thetai]=x[thetai]-delti[thetai]/k;
2787: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2788: k3=func(p2)-fx;
2789:
2790: p2[thetai]=x[thetai]-delti[thetai]/k;
2791: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2792: k4=func(p2)-fx;
2793: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2794: #ifdef DEBUG
2795: 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);
2796: 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);
2797: #endif
2798: }
2799: return res;
2800: }
2801:
2802: /************** Inverse of matrix **************/
2803: void ludcmp(double **a, int n, int *indx, double *d)
2804: {
2805: int i,imax,j,k;
2806: double big,dum,sum,temp;
2807: double *vv;
2808:
2809: vv=vector(1,n);
2810: *d=1.0;
2811: for (i=1;i<=n;i++) {
2812: big=0.0;
2813: for (j=1;j<=n;j++)
2814: if ((temp=fabs(a[i][j])) > big) big=temp;
2815: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2816: vv[i]=1.0/big;
2817: }
2818: for (j=1;j<=n;j++) {
2819: for (i=1;i<j;i++) {
2820: sum=a[i][j];
2821: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2822: a[i][j]=sum;
2823: }
2824: big=0.0;
2825: for (i=j;i<=n;i++) {
2826: sum=a[i][j];
2827: for (k=1;k<j;k++)
2828: sum -= a[i][k]*a[k][j];
2829: a[i][j]=sum;
2830: if ( (dum=vv[i]*fabs(sum)) >= big) {
2831: big=dum;
2832: imax=i;
2833: }
2834: }
2835: if (j != imax) {
2836: for (k=1;k<=n;k++) {
2837: dum=a[imax][k];
2838: a[imax][k]=a[j][k];
2839: a[j][k]=dum;
2840: }
2841: *d = -(*d);
2842: vv[imax]=vv[j];
2843: }
2844: indx[j]=imax;
2845: if (a[j][j] == 0.0) a[j][j]=TINY;
2846: if (j != n) {
2847: dum=1.0/(a[j][j]);
2848: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2849: }
2850: }
2851: free_vector(vv,1,n); /* Doesn't work */
2852: ;
2853: }
2854:
2855: void lubksb(double **a, int n, int *indx, double b[])
2856: {
2857: int i,ii=0,ip,j;
2858: double sum;
2859:
2860: for (i=1;i<=n;i++) {
2861: ip=indx[i];
2862: sum=b[ip];
2863: b[ip]=b[i];
2864: if (ii)
2865: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2866: else if (sum) ii=i;
2867: b[i]=sum;
2868: }
2869: for (i=n;i>=1;i--) {
2870: sum=b[i];
2871: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2872: b[i]=sum/a[i][i];
2873: }
2874: }
2875:
2876: void pstamp(FILE *fichier)
2877: {
2878: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2879: }
2880:
2881: /************ Frequencies ********************/
2882: 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[])
2883: { /* Some frequencies */
2884:
2885: int i, m, jk, j1, bool, z1,j;
2886: int first;
2887: double ***freq; /* Frequencies */
2888: double *pp, **prop;
2889: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2890: char fileresp[FILENAMELENGTH];
2891:
2892: pp=vector(1,nlstate);
2893: prop=matrix(1,nlstate,iagemin,iagemax+3);
2894: strcpy(fileresp,"p");
2895: strcat(fileresp,fileres);
2896: if((ficresp=fopen(fileresp,"w"))==NULL) {
2897: printf("Problem with prevalence resultfile: %s\n", fileresp);
2898: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2899: exit(0);
2900: }
2901: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2902: j1=0;
2903:
2904: j=cptcoveff;
2905: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2906:
2907: first=1;
2908:
2909: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2910: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2911: /* j1++; */
2912: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2913: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2914: scanf("%d", i);*/
2915: for (i=-5; i<=nlstate+ndeath; i++)
2916: for (jk=-5; jk<=nlstate+ndeath; jk++)
2917: for(m=iagemin; m <= iagemax+3; m++)
2918: freq[i][jk][m]=0;
2919:
2920: for (i=1; i<=nlstate; i++)
2921: for(m=iagemin; m <= iagemax+3; m++)
2922: prop[i][m]=0;
2923:
2924: dateintsum=0;
2925: k2cpt=0;
2926: for (i=1; i<=imx; i++) {
2927: bool=1;
2928: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2929: for (z1=1; z1<=cptcoveff; z1++)
2930: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2931: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2932: bool=0;
2933: /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n",
2934: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2935: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2936: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2937: }
2938: }
2939:
2940: if (bool==1){
2941: for(m=firstpass; m<=lastpass; m++){
2942: k2=anint[m][i]+(mint[m][i]/12.);
2943: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2944: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2945: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2946: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2947: if (m<lastpass) {
2948: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2949: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2950: }
2951:
2952: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2953: dateintsum=dateintsum+k2;
2954: k2cpt++;
2955: }
2956: /*}*/
2957: }
2958: }
2959: } /* end i */
2960:
2961: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2962: pstamp(ficresp);
2963: if (cptcovn>0) {
2964: fprintf(ficresp, "\n#********** Variable ");
2965: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2966: fprintf(ficresp, "**********\n#");
2967: fprintf(ficlog, "\n#********** Variable ");
2968: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2969: fprintf(ficlog, "**********\n#");
2970: }
2971: for(i=1; i<=nlstate;i++)
2972: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2973: fprintf(ficresp, "\n");
2974:
2975: for(i=iagemin; i <= iagemax+3; i++){
2976: if(i==iagemax+3){
2977: fprintf(ficlog,"Total");
2978: }else{
2979: if(first==1){
2980: first=0;
2981: printf("See log file for details...\n");
2982: }
2983: fprintf(ficlog,"Age %d", i);
2984: }
2985: for(jk=1; jk <=nlstate ; jk++){
2986: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2987: pp[jk] += freq[jk][m][i];
2988: }
2989: for(jk=1; jk <=nlstate ; jk++){
2990: for(m=-1, pos=0; m <=0 ; m++)
2991: pos += freq[jk][m][i];
2992: if(pp[jk]>=1.e-10){
2993: if(first==1){
2994: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2995: }
2996: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2997: }else{
2998: if(first==1)
2999: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3000: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3001: }
3002: }
3003:
3004: for(jk=1; jk <=nlstate ; jk++){
3005: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3006: pp[jk] += freq[jk][m][i];
3007: }
3008: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3009: pos += pp[jk];
3010: posprop += prop[jk][i];
3011: }
3012: for(jk=1; jk <=nlstate ; jk++){
3013: if(pos>=1.e-5){
3014: if(first==1)
3015: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3016: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3017: }else{
3018: if(first==1)
3019: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3020: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3021: }
3022: if( i <= iagemax){
3023: if(pos>=1.e-5){
3024: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3025: /*probs[i][jk][j1]= pp[jk]/pos;*/
3026: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3027: }
3028: else
3029: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3030: }
3031: }
3032:
3033: for(jk=-1; jk <=nlstate+ndeath; jk++)
3034: for(m=-1; m <=nlstate+ndeath; m++)
3035: if(freq[jk][m][i] !=0 ) {
3036: if(first==1)
3037: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3038: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3039: }
3040: if(i <= iagemax)
3041: fprintf(ficresp,"\n");
3042: if(first==1)
3043: printf("Others in log...\n");
3044: fprintf(ficlog,"\n");
3045: }
3046: /*}*/
3047: }
3048: dateintmean=dateintsum/k2cpt;
3049:
3050: fclose(ficresp);
3051: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3052: free_vector(pp,1,nlstate);
3053: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3054: /* End of Freq */
3055: }
3056:
3057: /************ Prevalence ********************/
3058: 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)
3059: {
3060: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3061: in each health status at the date of interview (if between dateprev1 and dateprev2).
3062: We still use firstpass and lastpass as another selection.
3063: */
3064:
3065: int i, m, jk, j1, bool, z1,j;
3066:
3067: double **prop;
3068: double posprop;
3069: double y2; /* in fractional years */
3070: int iagemin, iagemax;
3071: int first; /** to stop verbosity which is redirected to log file */
3072:
3073: iagemin= (int) agemin;
3074: iagemax= (int) agemax;
3075: /*pp=vector(1,nlstate);*/
3076: prop=matrix(1,nlstate,iagemin,iagemax+3);
3077: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3078: j1=0;
3079:
3080: /*j=cptcoveff;*/
3081: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3082:
3083: first=1;
3084: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3085: /*for(i1=1; i1<=ncodemax[k1];i1++){
3086: j1++;*/
3087:
3088: for (i=1; i<=nlstate; i++)
3089: for(m=iagemin; m <= iagemax+3; m++)
3090: prop[i][m]=0.0;
3091:
3092: for (i=1; i<=imx; i++) { /* Each individual */
3093: bool=1;
3094: if (cptcovn>0) {
3095: for (z1=1; z1<=cptcoveff; z1++)
3096: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
3097: bool=0;
3098: }
3099: if (bool==1) {
3100: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3101: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3102: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3103: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3104: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3105: 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);
3106: if (s[m][i]>0 && s[m][i]<=nlstate) {
3107: /*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]]);*/
3108: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3109: prop[s[m][i]][iagemax+3] += weight[i];
3110: }
3111: }
3112: } /* end selection of waves */
3113: }
3114: }
3115: for(i=iagemin; i <= iagemax+3; i++){
3116: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3117: posprop += prop[jk][i];
3118: }
3119:
3120: for(jk=1; jk <=nlstate ; jk++){
3121: if( i <= iagemax){
3122: if(posprop>=1.e-5){
3123: probs[i][jk][j1]= prop[jk][i]/posprop;
3124: } else{
3125: if(first==1){
3126: first=0;
3127: 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]);
3128: }
3129: }
3130: }
3131: }/* end jk */
3132: }/* end i */
3133: /*} *//* end i1 */
3134: } /* end j1 */
3135:
3136: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3137: /*free_vector(pp,1,nlstate);*/
3138: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3139: } /* End of prevalence */
3140:
3141: /************* Waves Concatenation ***************/
3142:
3143: 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)
3144: {
3145: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3146: Death is a valid wave (if date is known).
3147: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3148: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3149: and mw[mi+1][i]. dh depends on stepm.
3150: */
3151:
3152: int i, mi, m;
3153: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3154: double sum=0., jmean=0.;*/
3155: int first;
3156: int j, k=0,jk, ju, jl;
3157: double sum=0.;
3158: first=0;
3159: jmin=100000;
3160: jmax=-1;
3161: jmean=0.;
3162: for(i=1; i<=imx; i++){
3163: mi=0;
3164: m=firstpass;
3165: while(s[m][i] <= nlstate){
3166: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3167: mw[++mi][i]=m;
3168: if(m >=lastpass)
3169: break;
3170: else
3171: m++;
3172: }/* end while */
3173: if (s[m][i] > nlstate){
3174: mi++; /* Death is another wave */
3175: /* if(mi==0) never been interviewed correctly before death */
3176: /* Only death is a correct wave */
3177: mw[mi][i]=m;
3178: }
3179:
3180: wav[i]=mi;
3181: if(mi==0){
3182: nbwarn++;
3183: if(first==0){
3184: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3185: first=1;
3186: }
3187: if(first==1){
3188: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3189: }
3190: } /* end mi==0 */
3191: } /* End individuals */
3192:
3193: for(i=1; i<=imx; i++){
3194: for(mi=1; mi<wav[i];mi++){
3195: if (stepm <=0)
3196: dh[mi][i]=1;
3197: else{
3198: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3199: if (agedc[i] < 2*AGESUP) {
3200: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3201: if(j==0) j=1; /* Survives at least one month after exam */
3202: else if(j<0){
3203: nberr++;
3204: 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]);
3205: j=1; /* Temporary Dangerous patch */
3206: 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);
3207: 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]);
3208: 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);
3209: }
3210: k=k+1;
3211: if (j >= jmax){
3212: jmax=j;
3213: ijmax=i;
3214: }
3215: if (j <= jmin){
3216: jmin=j;
3217: ijmin=i;
3218: }
3219: sum=sum+j;
3220: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3221: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3222: }
3223: }
3224: else{
3225: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3226: /* 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]); */
3227:
3228: k=k+1;
3229: if (j >= jmax) {
3230: jmax=j;
3231: ijmax=i;
3232: }
3233: else if (j <= jmin){
3234: jmin=j;
3235: ijmin=i;
3236: }
3237: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3238: /*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]);*/
3239: if(j<0){
3240: nberr++;
3241: 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]);
3242: 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]);
3243: }
3244: sum=sum+j;
3245: }
3246: jk= j/stepm;
3247: jl= j -jk*stepm;
3248: ju= j -(jk+1)*stepm;
3249: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3250: if(jl==0){
3251: dh[mi][i]=jk;
3252: bh[mi][i]=0;
3253: }else{ /* We want a negative bias in order to only have interpolation ie
3254: * to avoid the price of an extra matrix product in likelihood */
3255: dh[mi][i]=jk+1;
3256: bh[mi][i]=ju;
3257: }
3258: }else{
3259: if(jl <= -ju){
3260: dh[mi][i]=jk;
3261: bh[mi][i]=jl; /* bias is positive if real duration
3262: * is higher than the multiple of stepm and negative otherwise.
3263: */
3264: }
3265: else{
3266: dh[mi][i]=jk+1;
3267: bh[mi][i]=ju;
3268: }
3269: if(dh[mi][i]==0){
3270: dh[mi][i]=1; /* At least one step */
3271: bh[mi][i]=ju; /* At least one step */
3272: /* 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);*/
3273: }
3274: } /* end if mle */
3275: }
3276: } /* end wave */
3277: }
3278: jmean=sum/k;
3279: 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);
3280: 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);
3281: }
3282:
3283: /*********** Tricode ****************************/
3284: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3285: {
3286: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3287: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3288: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3289: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3290: * nbcode[Tvar[j]][1]=
3291: */
3292:
3293: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3294: int modmaxcovj=0; /* Modality max of covariates j */
3295: int cptcode=0; /* Modality max of covariates j */
3296: int modmincovj=0; /* Modality min of covariates j */
3297:
3298:
3299: cptcoveff=0;
3300:
3301: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3302: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3303:
3304: /* Loop on covariates without age and products */
3305: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3306: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3307: modality of this covariate Vj*/
3308: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3309: * If product of Vn*Vm, still boolean *:
3310: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3311: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3312: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3313: modality of the nth covariate of individual i. */
3314: if (ij > modmaxcovj)
3315: modmaxcovj=ij;
3316: else if (ij < modmincovj)
3317: modmincovj=ij;
3318: if ((ij < -1) && (ij > NCOVMAX)){
3319: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3320: exit(1);
3321: }else
3322: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3323: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3324: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3325: /* getting the maximum value of the modality of the covariate
3326: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3327: female is 1, then modmaxcovj=1.*/
3328: } /* end for loop on individuals */
3329: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3330: cptcode=modmaxcovj;
3331: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3332: /*for (i=0; i<=cptcode; i++) {*/
3333: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3334: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
3335: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3336: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3337: }
3338: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3339: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3340: } /* Ndum[-1] number of undefined modalities */
3341:
3342: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3343: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3344: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3345: modmincovj=3; modmaxcovj = 7;
3346: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3347: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3348: defining two dummy variables: variables V1_1 and V1_2.
3349: nbcode[Tvar[j]][ij]=k;
3350: nbcode[Tvar[j]][1]=0;
3351: nbcode[Tvar[j]][2]=1;
3352: nbcode[Tvar[j]][3]=2;
3353: */
3354: ij=1; /* ij is similar to i but can jumps over null modalities */
3355: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3356: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3357: /*recode from 0 */
3358: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3359: nbcode[Tvar[j]][ij]=k; /* stores the modality k in an array nbcode.
3360: k is a modality. If we have model=V1+V1*sex
3361: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3362: ij++;
3363: }
3364: if (ij > ncodemax[j]) break;
3365: } /* end of loop on */
3366: } /* end of loop on modality */
3367: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3368:
3369: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3370:
3371: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3372: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3373: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3374: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3375: }
3376:
3377: ij=1;
3378: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3379: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3380: if((Ndum[i]!=0) && (i<=ncovcol)){
3381: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3382: Tvaraff[ij]=i; /*For printing (unclear) */
3383: ij++;
3384: }else
3385: Tvaraff[ij]=0;
3386: }
3387: ij--;
3388: cptcoveff=ij; /*Number of total covariates*/
3389:
3390: }
3391:
3392:
3393: /*********** Health Expectancies ****************/
3394:
3395: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3396:
3397: {
3398: /* Health expectancies, no variances */
3399: int i, j, nhstepm, hstepm, h, nstepm;
3400: int nhstepma, nstepma; /* Decreasing with age */
3401: double age, agelim, hf;
3402: double ***p3mat;
3403: double eip;
3404:
3405: pstamp(ficreseij);
3406: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3407: fprintf(ficreseij,"# Age");
3408: for(i=1; i<=nlstate;i++){
3409: for(j=1; j<=nlstate;j++){
3410: fprintf(ficreseij," e%1d%1d ",i,j);
3411: }
3412: fprintf(ficreseij," e%1d. ",i);
3413: }
3414: fprintf(ficreseij,"\n");
3415:
3416:
3417: if(estepm < stepm){
3418: printf ("Problem %d lower than %d\n",estepm, stepm);
3419: }
3420: else hstepm=estepm;
3421: /* We compute the life expectancy from trapezoids spaced every estepm months
3422: * This is mainly to measure the difference between two models: for example
3423: * if stepm=24 months pijx are given only every 2 years and by summing them
3424: * we are calculating an estimate of the Life Expectancy assuming a linear
3425: * progression in between and thus overestimating or underestimating according
3426: * to the curvature of the survival function. If, for the same date, we
3427: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3428: * to compare the new estimate of Life expectancy with the same linear
3429: * hypothesis. A more precise result, taking into account a more precise
3430: * curvature will be obtained if estepm is as small as stepm. */
3431:
3432: /* For example we decided to compute the life expectancy with the smallest unit */
3433: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3434: nhstepm is the number of hstepm from age to agelim
3435: nstepm is the number of stepm from age to agelin.
3436: Look at hpijx to understand the reason of that which relies in memory size
3437: and note for a fixed period like estepm months */
3438: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3439: survival function given by stepm (the optimization length). Unfortunately it
3440: means that if the survival funtion is printed only each two years of age and if
3441: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3442: results. So we changed our mind and took the option of the best precision.
3443: */
3444: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3445:
3446: agelim=AGESUP;
3447: /* If stepm=6 months */
3448: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3449: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3450:
3451: /* nhstepm age range expressed in number of stepm */
3452: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3453: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3454: /* if (stepm >= YEARM) hstepm=1;*/
3455: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3456: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3457:
3458: for (age=bage; age<=fage; age ++){
3459: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3460: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3461: /* if (stepm >= YEARM) hstepm=1;*/
3462: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3463:
3464: /* If stepm=6 months */
3465: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3466: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3467:
3468: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3469:
3470: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3471:
3472: printf("%d|",(int)age);fflush(stdout);
3473: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3474:
3475: /* Computing expectancies */
3476: for(i=1; i<=nlstate;i++)
3477: for(j=1; j<=nlstate;j++)
3478: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3479: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3480:
3481: /* 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]);*/
3482:
3483: }
3484:
3485: fprintf(ficreseij,"%3.0f",age );
3486: for(i=1; i<=nlstate;i++){
3487: eip=0;
3488: for(j=1; j<=nlstate;j++){
3489: eip +=eij[i][j][(int)age];
3490: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3491: }
3492: fprintf(ficreseij,"%9.4f", eip );
3493: }
3494: fprintf(ficreseij,"\n");
3495:
3496: }
3497: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3498: printf("\n");
3499: fprintf(ficlog,"\n");
3500:
3501: }
3502:
3503: 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[] )
3504:
3505: {
3506: /* Covariances of health expectancies eij and of total life expectancies according
3507: to initial status i, ei. .
3508: */
3509: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3510: int nhstepma, nstepma; /* Decreasing with age */
3511: double age, agelim, hf;
3512: double ***p3matp, ***p3matm, ***varhe;
3513: double **dnewm,**doldm;
3514: double *xp, *xm;
3515: double **gp, **gm;
3516: double ***gradg, ***trgradg;
3517: int theta;
3518:
3519: double eip, vip;
3520:
3521: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3522: xp=vector(1,npar);
3523: xm=vector(1,npar);
3524: dnewm=matrix(1,nlstate*nlstate,1,npar);
3525: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3526:
3527: pstamp(ficresstdeij);
3528: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3529: fprintf(ficresstdeij,"# Age");
3530: for(i=1; i<=nlstate;i++){
3531: for(j=1; j<=nlstate;j++)
3532: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3533: fprintf(ficresstdeij," e%1d. ",i);
3534: }
3535: fprintf(ficresstdeij,"\n");
3536:
3537: pstamp(ficrescveij);
3538: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3539: fprintf(ficrescveij,"# Age");
3540: for(i=1; i<=nlstate;i++)
3541: for(j=1; j<=nlstate;j++){
3542: cptj= (j-1)*nlstate+i;
3543: for(i2=1; i2<=nlstate;i2++)
3544: for(j2=1; j2<=nlstate;j2++){
3545: cptj2= (j2-1)*nlstate+i2;
3546: if(cptj2 <= cptj)
3547: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3548: }
3549: }
3550: fprintf(ficrescveij,"\n");
3551:
3552: if(estepm < stepm){
3553: printf ("Problem %d lower than %d\n",estepm, stepm);
3554: }
3555: else hstepm=estepm;
3556: /* We compute the life expectancy from trapezoids spaced every estepm months
3557: * This is mainly to measure the difference between two models: for example
3558: * if stepm=24 months pijx are given only every 2 years and by summing them
3559: * we are calculating an estimate of the Life Expectancy assuming a linear
3560: * progression in between and thus overestimating or underestimating according
3561: * to the curvature of the survival function. If, for the same date, we
3562: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3563: * to compare the new estimate of Life expectancy with the same linear
3564: * hypothesis. A more precise result, taking into account a more precise
3565: * curvature will be obtained if estepm is as small as stepm. */
3566:
3567: /* For example we decided to compute the life expectancy with the smallest unit */
3568: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3569: nhstepm is the number of hstepm from age to agelim
3570: nstepm is the number of stepm from age to agelin.
3571: Look at hpijx to understand the reason of that which relies in memory size
3572: and note for a fixed period like estepm months */
3573: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3574: survival function given by stepm (the optimization length). Unfortunately it
3575: means that if the survival funtion is printed only each two years of age and if
3576: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3577: results. So we changed our mind and took the option of the best precision.
3578: */
3579: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3580:
3581: /* If stepm=6 months */
3582: /* nhstepm age range expressed in number of stepm */
3583: agelim=AGESUP;
3584: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3585: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3586: /* if (stepm >= YEARM) hstepm=1;*/
3587: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3588:
3589: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3590: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3591: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3592: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3593: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3594: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3595:
3596: for (age=bage; age<=fage; age ++){
3597: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3598: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3599: /* if (stepm >= YEARM) hstepm=1;*/
3600: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3601:
3602: /* If stepm=6 months */
3603: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3604: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3605:
3606: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3607:
3608: /* Computing Variances of health expectancies */
3609: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3610: decrease memory allocation */
3611: for(theta=1; theta <=npar; theta++){
3612: for(i=1; i<=npar; i++){
3613: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3614: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3615: }
3616: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3617: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3618:
3619: for(j=1; j<= nlstate; j++){
3620: for(i=1; i<=nlstate; i++){
3621: for(h=0; h<=nhstepm-1; h++){
3622: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3623: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3624: }
3625: }
3626: }
3627:
3628: for(ij=1; ij<= nlstate*nlstate; ij++)
3629: for(h=0; h<=nhstepm-1; h++){
3630: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3631: }
3632: }/* End theta */
3633:
3634:
3635: for(h=0; h<=nhstepm-1; h++)
3636: for(j=1; j<=nlstate*nlstate;j++)
3637: for(theta=1; theta <=npar; theta++)
3638: trgradg[h][j][theta]=gradg[h][theta][j];
3639:
3640:
3641: for(ij=1;ij<=nlstate*nlstate;ij++)
3642: for(ji=1;ji<=nlstate*nlstate;ji++)
3643: varhe[ij][ji][(int)age] =0.;
3644:
3645: printf("%d|",(int)age);fflush(stdout);
3646: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3647: for(h=0;h<=nhstepm-1;h++){
3648: for(k=0;k<=nhstepm-1;k++){
3649: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3650: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3651: for(ij=1;ij<=nlstate*nlstate;ij++)
3652: for(ji=1;ji<=nlstate*nlstate;ji++)
3653: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3654: }
3655: }
3656:
3657: /* Computing expectancies */
3658: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3659: for(i=1; i<=nlstate;i++)
3660: for(j=1; j<=nlstate;j++)
3661: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3662: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3663:
3664: /* 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]);*/
3665:
3666: }
3667:
3668: fprintf(ficresstdeij,"%3.0f",age );
3669: for(i=1; i<=nlstate;i++){
3670: eip=0.;
3671: vip=0.;
3672: for(j=1; j<=nlstate;j++){
3673: eip += eij[i][j][(int)age];
3674: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3675: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3676: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3677: }
3678: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3679: }
3680: fprintf(ficresstdeij,"\n");
3681:
3682: fprintf(ficrescveij,"%3.0f",age );
3683: for(i=1; i<=nlstate;i++)
3684: for(j=1; j<=nlstate;j++){
3685: cptj= (j-1)*nlstate+i;
3686: for(i2=1; i2<=nlstate;i2++)
3687: for(j2=1; j2<=nlstate;j2++){
3688: cptj2= (j2-1)*nlstate+i2;
3689: if(cptj2 <= cptj)
3690: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3691: }
3692: }
3693: fprintf(ficrescveij,"\n");
3694:
3695: }
3696: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3697: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3698: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3699: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3700: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3701: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3702: printf("\n");
3703: fprintf(ficlog,"\n");
3704:
3705: free_vector(xm,1,npar);
3706: free_vector(xp,1,npar);
3707: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3708: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3709: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3710: }
3711:
3712: /************ Variance ******************/
3713: void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
3714: {
3715: /* Variance of health expectancies */
3716: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3717: /* double **newm;*/
3718: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3719:
3720: int movingaverage();
3721: double **dnewm,**doldm;
3722: double **dnewmp,**doldmp;
3723: int i, j, nhstepm, hstepm, h, nstepm ;
3724: int k;
3725: double *xp;
3726: double **gp, **gm; /* for var eij */
3727: double ***gradg, ***trgradg; /*for var eij */
3728: double **gradgp, **trgradgp; /* for var p point j */
3729: double *gpp, *gmp; /* for var p point j */
3730: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3731: double ***p3mat;
3732: double age,agelim, hf;
3733: double ***mobaverage;
3734: int theta;
3735: char digit[4];
3736: char digitp[25];
3737:
3738: char fileresprobmorprev[FILENAMELENGTH];
3739:
3740: if(popbased==1){
3741: if(mobilav!=0)
3742: strcpy(digitp,"-populbased-mobilav-");
3743: else strcpy(digitp,"-populbased-nomobil-");
3744: }
3745: else
3746: strcpy(digitp,"-stablbased-");
3747:
3748: if (mobilav!=0) {
3749: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3750: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3751: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3752: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3753: }
3754: }
3755:
3756: strcpy(fileresprobmorprev,"prmorprev");
3757: sprintf(digit,"%-d",ij);
3758: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3759: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3760: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3761: strcat(fileresprobmorprev,fileres);
3762: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3763: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3764: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3765: }
3766: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3767:
3768: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3769: pstamp(ficresprobmorprev);
3770: 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);
3771: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3772: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3773: fprintf(ficresprobmorprev," p.%-d SE",j);
3774: for(i=1; i<=nlstate;i++)
3775: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3776: }
3777: fprintf(ficresprobmorprev,"\n");
3778: fprintf(ficgp,"\n# Routine varevsij");
3779: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3780: 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");
3781: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3782: /* } */
3783: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3784: pstamp(ficresvij);
3785: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3786: if(popbased==1)
3787: 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);
3788: else
3789: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3790: fprintf(ficresvij,"# Age");
3791: for(i=1; i<=nlstate;i++)
3792: for(j=1; j<=nlstate;j++)
3793: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3794: fprintf(ficresvij,"\n");
3795:
3796: xp=vector(1,npar);
3797: dnewm=matrix(1,nlstate,1,npar);
3798: doldm=matrix(1,nlstate,1,nlstate);
3799: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3800: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3801:
3802: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3803: gpp=vector(nlstate+1,nlstate+ndeath);
3804: gmp=vector(nlstate+1,nlstate+ndeath);
3805: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3806:
3807: if(estepm < stepm){
3808: printf ("Problem %d lower than %d\n",estepm, stepm);
3809: }
3810: else hstepm=estepm;
3811: /* For example we decided to compute the life expectancy with the smallest unit */
3812: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3813: nhstepm is the number of hstepm from age to agelim
3814: nstepm is the number of stepm from age to agelin.
3815: Look at function hpijx to understand why (it is linked to memory size questions) */
3816: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3817: survival function given by stepm (the optimization length). Unfortunately it
3818: means that if the survival funtion is printed every two years of age and if
3819: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3820: results. So we changed our mind and took the option of the best precision.
3821: */
3822: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3823: agelim = AGESUP;
3824: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3825: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3826: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3827: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3828: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3829: gp=matrix(0,nhstepm,1,nlstate);
3830: gm=matrix(0,nhstepm,1,nlstate);
3831:
3832:
3833: for(theta=1; theta <=npar; theta++){
3834: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3835: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3836: }
3837: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3838: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3839:
3840: if (popbased==1) {
3841: if(mobilav ==0){
3842: for(i=1; i<=nlstate;i++)
3843: prlim[i][i]=probs[(int)age][i][ij];
3844: }else{ /* mobilav */
3845: for(i=1; i<=nlstate;i++)
3846: prlim[i][i]=mobaverage[(int)age][i][ij];
3847: }
3848: }
3849:
3850: for(j=1; j<= nlstate; j++){
3851: for(h=0; h<=nhstepm; h++){
3852: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3853: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3854: }
3855: }
3856: /* This for computing probability of death (h=1 means
3857: computed over hstepm matrices product = hstepm*stepm months)
3858: as a weighted average of prlim.
3859: */
3860: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3861: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3862: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3863: }
3864: /* end probability of death */
3865:
3866: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3867: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3868: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3869: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3870:
3871: if (popbased==1) {
3872: if(mobilav ==0){
3873: for(i=1; i<=nlstate;i++)
3874: prlim[i][i]=probs[(int)age][i][ij];
3875: }else{ /* mobilav */
3876: for(i=1; i<=nlstate;i++)
3877: prlim[i][i]=mobaverage[(int)age][i][ij];
3878: }
3879: }
3880:
3881: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3882: for(h=0; h<=nhstepm; h++){
3883: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3884: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3885: }
3886: }
3887: /* This for computing probability of death (h=1 means
3888: computed over hstepm matrices product = hstepm*stepm months)
3889: as a weighted average of prlim.
3890: */
3891: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3892: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3893: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3894: }
3895: /* end probability of death */
3896:
3897: for(j=1; j<= nlstate; j++) /* vareij */
3898: for(h=0; h<=nhstepm; h++){
3899: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3900: }
3901:
3902: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3903: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3904: }
3905:
3906: } /* End theta */
3907:
3908: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3909:
3910: for(h=0; h<=nhstepm; h++) /* veij */
3911: for(j=1; j<=nlstate;j++)
3912: for(theta=1; theta <=npar; theta++)
3913: trgradg[h][j][theta]=gradg[h][theta][j];
3914:
3915: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3916: for(theta=1; theta <=npar; theta++)
3917: trgradgp[j][theta]=gradgp[theta][j];
3918:
3919:
3920: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3921: for(i=1;i<=nlstate;i++)
3922: for(j=1;j<=nlstate;j++)
3923: vareij[i][j][(int)age] =0.;
3924:
3925: for(h=0;h<=nhstepm;h++){
3926: for(k=0;k<=nhstepm;k++){
3927: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3928: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3929: for(i=1;i<=nlstate;i++)
3930: for(j=1;j<=nlstate;j++)
3931: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3932: }
3933: }
3934:
3935: /* pptj */
3936: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3937: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3938: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3939: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3940: varppt[j][i]=doldmp[j][i];
3941: /* end ppptj */
3942: /* x centered again */
3943: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3944: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3945:
3946: if (popbased==1) {
3947: if(mobilav ==0){
3948: for(i=1; i<=nlstate;i++)
3949: prlim[i][i]=probs[(int)age][i][ij];
3950: }else{ /* mobilav */
3951: for(i=1; i<=nlstate;i++)
3952: prlim[i][i]=mobaverage[(int)age][i][ij];
3953: }
3954: }
3955:
3956: /* This for computing probability of death (h=1 means
3957: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3958: as a weighted average of prlim.
3959: */
3960: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3961: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3962: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3963: }
3964: /* end probability of death */
3965:
3966: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3967: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3968: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3969: for(i=1; i<=nlstate;i++){
3970: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3971: }
3972: }
3973: fprintf(ficresprobmorprev,"\n");
3974:
3975: fprintf(ficresvij,"%.0f ",age );
3976: for(i=1; i<=nlstate;i++)
3977: for(j=1; j<=nlstate;j++){
3978: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3979: }
3980: fprintf(ficresvij,"\n");
3981: free_matrix(gp,0,nhstepm,1,nlstate);
3982: free_matrix(gm,0,nhstepm,1,nlstate);
3983: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3984: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3985: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3986: } /* End age */
3987: free_vector(gpp,nlstate+1,nlstate+ndeath);
3988: free_vector(gmp,nlstate+1,nlstate+ndeath);
3989: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3990: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3991: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3992: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3993: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3994: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3995: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3996: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3997: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3998: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3999: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4000: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4001: fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4002: /* fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
4003: */
4004: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
4005: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4006:
4007: free_vector(xp,1,npar);
4008: free_matrix(doldm,1,nlstate,1,nlstate);
4009: free_matrix(dnewm,1,nlstate,1,npar);
4010: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4011: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4012: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4013: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4014: fclose(ficresprobmorprev);
4015: fflush(ficgp);
4016: fflush(fichtm);
4017: } /* end varevsij */
4018:
4019: /************ Variance of prevlim ******************/
4020: void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
4021: {
4022: /* Variance of prevalence limit */
4023: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4024:
4025: double **dnewm,**doldm;
4026: int i, j, nhstepm, hstepm;
4027: double *xp;
4028: double *gp, *gm;
4029: double **gradg, **trgradg;
4030: double age,agelim;
4031: int theta;
4032:
4033: pstamp(ficresvpl);
4034: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4035: fprintf(ficresvpl,"# Age");
4036: for(i=1; i<=nlstate;i++)
4037: fprintf(ficresvpl," %1d-%1d",i,i);
4038: fprintf(ficresvpl,"\n");
4039:
4040: xp=vector(1,npar);
4041: dnewm=matrix(1,nlstate,1,npar);
4042: doldm=matrix(1,nlstate,1,nlstate);
4043:
4044: hstepm=1*YEARM; /* Every year of age */
4045: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4046: agelim = AGESUP;
4047: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4048: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4049: if (stepm >= YEARM) hstepm=1;
4050: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4051: gradg=matrix(1,npar,1,nlstate);
4052: gp=vector(1,nlstate);
4053: gm=vector(1,nlstate);
4054:
4055: for(theta=1; theta <=npar; theta++){
4056: for(i=1; i<=npar; i++){ /* Computes gradient */
4057: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4058: }
4059: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4060: for(i=1;i<=nlstate;i++)
4061: gp[i] = prlim[i][i];
4062:
4063: for(i=1; i<=npar; i++) /* Computes gradient */
4064: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4065: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4066: for(i=1;i<=nlstate;i++)
4067: gm[i] = prlim[i][i];
4068:
4069: for(i=1;i<=nlstate;i++)
4070: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4071: } /* End theta */
4072:
4073: trgradg =matrix(1,nlstate,1,npar);
4074:
4075: for(j=1; j<=nlstate;j++)
4076: for(theta=1; theta <=npar; theta++)
4077: trgradg[j][theta]=gradg[theta][j];
4078:
4079: for(i=1;i<=nlstate;i++)
4080: varpl[i][(int)age] =0.;
4081: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4082: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4083: for(i=1;i<=nlstate;i++)
4084: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4085:
4086: fprintf(ficresvpl,"%.0f ",age );
4087: for(i=1; i<=nlstate;i++)
4088: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4089: fprintf(ficresvpl,"\n");
4090: free_vector(gp,1,nlstate);
4091: free_vector(gm,1,nlstate);
4092: free_matrix(gradg,1,npar,1,nlstate);
4093: free_matrix(trgradg,1,nlstate,1,npar);
4094: } /* End age */
4095:
4096: free_vector(xp,1,npar);
4097: free_matrix(doldm,1,nlstate,1,npar);
4098: free_matrix(dnewm,1,nlstate,1,nlstate);
4099:
4100: }
4101:
4102: /************ Variance of one-step probabilities ******************/
4103: 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[])
4104: {
4105: int i, j=0, k1, l1, tj;
4106: int k2, l2, j1, z1;
4107: int k=0, l;
4108: int first=1, first1, first2;
4109: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4110: double **dnewm,**doldm;
4111: double *xp;
4112: double *gp, *gm;
4113: double **gradg, **trgradg;
4114: double **mu;
4115: double age, cov[NCOVMAX+1];
4116: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4117: int theta;
4118: char fileresprob[FILENAMELENGTH];
4119: char fileresprobcov[FILENAMELENGTH];
4120: char fileresprobcor[FILENAMELENGTH];
4121: double ***varpij;
4122:
4123: strcpy(fileresprob,"prob");
4124: strcat(fileresprob,fileres);
4125: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4126: printf("Problem with resultfile: %s\n", fileresprob);
4127: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4128: }
4129: strcpy(fileresprobcov,"probcov");
4130: strcat(fileresprobcov,fileres);
4131: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4132: printf("Problem with resultfile: %s\n", fileresprobcov);
4133: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4134: }
4135: strcpy(fileresprobcor,"probcor");
4136: strcat(fileresprobcor,fileres);
4137: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4138: printf("Problem with resultfile: %s\n", fileresprobcor);
4139: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4140: }
4141: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4142: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4143: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4144: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4145: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4146: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4147: pstamp(ficresprob);
4148: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4149: fprintf(ficresprob,"# Age");
4150: pstamp(ficresprobcov);
4151: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4152: fprintf(ficresprobcov,"# Age");
4153: pstamp(ficresprobcor);
4154: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4155: fprintf(ficresprobcor,"# Age");
4156:
4157:
4158: for(i=1; i<=nlstate;i++)
4159: for(j=1; j<=(nlstate+ndeath);j++){
4160: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4161: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4162: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4163: }
4164: /* fprintf(ficresprob,"\n");
4165: fprintf(ficresprobcov,"\n");
4166: fprintf(ficresprobcor,"\n");
4167: */
4168: xp=vector(1,npar);
4169: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4170: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4171: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4172: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4173: first=1;
4174: fprintf(ficgp,"\n# Routine varprob");
4175: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4176: fprintf(fichtm,"\n");
4177:
4178: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
4179: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
4180: file %s<br>\n",optionfilehtmcov);
4181: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
4182: and drawn. It helps understanding how is the covariance between two incidences.\
4183: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4184: 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. \
4185: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4186: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4187: standard deviations wide on each axis. <br>\
4188: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4189: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4190: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4191:
4192: cov[1]=1;
4193: /* tj=cptcoveff; */
4194: tj = (int) pow(2,cptcoveff);
4195: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4196: j1=0;
4197: for(j1=1; j1<=tj;j1++){
4198: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4199: /*j1++;*/
4200: if (cptcovn>0) {
4201: fprintf(ficresprob, "\n#********** Variable ");
4202: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4203: fprintf(ficresprob, "**********\n#\n");
4204: fprintf(ficresprobcov, "\n#********** Variable ");
4205: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4206: fprintf(ficresprobcov, "**********\n#\n");
4207:
4208: fprintf(ficgp, "\n#********** Variable ");
4209: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4210: fprintf(ficgp, "**********\n#\n");
4211:
4212:
4213: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4214: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4215: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4216:
4217: fprintf(ficresprobcor, "\n#********** Variable ");
4218: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4219: fprintf(ficresprobcor, "**********\n#");
4220: }
4221:
4222: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4223: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4224: gp=vector(1,(nlstate)*(nlstate+ndeath));
4225: gm=vector(1,(nlstate)*(nlstate+ndeath));
4226: for (age=bage; age<=fage; age ++){
4227: cov[2]=age;
4228: if(nagesqr==1)
4229: cov[3]= age*age;
4230: for (k=1; k<=cptcovn;k++) {
4231: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
4232: * 1 1 1 1 1
4233: * 2 2 1 1 1
4234: * 3 1 2 1 1
4235: */
4236: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4237: }
4238: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4239: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
4240: for (k=1; k<=cptcovprod;k++)
4241: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
4242:
4243:
4244: for(theta=1; theta <=npar; theta++){
4245: for(i=1; i<=npar; i++)
4246: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4247:
4248: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4249:
4250: k=0;
4251: for(i=1; i<= (nlstate); i++){
4252: for(j=1; j<=(nlstate+ndeath);j++){
4253: k=k+1;
4254: gp[k]=pmmij[i][j];
4255: }
4256: }
4257:
4258: for(i=1; i<=npar; i++)
4259: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4260:
4261: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4262: k=0;
4263: for(i=1; i<=(nlstate); i++){
4264: for(j=1; j<=(nlstate+ndeath);j++){
4265: k=k+1;
4266: gm[k]=pmmij[i][j];
4267: }
4268: }
4269:
4270: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4271: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4272: }
4273:
4274: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4275: for(theta=1; theta <=npar; theta++)
4276: trgradg[j][theta]=gradg[theta][j];
4277:
4278: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4279: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4280:
4281: pmij(pmmij,cov,ncovmodel,x,nlstate);
4282:
4283: k=0;
4284: for(i=1; i<=(nlstate); i++){
4285: for(j=1; j<=(nlstate+ndeath);j++){
4286: k=k+1;
4287: mu[k][(int) age]=pmmij[i][j];
4288: }
4289: }
4290: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4291: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4292: varpij[i][j][(int)age] = doldm[i][j];
4293:
4294: /*printf("\n%d ",(int)age);
4295: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4296: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4297: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4298: }*/
4299:
4300: fprintf(ficresprob,"\n%d ",(int)age);
4301: fprintf(ficresprobcov,"\n%d ",(int)age);
4302: fprintf(ficresprobcor,"\n%d ",(int)age);
4303:
4304: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4305: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4306: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4307: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4308: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4309: }
4310: i=0;
4311: for (k=1; k<=(nlstate);k++){
4312: for (l=1; l<=(nlstate+ndeath);l++){
4313: i++;
4314: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4315: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4316: for (j=1; j<=i;j++){
4317: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4318: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4319: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4320: }
4321: }
4322: }/* end of loop for state */
4323: } /* end of loop for age */
4324: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4325: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4326: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4327: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4328:
4329: /* Confidence intervalle of pij */
4330: /*
4331: fprintf(ficgp,"\nunset parametric;unset label");
4332: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4333: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4334: 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);
4335: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4336: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4337: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4338: */
4339:
4340: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4341: first1=1;first2=2;
4342: for (k2=1; k2<=(nlstate);k2++){
4343: for (l2=1; l2<=(nlstate+ndeath);l2++){
4344: if(l2==k2) continue;
4345: j=(k2-1)*(nlstate+ndeath)+l2;
4346: for (k1=1; k1<=(nlstate);k1++){
4347: for (l1=1; l1<=(nlstate+ndeath);l1++){
4348: if(l1==k1) continue;
4349: i=(k1-1)*(nlstate+ndeath)+l1;
4350: if(i<=j) continue;
4351: for (age=bage; age<=fage; age ++){
4352: if ((int)age %5==0){
4353: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4354: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4355: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4356: mu1=mu[i][(int) age]/stepm*YEARM ;
4357: mu2=mu[j][(int) age]/stepm*YEARM;
4358: c12=cv12/sqrt(v1*v2);
4359: /* Computing eigen value of matrix of covariance */
4360: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4361: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4362: if ((lc2 <0) || (lc1 <0) ){
4363: if(first2==1){
4364: first1=0;
4365: 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);
4366: }
4367: 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);
4368: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4369: /* lc2=fabs(lc2); */
4370: }
4371:
4372: /* Eigen vectors */
4373: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4374: /*v21=sqrt(1.-v11*v11); *//* error */
4375: v21=(lc1-v1)/cv12*v11;
4376: v12=-v21;
4377: v22=v11;
4378: tnalp=v21/v11;
4379: if(first1==1){
4380: first1=0;
4381: 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);
4382: }
4383: 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);
4384: /*printf(fignu*/
4385: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4386: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4387: if(first==1){
4388: first=0;
4389: fprintf(ficgp,"\nset parametric;unset label");
4390: 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);
4391: fprintf(ficgp,"\nset ter png small size 320, 240");
4392: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4393: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4394: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4395: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4396: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4397: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4398: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4399: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4400: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4401: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4402: 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",\
4403: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4404: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4405: }else{
4406: first=0;
4407: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4408: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4409: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4410: 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",\
4411: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4412: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4413: }/* if first */
4414: } /* age mod 5 */
4415: } /* end loop age */
4416: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4417: first=1;
4418: } /*l12 */
4419: } /* k12 */
4420: } /*l1 */
4421: }/* k1 */
4422: /* } */ /* loop covariates */
4423: }
4424: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4425: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4426: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4427: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4428: free_vector(xp,1,npar);
4429: fclose(ficresprob);
4430: fclose(ficresprobcov);
4431: fclose(ficresprobcor);
4432: fflush(ficgp);
4433: fflush(fichtmcov);
4434: }
4435:
4436:
4437: /******************* Printing html file ***********/
4438: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4439: int lastpass, int stepm, int weightopt, char model[],\
4440: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4441: int popforecast, int estepm ,\
4442: double jprev1, double mprev1,double anprev1, \
4443: double jprev2, double mprev2,double anprev2){
4444: int jj1, k1, i1, cpt;
4445:
4446: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4447: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4448: </ul>");
4449: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4450: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4451: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4452: fprintf(fichtm,"\
4453: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4454: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4455: fprintf(fichtm,"\
4456: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4457: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4458: fprintf(fichtm,"\
4459: - (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): \
4460: <a href=\"%s\">%s</a> <br>\n",
4461: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4462: fprintf(fichtm,"\
4463: - Population projections by age and states: \
4464: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4465:
4466: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4467:
4468: m=pow(2,cptcoveff);
4469: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4470:
4471: jj1=0;
4472: for(k1=1; k1<=m;k1++){
4473: for(i1=1; i1<=ncodemax[k1];i1++){
4474: jj1++;
4475: if (cptcovn > 0) {
4476: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4477: for (cpt=1; cpt<=cptcoveff;cpt++)
4478: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4479: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4480: }
4481: /* Pij */
4482: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
4483: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4484: /* Quasi-incidences */
4485: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4486: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
4487: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4488: /* Period (stable) prevalence in each health state */
4489: for(cpt=1; cpt<=nlstate;cpt++){
4490: fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
4491: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4492: }
4493: for(cpt=1; cpt<=nlstate;cpt++) {
4494: fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
4495: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4496: }
4497: } /* end i1 */
4498: }/* End k1 */
4499: fprintf(fichtm,"</ul>");
4500:
4501:
4502: fprintf(fichtm,"\
4503: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4504: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4505:
4506: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4507: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4508: fprintf(fichtm,"\
4509: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4510: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4511:
4512: fprintf(fichtm,"\
4513: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4514: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4515: fprintf(fichtm,"\
4516: - 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): \
4517: <a href=\"%s\">%s</a> <br>\n</li>",
4518: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4519: fprintf(fichtm,"\
4520: - (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): \
4521: <a href=\"%s\">%s</a> <br>\n</li>",
4522: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4523: fprintf(fichtm,"\
4524: - 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",
4525: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4526: fprintf(fichtm,"\
4527: - 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",
4528: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4529: fprintf(fichtm,"\
4530: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4531: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4532:
4533: /* if(popforecast==1) fprintf(fichtm,"\n */
4534: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4535: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4536: /* <br>",fileres,fileres,fileres,fileres); */
4537: /* else */
4538: /* 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); */
4539: fflush(fichtm);
4540: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4541:
4542: m=pow(2,cptcoveff);
4543: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4544:
4545: jj1=0;
4546: for(k1=1; k1<=m;k1++){
4547: for(i1=1; i1<=ncodemax[k1];i1++){
4548: jj1++;
4549: if (cptcovn > 0) {
4550: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4551: for (cpt=1; cpt<=cptcoveff;cpt++)
4552: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4553: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4554: }
4555: for(cpt=1; cpt<=nlstate;cpt++) {
4556: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4557: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4558: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4559: }
4560: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4561: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4562: true period expectancies (those weighted with period prevalences are also\
4563: drawn in addition to the population based expectancies computed using\
4564: observed and cahotic prevalences: %s%d.png<br>\
4565: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4566: } /* end i1 */
4567: }/* End k1 */
4568: fprintf(fichtm,"</ul>");
4569: fflush(fichtm);
4570: }
4571:
4572: /******************* Gnuplot file **************/
4573: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4574:
4575: char dirfileres[132],optfileres[132];
4576: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4577: int ng=0;
4578: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4579: /* printf("Problem with file %s",optionfilegnuplot); */
4580: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4581: /* } */
4582:
4583: /*#ifdef windows */
4584: fprintf(ficgp,"cd \"%s\" \n",pathc);
4585: /*#endif */
4586: m=pow(2,cptcoveff);
4587:
4588: strcpy(dirfileres,optionfilefiname);
4589: strcpy(optfileres,"vpl");
4590: /* 1eme*/
4591: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4592: for (cpt=1; cpt<= nlstate ; cpt ++) {
4593: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4594: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4595: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4596: fprintf(ficgp,"set xlabel \"Age\" \n\
4597: set ylabel \"Probability\" \n\
4598: set ter png small size 320, 240\n\
4599: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4600:
4601: for (i=1; i<= nlstate ; i ++) {
4602: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4603: else fprintf(ficgp," %%*lf (%%*lf)");
4604: }
4605: fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
4606: for (i=1; i<= nlstate ; i ++) {
4607: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4608: else fprintf(ficgp," %%*lf (%%*lf)");
4609: }
4610: fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
4611: for (i=1; i<= nlstate ; i ++) {
4612: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4613: else fprintf(ficgp," %%*lf (%%*lf)");
4614: }
4615: fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
4616: }
4617: }
4618: /*2 eme*/
4619: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4620: for (k1=1; k1<= m ; k1 ++) {
4621: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4622: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4623:
4624: for (i=1; i<= nlstate+1 ; i ++) {
4625: k=2*i;
4626: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4627: for (j=1; j<= nlstate+1 ; j ++) {
4628: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4629: else fprintf(ficgp," %%*lf (%%*lf)");
4630: }
4631: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4632: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4633: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4634: for (j=1; j<= nlstate+1 ; j ++) {
4635: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4636: else fprintf(ficgp," %%*lf (%%*lf)");
4637: }
4638: fprintf(ficgp,"\" t\"\" w l lt 0,");
4639: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4640: for (j=1; j<= nlstate+1 ; j ++) {
4641: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4642: else fprintf(ficgp," %%*lf (%%*lf)");
4643: }
4644: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4645: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4646: }
4647: }
4648:
4649: /*3eme*/
4650:
4651: for (k1=1; k1<= m ; k1 ++) {
4652: for (cpt=1; cpt<= nlstate ; cpt ++) {
4653: /* k=2+nlstate*(2*cpt-2); */
4654: k=2+(nlstate+1)*(cpt-1);
4655: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4656: fprintf(ficgp,"set ter png small size 320, 240\n\
4657: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
4658: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4659: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4660: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4661: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4662: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4663: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4664:
4665: */
4666: for (i=1; i< nlstate ; i ++) {
4667: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
4668: /* 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);*/
4669:
4670: }
4671: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4672: }
4673: }
4674:
4675: /* CV preval stable (period) */
4676: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4677: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4678: k=3;
4679: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4680: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4681: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4682: set ter png small size 320, 240\n\
4683: unset log y\n\
4684: plot [%.f:%.f] ", ageminpar, agemaxpar);
4685: for (i=1; i<= nlstate ; i ++){
4686: if(i==1)
4687: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4688: else
4689: fprintf(ficgp,", '' ");
4690: l=(nlstate+ndeath)*(i-1)+1;
4691: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4692: for (j=1; j<= (nlstate-1) ; j ++)
4693: fprintf(ficgp,"+$%d",k+l+j);
4694: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4695: } /* nlstate */
4696: fprintf(ficgp,"\n");
4697: } /* end cpt state*/
4698: } /* end covariate */
4699:
4700: /* proba elementaires */
4701: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
4702: for(i=1,jk=1; i <=nlstate; i++){
4703: fprintf(ficgp,"# initial state %d\n",i);
4704: for(k=1; k <=(nlstate+ndeath); k++){
4705: if (k != i) {
4706: fprintf(ficgp,"# current state %d\n",k);
4707: for(j=1; j <=ncovmodel; j++){
4708: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
4709: jk++;
4710: }
4711: fprintf(ficgp,"\n");
4712: }
4713: }
4714: }
4715: fprintf(ficgp,"##############\n#\n");
4716:
4717: /*goto avoid;*/
4718: fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
4719: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4720: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4721: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4722: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4723: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4724: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4725: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4726: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4727: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4728: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4729: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4730: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4731: fprintf(ficgp,"#\n");
4732: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4733: fprintf(ficgp,"# ng=%d\n",ng);
4734: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
4735: for(jk=1; jk <=m; jk++) {
4736: fprintf(ficgp,"# jk=%d\n",jk);
4737: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4738: if (ng==2)
4739: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4740: else
4741: fprintf(ficgp,"\nset title \"Probability\"\n");
4742: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4743: i=1;
4744: for(k2=1; k2<=nlstate; k2++) {
4745: k3=i;
4746: for(k=1; k<=(nlstate+ndeath); k++) {
4747: if (k != k2){
4748: if(ng==2)
4749: if(nagesqr==0)
4750: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4751: else /* nagesqr =1 */
4752: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
4753: else
4754: if(nagesqr==0)
4755: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4756: else /* nagesqr =1 */
4757: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
4758: ij=1;/* To be checked else nbcode[0][0] wrong */
4759: for(j=3; j <=ncovmodel-nagesqr; j++) {
4760: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
4761: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
4762: ij++;
4763: }
4764: else
4765: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4766: }
4767: fprintf(ficgp,")/(1");
4768:
4769: for(k1=1; k1 <=nlstate; k1++){
4770: if(nagesqr==0)
4771: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4772: else /* nagesqr =1 */
4773: 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);
4774:
4775: ij=1;
4776: for(j=3; j <=ncovmodel-nagesqr; j++){
4777: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
4778: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
4779: ij++;
4780: }
4781: else
4782: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4783: }
4784: fprintf(ficgp,")");
4785: }
4786: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4787: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4788: i=i+ncovmodel;
4789: }
4790: } /* end k */
4791: } /* end k2 */
4792: } /* end jk */
4793: } /* end ng */
4794: /* avoid: */
4795: fflush(ficgp);
4796: } /* end gnuplot */
4797:
4798:
4799: /*************** Moving average **************/
4800: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4801:
4802: int i, cpt, cptcod;
4803: int modcovmax =1;
4804: int mobilavrange, mob;
4805: double age;
4806:
4807: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4808: a covariate has 2 modalities */
4809: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4810:
4811: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4812: if(mobilav==1) mobilavrange=5; /* default */
4813: else mobilavrange=mobilav;
4814: for (age=bage; age<=fage; age++)
4815: for (i=1; i<=nlstate;i++)
4816: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4817: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4818: /* We keep the original values on the extreme ages bage, fage and for
4819: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4820: we use a 5 terms etc. until the borders are no more concerned.
4821: */
4822: for (mob=3;mob <=mobilavrange;mob=mob+2){
4823: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4824: for (i=1; i<=nlstate;i++){
4825: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4826: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4827: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4828: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4829: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4830: }
4831: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4832: }
4833: }
4834: }/* end age */
4835: }/* end mob */
4836: }else return -1;
4837: return 0;
4838: }/* End movingaverage */
4839:
4840:
4841: /************** Forecasting ******************/
4842: 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){
4843: /* proj1, year, month, day of starting projection
4844: agemin, agemax range of age
4845: dateprev1 dateprev2 range of dates during which prevalence is computed
4846: anproj2 year of en of projection (same day and month as proj1).
4847: */
4848: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4849: double agec; /* generic age */
4850: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4851: double *popeffectif,*popcount;
4852: double ***p3mat;
4853: double ***mobaverage;
4854: char fileresf[FILENAMELENGTH];
4855:
4856: agelim=AGESUP;
4857: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4858:
4859: strcpy(fileresf,"f");
4860: strcat(fileresf,fileres);
4861: if((ficresf=fopen(fileresf,"w"))==NULL) {
4862: printf("Problem with forecast resultfile: %s\n", fileresf);
4863: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4864: }
4865: printf("Computing forecasting: result on file '%s' \n", fileresf);
4866: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4867:
4868: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4869:
4870: if (mobilav!=0) {
4871: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4872: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4873: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4874: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4875: }
4876: }
4877:
4878: stepsize=(int) (stepm+YEARM-1)/YEARM;
4879: if (stepm<=12) stepsize=1;
4880: if(estepm < stepm){
4881: printf ("Problem %d lower than %d\n",estepm, stepm);
4882: }
4883: else hstepm=estepm;
4884:
4885: hstepm=hstepm/stepm;
4886: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4887: fractional in yp1 */
4888: anprojmean=yp;
4889: yp2=modf((yp1*12),&yp);
4890: mprojmean=yp;
4891: yp1=modf((yp2*30.5),&yp);
4892: jprojmean=yp;
4893: if(jprojmean==0) jprojmean=1;
4894: if(mprojmean==0) jprojmean=1;
4895:
4896: i1=cptcoveff;
4897: if (cptcovn < 1){i1=1;}
4898:
4899: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4900:
4901: fprintf(ficresf,"#****** Routine prevforecast **\n");
4902:
4903: /* if (h==(int)(YEARM*yearp)){ */
4904: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4905: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4906: k=k+1;
4907: fprintf(ficresf,"\n#******");
4908: for(j=1;j<=cptcoveff;j++) {
4909: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4910: }
4911: fprintf(ficresf,"******\n");
4912: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4913: for(j=1; j<=nlstate+ndeath;j++){
4914: for(i=1; i<=nlstate;i++)
4915: fprintf(ficresf," p%d%d",i,j);
4916: fprintf(ficresf," p.%d",j);
4917: }
4918: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4919: fprintf(ficresf,"\n");
4920: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4921:
4922: for (agec=fage; agec>=(ageminpar-1); agec--){
4923: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4924: nhstepm = nhstepm/hstepm;
4925: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4926: oldm=oldms;savm=savms;
4927: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4928:
4929: for (h=0; h<=nhstepm; h++){
4930: if (h*hstepm/YEARM*stepm ==yearp) {
4931: fprintf(ficresf,"\n");
4932: for(j=1;j<=cptcoveff;j++)
4933: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4934: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4935: }
4936: for(j=1; j<=nlstate+ndeath;j++) {
4937: ppij=0.;
4938: for(i=1; i<=nlstate;i++) {
4939: if (mobilav==1)
4940: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4941: else {
4942: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4943: }
4944: if (h*hstepm/YEARM*stepm== yearp) {
4945: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4946: }
4947: } /* end i */
4948: if (h*hstepm/YEARM*stepm==yearp) {
4949: fprintf(ficresf," %.3f", ppij);
4950: }
4951: }/* end j */
4952: } /* end h */
4953: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4954: } /* end agec */
4955: } /* end yearp */
4956: } /* end cptcod */
4957: } /* end cptcov */
4958:
4959: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4960:
4961: fclose(ficresf);
4962: }
4963:
4964: /************** Forecasting *****not tested NB*************/
4965: 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){
4966:
4967: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4968: int *popage;
4969: double calagedatem, agelim, kk1, kk2;
4970: double *popeffectif,*popcount;
4971: double ***p3mat,***tabpop,***tabpopprev;
4972: double ***mobaverage;
4973: char filerespop[FILENAMELENGTH];
4974:
4975: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4976: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4977: agelim=AGESUP;
4978: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4979:
4980: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4981:
4982:
4983: strcpy(filerespop,"pop");
4984: strcat(filerespop,fileres);
4985: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4986: printf("Problem with forecast resultfile: %s\n", filerespop);
4987: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4988: }
4989: printf("Computing forecasting: result on file '%s' \n", filerespop);
4990: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4991:
4992: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4993:
4994: if (mobilav!=0) {
4995: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4996: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4997: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4998: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4999: }
5000: }
5001:
5002: stepsize=(int) (stepm+YEARM-1)/YEARM;
5003: if (stepm<=12) stepsize=1;
5004:
5005: agelim=AGESUP;
5006:
5007: hstepm=1;
5008: hstepm=hstepm/stepm;
5009:
5010: if (popforecast==1) {
5011: if((ficpop=fopen(popfile,"r"))==NULL) {
5012: printf("Problem with population file : %s\n",popfile);exit(0);
5013: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5014: }
5015: popage=ivector(0,AGESUP);
5016: popeffectif=vector(0,AGESUP);
5017: popcount=vector(0,AGESUP);
5018:
5019: i=1;
5020: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5021:
5022: imx=i;
5023: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5024: }
5025:
5026: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5027: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5028: k=k+1;
5029: fprintf(ficrespop,"\n#******");
5030: for(j=1;j<=cptcoveff;j++) {
5031: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5032: }
5033: fprintf(ficrespop,"******\n");
5034: fprintf(ficrespop,"# Age");
5035: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5036: if (popforecast==1) fprintf(ficrespop," [Population]");
5037:
5038: for (cpt=0; cpt<=0;cpt++) {
5039: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5040:
5041: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5042: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5043: nhstepm = nhstepm/hstepm;
5044:
5045: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5046: oldm=oldms;savm=savms;
5047: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5048:
5049: for (h=0; h<=nhstepm; h++){
5050: if (h==(int) (calagedatem+YEARM*cpt)) {
5051: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5052: }
5053: for(j=1; j<=nlstate+ndeath;j++) {
5054: kk1=0.;kk2=0;
5055: for(i=1; i<=nlstate;i++) {
5056: if (mobilav==1)
5057: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5058: else {
5059: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5060: }
5061: }
5062: if (h==(int)(calagedatem+12*cpt)){
5063: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5064: /*fprintf(ficrespop," %.3f", kk1);
5065: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5066: }
5067: }
5068: for(i=1; i<=nlstate;i++){
5069: kk1=0.;
5070: for(j=1; j<=nlstate;j++){
5071: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5072: }
5073: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5074: }
5075:
5076: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5077: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5078: }
5079: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5080: }
5081: }
5082:
5083: /******/
5084:
5085: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5086: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5087: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5088: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5089: nhstepm = nhstepm/hstepm;
5090:
5091: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5092: oldm=oldms;savm=savms;
5093: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5094: for (h=0; h<=nhstepm; h++){
5095: if (h==(int) (calagedatem+YEARM*cpt)) {
5096: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5097: }
5098: for(j=1; j<=nlstate+ndeath;j++) {
5099: kk1=0.;kk2=0;
5100: for(i=1; i<=nlstate;i++) {
5101: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5102: }
5103: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5104: }
5105: }
5106: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5107: }
5108: }
5109: }
5110: }
5111:
5112: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5113:
5114: if (popforecast==1) {
5115: free_ivector(popage,0,AGESUP);
5116: free_vector(popeffectif,0,AGESUP);
5117: free_vector(popcount,0,AGESUP);
5118: }
5119: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5120: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5121: fclose(ficrespop);
5122: } /* End of popforecast */
5123:
5124: int fileappend(FILE *fichier, char *optionfich)
5125: {
5126: if((fichier=fopen(optionfich,"a"))==NULL) {
5127: printf("Problem with file: %s\n", optionfich);
5128: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5129: return (0);
5130: }
5131: fflush(fichier);
5132: return (1);
5133: }
5134:
5135:
5136: /**************** function prwizard **********************/
5137: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5138: {
5139:
5140: /* Wizard to print covariance matrix template */
5141:
5142: char ca[32], cb[32];
5143: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5144: int numlinepar;
5145:
5146: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5147: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5148: for(i=1; i <=nlstate; i++){
5149: jj=0;
5150: for(j=1; j <=nlstate+ndeath; j++){
5151: if(j==i) continue;
5152: jj++;
5153: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5154: printf("%1d%1d",i,j);
5155: fprintf(ficparo,"%1d%1d",i,j);
5156: for(k=1; k<=ncovmodel;k++){
5157: /* printf(" %lf",param[i][j][k]); */
5158: /* fprintf(ficparo," %lf",param[i][j][k]); */
5159: printf(" 0.");
5160: fprintf(ficparo," 0.");
5161: }
5162: printf("\n");
5163: fprintf(ficparo,"\n");
5164: }
5165: }
5166: printf("# Scales (for hessian or gradient estimation)\n");
5167: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5168: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5169: for(i=1; i <=nlstate; i++){
5170: jj=0;
5171: for(j=1; j <=nlstate+ndeath; j++){
5172: if(j==i) continue;
5173: jj++;
5174: fprintf(ficparo,"%1d%1d",i,j);
5175: printf("%1d%1d",i,j);
5176: fflush(stdout);
5177: for(k=1; k<=ncovmodel;k++){
5178: /* printf(" %le",delti3[i][j][k]); */
5179: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5180: printf(" 0.");
5181: fprintf(ficparo," 0.");
5182: }
5183: numlinepar++;
5184: printf("\n");
5185: fprintf(ficparo,"\n");
5186: }
5187: }
5188: printf("# Covariance matrix\n");
5189: /* # 121 Var(a12)\n\ */
5190: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5191: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5192: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5193: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5194: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5195: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5196: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5197: fflush(stdout);
5198: fprintf(ficparo,"# Covariance matrix\n");
5199: /* # 121 Var(a12)\n\ */
5200: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5201: /* # ...\n\ */
5202: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5203:
5204: for(itimes=1;itimes<=2;itimes++){
5205: jj=0;
5206: for(i=1; i <=nlstate; i++){
5207: for(j=1; j <=nlstate+ndeath; j++){
5208: if(j==i) continue;
5209: for(k=1; k<=ncovmodel;k++){
5210: jj++;
5211: ca[0]= k+'a'-1;ca[1]='\0';
5212: if(itimes==1){
5213: printf("#%1d%1d%d",i,j,k);
5214: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5215: }else{
5216: printf("%1d%1d%d",i,j,k);
5217: fprintf(ficparo,"%1d%1d%d",i,j,k);
5218: /* printf(" %.5le",matcov[i][j]); */
5219: }
5220: ll=0;
5221: for(li=1;li <=nlstate; li++){
5222: for(lj=1;lj <=nlstate+ndeath; lj++){
5223: if(lj==li) continue;
5224: for(lk=1;lk<=ncovmodel;lk++){
5225: ll++;
5226: if(ll<=jj){
5227: cb[0]= lk +'a'-1;cb[1]='\0';
5228: if(ll<jj){
5229: if(itimes==1){
5230: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5231: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5232: }else{
5233: printf(" 0.");
5234: fprintf(ficparo," 0.");
5235: }
5236: }else{
5237: if(itimes==1){
5238: printf(" Var(%s%1d%1d)",ca,i,j);
5239: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5240: }else{
5241: printf(" 0.");
5242: fprintf(ficparo," 0.");
5243: }
5244: }
5245: }
5246: } /* end lk */
5247: } /* end lj */
5248: } /* end li */
5249: printf("\n");
5250: fprintf(ficparo,"\n");
5251: numlinepar++;
5252: } /* end k*/
5253: } /*end j */
5254: } /* end i */
5255: } /* end itimes */
5256:
5257: } /* end of prwizard */
5258: /******************* Gompertz Likelihood ******************************/
5259: double gompertz(double x[])
5260: {
5261: double A,B,L=0.0,sump=0.,num=0.;
5262: int i,n=0; /* n is the size of the sample */
5263:
5264: for (i=0;i<=imx-1 ; i++) {
5265: sump=sump+weight[i];
5266: /* sump=sump+1;*/
5267: num=num+1;
5268: }
5269:
5270:
5271: /* for (i=0; i<=imx; i++)
5272: 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]);*/
5273:
5274: for (i=1;i<=imx ; i++)
5275: {
5276: if (cens[i] == 1 && wav[i]>1)
5277: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5278:
5279: if (cens[i] == 0 && wav[i]>1)
5280: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5281: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5282:
5283: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5284: if (wav[i] > 1 ) { /* ??? */
5285: L=L+A*weight[i];
5286: /* 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]);*/
5287: }
5288: }
5289:
5290: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5291:
5292: return -2*L*num/sump;
5293: }
5294:
5295: #ifdef GSL
5296: /******************* Gompertz_f Likelihood ******************************/
5297: double gompertz_f(const gsl_vector *v, void *params)
5298: {
5299: double A,B,LL=0.0,sump=0.,num=0.;
5300: double *x= (double *) v->data;
5301: int i,n=0; /* n is the size of the sample */
5302:
5303: for (i=0;i<=imx-1 ; i++) {
5304: sump=sump+weight[i];
5305: /* sump=sump+1;*/
5306: num=num+1;
5307: }
5308:
5309:
5310: /* for (i=0; i<=imx; i++)
5311: 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]);*/
5312: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5313: for (i=1;i<=imx ; i++)
5314: {
5315: if (cens[i] == 1 && wav[i]>1)
5316: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5317:
5318: if (cens[i] == 0 && wav[i]>1)
5319: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5320: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5321:
5322: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5323: if (wav[i] > 1 ) { /* ??? */
5324: LL=LL+A*weight[i];
5325: /* 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]);*/
5326: }
5327: }
5328:
5329: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5330: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5331:
5332: return -2*LL*num/sump;
5333: }
5334: #endif
5335:
5336: /******************* Printing html file ***********/
5337: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5338: int lastpass, int stepm, int weightopt, char model[],\
5339: int imx, double p[],double **matcov,double agemortsup){
5340: int i,k;
5341:
5342: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5343: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5344: for (i=1;i<=2;i++)
5345: 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]));
5346: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5347: fprintf(fichtm,"</ul>");
5348:
5349: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5350:
5351: 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>");
5352:
5353: for (k=agegomp;k<(agemortsup-2);k++)
5354: 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]);
5355:
5356:
5357: fflush(fichtm);
5358: }
5359:
5360: /******************* Gnuplot file **************/
5361: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5362:
5363: char dirfileres[132],optfileres[132];
5364:
5365: int ng;
5366:
5367:
5368: /*#ifdef windows */
5369: fprintf(ficgp,"cd \"%s\" \n",pathc);
5370: /*#endif */
5371:
5372:
5373: strcpy(dirfileres,optionfilefiname);
5374: strcpy(optfileres,"vpl");
5375: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5376: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5377: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5378: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5379: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5380:
5381: }
5382:
5383: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5384: {
5385:
5386: /*-------- data file ----------*/
5387: FILE *fic;
5388: char dummy[]=" ";
5389: int i=0, j=0, n=0;
5390: int linei, month, year,iout;
5391: char line[MAXLINE], linetmp[MAXLINE];
5392: char stra[MAXLINE], strb[MAXLINE];
5393: char *stratrunc;
5394: int lstra;
5395:
5396:
5397: if((fic=fopen(datafile,"r"))==NULL) {
5398: printf("Problem while opening datafile: %s\n", datafile);return 1;
5399: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5400: }
5401:
5402: i=1;
5403: linei=0;
5404: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5405: linei=linei+1;
5406: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5407: if(line[j] == '\t')
5408: line[j] = ' ';
5409: }
5410: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5411: ;
5412: };
5413: line[j+1]=0; /* Trims blanks at end of line */
5414: if(line[0]=='#'){
5415: fprintf(ficlog,"Comment line\n%s\n",line);
5416: printf("Comment line\n%s\n",line);
5417: continue;
5418: }
5419: trimbb(linetmp,line); /* Trims multiple blanks in line */
5420: strcpy(line, linetmp);
5421:
5422:
5423: for (j=maxwav;j>=1;j--){
5424: cutv(stra, strb, line, ' ');
5425: if(strb[0]=='.') { /* Missing status */
5426: lval=-1;
5427: }else{
5428: errno=0;
5429: lval=strtol(strb,&endptr,10);
5430: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5431: if( strb[0]=='\0' || (*endptr != '\0')){
5432: 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);
5433: 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);
5434: return 1;
5435: }
5436: }
5437: s[j][i]=lval;
5438:
5439: strcpy(line,stra);
5440: cutv(stra, strb,line,' ');
5441: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5442: }
5443: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5444: month=99;
5445: year=9999;
5446: }else{
5447: 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);
5448: 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);
5449: return 1;
5450: }
5451: anint[j][i]= (double) year;
5452: mint[j][i]= (double)month;
5453: strcpy(line,stra);
5454: } /* ENd Waves */
5455:
5456: cutv(stra, strb,line,' ');
5457: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5458: }
5459: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5460: month=99;
5461: year=9999;
5462: }else{
5463: 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);
5464: 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);
5465: return 1;
5466: }
5467: andc[i]=(double) year;
5468: moisdc[i]=(double) month;
5469: strcpy(line,stra);
5470:
5471: cutv(stra, strb,line,' ');
5472: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5473: }
5474: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5475: month=99;
5476: year=9999;
5477: }else{
5478: 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);
5479: 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);
5480: return 1;
5481: }
5482: if (year==9999) {
5483: 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);
5484: 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);
5485: return 1;
5486:
5487: }
5488: annais[i]=(double)(year);
5489: moisnais[i]=(double)(month);
5490: strcpy(line,stra);
5491:
5492: cutv(stra, strb,line,' ');
5493: errno=0;
5494: dval=strtod(strb,&endptr);
5495: if( strb[0]=='\0' || (*endptr != '\0')){
5496: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5497: 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);
5498: fflush(ficlog);
5499: return 1;
5500: }
5501: weight[i]=dval;
5502: strcpy(line,stra);
5503:
5504: for (j=ncovcol;j>=1;j--){
5505: cutv(stra, strb,line,' ');
5506: if(strb[0]=='.') { /* Missing status */
5507: lval=-1;
5508: }else{
5509: errno=0;
5510: lval=strtol(strb,&endptr,10);
5511: if( strb[0]=='\0' || (*endptr != '\0')){
5512: 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);
5513: 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);
5514: return 1;
5515: }
5516: }
5517: if(lval <-1 || lval >1){
5518: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5519: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5520: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5521: For example, for multinomial values like 1, 2 and 3,\n \
5522: build V1=0 V2=0 for the reference value (1),\n \
5523: V1=1 V2=0 for (2) \n \
5524: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5525: output of IMaCh is often meaningless.\n \
5526: Exiting.\n",lval,linei, i,line,j);
5527: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5528: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5529: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5530: For example, for multinomial values like 1, 2 and 3,\n \
5531: build V1=0 V2=0 for the reference value (1),\n \
5532: V1=1 V2=0 for (2) \n \
5533: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5534: output of IMaCh is often meaningless.\n \
5535: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5536: return 1;
5537: }
5538: covar[j][i]=(double)(lval);
5539: strcpy(line,stra);
5540: }
5541: lstra=strlen(stra);
5542:
5543: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5544: stratrunc = &(stra[lstra-9]);
5545: num[i]=atol(stratrunc);
5546: }
5547: else
5548: num[i]=atol(stra);
5549: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5550: 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;}*/
5551:
5552: i=i+1;
5553: } /* End loop reading data */
5554:
5555: *imax=i-1; /* Number of individuals */
5556: fclose(fic);
5557:
5558: return (0);
5559: /* endread: */
5560: printf("Exiting readdata: ");
5561: fclose(fic);
5562: return (1);
5563:
5564:
5565:
5566: }
5567: void removespace(char *str) {
5568: char *p1 = str, *p2 = str;
5569: do
5570: while (*p2 == ' ')
5571: p2++;
5572: while (*p1++ == *p2++);
5573: }
5574:
5575: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5576: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5577: * - nagesqr = 1 if age*age in the model, otherwise 0.
5578: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5579: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
5580: * - cptcovage number of covariates with age*products =2
5581: * - cptcovs number of simple covariates
5582: * - 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
5583: * which is a new column after the 9 (ncovcol) variables.
5584: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5585: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5586: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5587: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5588: */
5589: {
5590: int i, j, k, ks;
5591: int j1, k1, k2;
5592: char modelsav[80];
5593: char stra[80], strb[80], strc[80], strd[80],stre[80];
5594: char *strpt;
5595:
5596: /*removespace(model);*/
5597: if (strlen(model) >1){ /* If there is at least 1 covariate */
5598: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5599: if (strstr(model,"AGE") !=0){
5600: printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
5601: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
5602: return 1;
5603: }
5604: if (strstr(model,"v") !=0){
5605: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5606: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5607: return 1;
5608: }
5609: strcpy(modelsav,model);
5610: if ((strpt=strstr(model,"age*age")) !=0){
5611: printf(" strpt=%s, model=%s\n",strpt, model);
5612: if(strpt != model){
5613: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
5614: 'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
5615: corresponding column of parameters.\n",model);
5616: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
5617: 'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
5618: corresponding column of parameters.\n",model); fflush(ficlog);
5619: return 1;
5620: }
5621:
5622: nagesqr=1;
5623: if (strstr(model,"+age*age") !=0)
5624: substrchaine(modelsav, model, "+age*age");
5625: else if (strstr(model,"age*age+") !=0)
5626: substrchaine(modelsav, model, "age*age+");
5627: else
5628: substrchaine(modelsav, model, "age*age");
5629: }else
5630: nagesqr=0;
5631: if (strlen(modelsav) >1){
5632: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5633: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5634: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5635: cptcovt= j+1; /* Number of total covariates in the model, not including
5636: * cst, age and age*age
5637: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5638: /* including age products which are counted in cptcovage.
5639: * but the covariates which are products must be treated
5640: * separately: ncovn=4- 2=2 (V1+V3). */
5641: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5642: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5643:
5644:
5645: /* Design
5646: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5647: * < ncovcol=8 >
5648: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5649: * k= 1 2 3 4 5 6 7 8
5650: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5651: * covar[k,i], value of kth covariate if not including age for individual i:
5652: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5653: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5654: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5655: * Tage[++cptcovage]=k
5656: * if products, new covar are created after ncovcol with k1
5657: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5658: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5659: * 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
5660: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5661: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5662: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5663: * < ncovcol=8 >
5664: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5665: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5666: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5667: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5668: * p Tprod[1]@2={ 6, 5}
5669: *p Tvard[1][1]@4= {7, 8, 5, 6}
5670: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5671: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5672: *How to reorganize?
5673: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5674: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5675: * {2, 1, 4, 8, 5, 6, 3, 7}
5676: * Struct []
5677: */
5678:
5679: /* This loop fills the array Tvar from the string 'model'.*/
5680: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5681: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5682: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5683: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5684: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5685: /* k=1 Tvar[1]=2 (from V2) */
5686: /* k=5 Tvar[5] */
5687: /* for (k=1; k<=cptcovn;k++) { */
5688: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5689: /* } */
5690: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
5691: /*
5692: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5693: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5694: Tvar[k]=0;
5695: cptcovage=0;
5696: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5697: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5698: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5699: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5700: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5701: /*scanf("%d",i);*/
5702: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5703: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5704: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5705: /* covar is not filled and then is empty */
5706: cptcovprod--;
5707: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5708: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5709: cptcovage++; /* Sums the number of covariates which include age as a product */
5710: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5711: /*printf("stre=%s ", stre);*/
5712: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5713: cptcovprod--;
5714: cutl(stre,strb,strc,'V');
5715: Tvar[k]=atoi(stre);
5716: cptcovage++;
5717: Tage[cptcovage]=k;
5718: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5719: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5720: cptcovn++;
5721: cptcovprodnoage++;k1++;
5722: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5723: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5724: because this model-covariate is a construction we invent a new column
5725: ncovcol + k1
5726: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5727: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5728: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5729: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5730: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5731: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5732: k2=k2+2;
5733: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5734: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5735: for (i=1; i<=lastobs;i++){
5736: /* Computes the new covariate which is a product of
5737: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5738: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5739: }
5740: } /* End age is not in the model */
5741: } /* End if model includes a product */
5742: else { /* no more sum */
5743: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5744: /* scanf("%d",i);*/
5745: cutl(strd,strc,strb,'V');
5746: ks++; /**< Number of simple covariates */
5747: cptcovn++;
5748: Tvar[k]=atoi(strd);
5749: }
5750: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5751: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5752: scanf("%d",i);*/
5753: } /* end of loop + on total covariates */
5754: } /* end if strlen(modelsave == 0) age*age might exist */
5755: } /* end if strlen(model == 0) */
5756:
5757: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5758: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5759:
5760: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5761: printf("cptcovprod=%d ", cptcovprod);
5762: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5763:
5764: scanf("%d ",i);*/
5765:
5766:
5767: return (0); /* with covar[new additional covariate if product] and Tage if age */
5768: /*endread:*/
5769: printf("Exiting decodemodel: ");
5770: return (1);
5771: }
5772:
5773: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5774: {
5775: int i, m;
5776:
5777: for (i=1; i<=imx; i++) {
5778: for(m=2; (m<= maxwav); m++) {
5779: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5780: anint[m][i]=9999;
5781: s[m][i]=-1;
5782: }
5783: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5784: *nberr = *nberr + 1;
5785: 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);
5786: 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);
5787: s[m][i]=-1;
5788: }
5789: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5790: (*nberr)++;
5791: 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]);
5792: 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]);
5793: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5794: }
5795: }
5796: }
5797:
5798: for (i=1; i<=imx; i++) {
5799: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5800: for(m=firstpass; (m<= lastpass); m++){
5801: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5802: if (s[m][i] >= nlstate+1) {
5803: if(agedc[i]>0){
5804: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5805: agev[m][i]=agedc[i];
5806: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5807: }else {
5808: if ((int)andc[i]!=9999){
5809: nbwarn++;
5810: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5811: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5812: agev[m][i]=-1;
5813: }
5814: }
5815: } /* agedc > 0 */
5816: }
5817: else if(s[m][i] !=9){ /* Standard case, age in fractional
5818: years but with the precision of a month */
5819: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5820: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5821: agev[m][i]=1;
5822: else if(agev[m][i] < *agemin){
5823: *agemin=agev[m][i];
5824: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5825: }
5826: else if(agev[m][i] >*agemax){
5827: *agemax=agev[m][i];
5828: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5829: }
5830: /*agev[m][i]=anint[m][i]-annais[i];*/
5831: /* agev[m][i] = age[i]+2*m;*/
5832: }
5833: else { /* =9 */
5834: agev[m][i]=1;
5835: s[m][i]=-1;
5836: }
5837: }
5838: else /*= 0 Unknown */
5839: agev[m][i]=1;
5840: }
5841:
5842: }
5843: for (i=1; i<=imx; i++) {
5844: for(m=firstpass; (m<=lastpass); m++){
5845: if (s[m][i] > (nlstate+ndeath)) {
5846: (*nberr)++;
5847: 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);
5848: 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);
5849: return 1;
5850: }
5851: }
5852: }
5853:
5854: /*for (i=1; i<=imx; i++){
5855: for (m=firstpass; (m<lastpass); m++){
5856: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5857: }
5858:
5859: }*/
5860:
5861:
5862: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5863: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5864:
5865: return (0);
5866: /* endread:*/
5867: printf("Exiting calandcheckages: ");
5868: return (1);
5869: }
5870:
5871: #if defined(_MSC_VER)
5872: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5873: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5874: //#include "stdafx.h"
5875: //#include <stdio.h>
5876: //#include <tchar.h>
5877: //#include <windows.h>
5878: //#include <iostream>
5879: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5880:
5881: LPFN_ISWOW64PROCESS fnIsWow64Process;
5882:
5883: BOOL IsWow64()
5884: {
5885: BOOL bIsWow64 = FALSE;
5886:
5887: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5888: // (HANDLE, PBOOL);
5889:
5890: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5891:
5892: HMODULE module = GetModuleHandle(_T("kernel32"));
5893: const char funcName[] = "IsWow64Process";
5894: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5895: GetProcAddress(module, funcName);
5896:
5897: if (NULL != fnIsWow64Process)
5898: {
5899: if (!fnIsWow64Process(GetCurrentProcess(),
5900: &bIsWow64))
5901: //throw std::exception("Unknown error");
5902: printf("Unknown error\n");
5903: }
5904: return bIsWow64 != FALSE;
5905: }
5906: #endif
5907:
5908: void syscompilerinfo(int logged)
5909: {
5910: /* #include "syscompilerinfo.h"*/
5911: /* command line Intel compiler 32bit windows, XP compatible:*/
5912: /* /GS /W3 /Gy
5913: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
5914: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
5915: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
5916: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
5917: */
5918: /* 64 bits */
5919: /*
5920: /GS /W3 /Gy
5921: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
5922: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
5923: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
5924: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
5925: /* Optimization are useless and O3 is slower than O2 */
5926: /*
5927: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
5928: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
5929: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
5930: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
5931: */
5932: /* Link is */ /* /OUT:"visual studio
5933: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
5934: /PDB:"visual studio
5935: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
5936: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
5937: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
5938: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
5939: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
5940: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
5941: uiAccess='false'"
5942: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
5943: /NOLOGO /TLBID:1
5944: */
5945: #if defined __INTEL_COMPILER
5946: #if defined(__GNUC__)
5947: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5948: #endif
5949: #elif defined(__GNUC__)
5950: #ifndef __APPLE__
5951: #include <gnu/libc-version.h> /* Only on gnu */
5952: #endif
5953: struct utsname sysInfo;
5954: int cross = CROSS;
5955: if (cross){
5956: printf("Cross-");
5957: if(logged) fprintf(ficlog, "Cross-");
5958: }
5959: #endif
5960:
5961: #include <stdint.h>
5962:
5963: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
5964: #if defined(__clang__)
5965: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5966: #endif
5967: #if defined(__ICC) || defined(__INTEL_COMPILER)
5968: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5969: #endif
5970: #if defined(__GNUC__) || defined(__GNUG__)
5971: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5972: #endif
5973: #if defined(__HP_cc) || defined(__HP_aCC)
5974: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5975: #endif
5976: #if defined(__IBMC__) || defined(__IBMCPP__)
5977: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5978: #endif
5979: #if defined(_MSC_VER)
5980: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5981: #endif
5982: #if defined(__PGI)
5983: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5984: #endif
5985: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5986: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5987: #endif
5988: printf(" for "); if (logged) fprintf(ficlog, " for ");
5989:
5990: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5991: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5992: // Windows (x64 and x86)
5993: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
5994: #elif __unix__ // all unices, not all compilers
5995: // Unix
5996: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
5997: #elif __linux__
5998: // linux
5999: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6000: #elif __APPLE__
6001: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6002: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6003: #endif
6004:
6005: /* __MINGW32__ */
6006: /* __CYGWIN__ */
6007: /* __MINGW64__ */
6008: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6009: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6010: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6011: /* _WIN64 // Defined for applications for Win64. */
6012: /* _M_X64 // Defined for compilations that target x64 processors. */
6013: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6014:
6015: #if UINTPTR_MAX == 0xffffffff
6016: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6017: #elif UINTPTR_MAX == 0xffffffffffffffff
6018: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6019: #else
6020: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6021: #endif
6022:
6023: #if defined(__GNUC__)
6024: # if defined(__GNUC_PATCHLEVEL__)
6025: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6026: + __GNUC_MINOR__ * 100 \
6027: + __GNUC_PATCHLEVEL__)
6028: # else
6029: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6030: + __GNUC_MINOR__ * 100)
6031: # endif
6032: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6033: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6034:
6035: if (uname(&sysInfo) != -1) {
6036: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6037: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6038: }
6039: else
6040: perror("uname() error");
6041: //#ifndef __INTEL_COMPILER
6042: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6043: printf("GNU libc version: %s\n", gnu_get_libc_version());
6044: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6045: #endif
6046: #endif
6047:
6048: // void main()
6049: // {
6050: #if defined(_MSC_VER)
6051: if (IsWow64()){
6052: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6053: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6054: }
6055: else{
6056: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6057: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6058: }
6059: // printf("\nPress Enter to continue...");
6060: // getchar();
6061: // }
6062:
6063: #endif
6064:
6065:
6066: }
6067:
6068: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6069: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6070: int i, j, k, i1 ;
6071: double ftolpl = 1.e-10;
6072: double age, agebase, agelim;
6073:
6074: strcpy(filerespl,"pl");
6075: strcat(filerespl,fileres);
6076: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6077: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6078: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6079: }
6080: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6081: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6082: pstamp(ficrespl);
6083: fprintf(ficrespl,"# Period (stable) prevalence \n");
6084: fprintf(ficrespl,"#Age ");
6085: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6086: fprintf(ficrespl,"\n");
6087:
6088: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6089:
6090: agebase=ageminpar;
6091: agelim=agemaxpar;
6092:
6093: i1=pow(2,cptcoveff);
6094: if (cptcovn < 1){i1=1;}
6095:
6096: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6097: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6098: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6099: k=k+1;
6100: /* to clean */
6101: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
6102: fprintf(ficrespl,"\n#******");
6103: printf("\n#******");
6104: fprintf(ficlog,"\n#******");
6105: for(j=1;j<=cptcoveff;j++) {
6106: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6107: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6108: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6109: }
6110: fprintf(ficrespl,"******\n");
6111: printf("******\n");
6112: fprintf(ficlog,"******\n");
6113:
6114: fprintf(ficrespl,"#Age ");
6115: for(j=1;j<=cptcoveff;j++) {
6116: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6117: }
6118: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6119: fprintf(ficrespl,"\n");
6120:
6121: for (age=agebase; age<=agelim; age++){
6122: /* for (age=agebase; age<=agebase; age++){ */
6123: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6124: fprintf(ficrespl,"%.0f ",age );
6125: for(j=1;j<=cptcoveff;j++)
6126: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6127: for(i=1; i<=nlstate;i++)
6128: fprintf(ficrespl," %.5f", prlim[i][i]);
6129: fprintf(ficrespl,"\n");
6130: } /* Age */
6131: /* was end of cptcod */
6132: } /* cptcov */
6133: return 0;
6134: }
6135:
6136: int hPijx(double *p, int bage, int fage){
6137: /*------------- h Pij x at various ages ------------*/
6138:
6139: int stepsize;
6140: int agelim;
6141: int hstepm;
6142: int nhstepm;
6143: int h, i, i1, j, k;
6144:
6145: double agedeb;
6146: double ***p3mat;
6147:
6148: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6149: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6150: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6151: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6152: }
6153: printf("Computing pij: result on file '%s' \n", filerespij);
6154: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6155:
6156: stepsize=(int) (stepm+YEARM-1)/YEARM;
6157: /*if (stepm<=24) stepsize=2;*/
6158:
6159: agelim=AGESUP;
6160: hstepm=stepsize*YEARM; /* Every year of age */
6161: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6162:
6163: /* hstepm=1; aff par mois*/
6164: pstamp(ficrespij);
6165: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6166: i1= pow(2,cptcoveff);
6167: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6168: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6169: /* k=k+1; */
6170: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6171: fprintf(ficrespij,"\n#****** ");
6172: for(j=1;j<=cptcoveff;j++)
6173: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6174: fprintf(ficrespij,"******\n");
6175:
6176: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6177: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6178: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6179:
6180: /* nhstepm=nhstepm*YEARM; aff par mois*/
6181:
6182: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6183: oldm=oldms;savm=savms;
6184: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6185: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6186: for(i=1; i<=nlstate;i++)
6187: for(j=1; j<=nlstate+ndeath;j++)
6188: fprintf(ficrespij," %1d-%1d",i,j);
6189: fprintf(ficrespij,"\n");
6190: for (h=0; h<=nhstepm; h++){
6191: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6192: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
6193: for(i=1; i<=nlstate;i++)
6194: for(j=1; j<=nlstate+ndeath;j++)
6195: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
6196: fprintf(ficrespij,"\n");
6197: }
6198: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6199: fprintf(ficrespij,"\n");
6200: }
6201: /*}*/
6202: }
6203: return 0;
6204: }
6205:
6206:
6207: /***********************************************/
6208: /**************** Main Program *****************/
6209: /***********************************************/
6210:
6211: int main(int argc, char *argv[])
6212: {
6213: #ifdef GSL
6214: const gsl_multimin_fminimizer_type *T;
6215: size_t iteri = 0, it;
6216: int rval = GSL_CONTINUE;
6217: int status = GSL_SUCCESS;
6218: double ssval;
6219: #endif
6220: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
6221: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6222:
6223: int jj, ll, li, lj, lk;
6224: int numlinepar=0; /* Current linenumber of parameter file */
6225: int itimes;
6226: int NDIM=2;
6227: int vpopbased=0;
6228:
6229: char ca[32], cb[32];
6230: /* FILE *fichtm; *//* Html File */
6231: /* FILE *ficgp;*/ /*Gnuplot File */
6232: struct stat info;
6233: double agedeb=0.;
6234: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
6235:
6236: double fret;
6237: double dum=0.; /* Dummy variable */
6238: double ***p3mat;
6239: double ***mobaverage;
6240:
6241: char line[MAXLINE];
6242: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
6243: char pathr[MAXLINE], pathimach[MAXLINE];
6244: char *tok, *val; /* pathtot */
6245: int firstobs=1, lastobs=10;
6246: int c, h , cpt;
6247: int jl=0;
6248: int i1, j1, jk, stepsize=0;
6249: int *tab;
6250: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6251: int mobilav=0,popforecast=0;
6252: int hstepm=0, nhstepm=0;
6253: int agemortsup;
6254: float sumlpop=0.;
6255: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6256: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6257:
6258: double bage=0, fage=110., age, agelim=0., agebase=0.;
6259: double ftolpl=FTOL;
6260: double **prlim;
6261: double ***param; /* Matrix of parameters */
6262: double *p;
6263: double **matcov; /* Matrix of covariance */
6264: double ***delti3; /* Scale */
6265: double *delti; /* Scale */
6266: double ***eij, ***vareij;
6267: double **varpl; /* Variances of prevalence limits by age */
6268: double *epj, vepp;
6269:
6270: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6271: double **ximort;
6272: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
6273: int *dcwave;
6274:
6275: char z[1]="c";
6276:
6277: /*char *strt;*/
6278: char strtend[80];
6279:
6280:
6281: /* setlocale (LC_ALL, ""); */
6282: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6283: /* textdomain (PACKAGE); */
6284: /* setlocale (LC_CTYPE, ""); */
6285: /* setlocale (LC_MESSAGES, ""); */
6286:
6287: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
6288: rstart_time = time(NULL);
6289: /* (void) gettimeofday(&start_time,&tzp);*/
6290: start_time = *localtime(&rstart_time);
6291: curr_time=start_time;
6292: /*tml = *localtime(&start_time.tm_sec);*/
6293: /* strcpy(strstart,asctime(&tml)); */
6294: strcpy(strstart,asctime(&start_time));
6295:
6296: /* printf("Localtime (at start)=%s",strstart); */
6297: /* tp.tm_sec = tp.tm_sec +86400; */
6298: /* tm = *localtime(&start_time.tm_sec); */
6299: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6300: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6301: /* tmg.tm_hour=tmg.tm_hour + 1; */
6302: /* tp.tm_sec = mktime(&tmg); */
6303: /* strt=asctime(&tmg); */
6304: /* printf("Time(after) =%s",strstart); */
6305: /* (void) time (&time_value);
6306: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6307: * tm = *localtime(&time_value);
6308: * strstart=asctime(&tm);
6309: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6310: */
6311:
6312: nberr=0; /* Number of errors and warnings */
6313: nbwarn=0;
6314: #ifdef WIN32
6315: _getcwd(pathcd, size);
6316: #else
6317: getcwd(pathcd, size);
6318: #endif
6319: syscompilerinfo(0);
6320: printf("\n%s\n%s",version,fullversion);
6321: if(argc <=1){
6322: printf("\nEnter the parameter file name: ");
6323: fgets(pathr,FILENAMELENGTH,stdin);
6324: i=strlen(pathr);
6325: if(pathr[i-1]=='\n')
6326: pathr[i-1]='\0';
6327: i=strlen(pathr);
6328: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6329: pathr[i-1]='\0';
6330: for (tok = pathr; tok != NULL; ){
6331: printf("Pathr |%s|\n",pathr);
6332: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6333: printf("val= |%s| pathr=%s\n",val,pathr);
6334: strcpy (pathtot, val);
6335: if(pathr[0] == '\0') break; /* Dirty */
6336: }
6337: }
6338: else{
6339: strcpy(pathtot,argv[1]);
6340: }
6341: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6342: /*cygwin_split_path(pathtot,path,optionfile);
6343: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6344: /* cutv(path,optionfile,pathtot,'\\');*/
6345:
6346: /* Split argv[0], imach program to get pathimach */
6347: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6348: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6349: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6350: /* strcpy(pathimach,argv[0]); */
6351: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6352: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6353: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6354: #ifdef WIN32
6355: _chdir(path); /* Can be a relative path */
6356: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6357: #else
6358: chdir(path); /* Can be a relative path */
6359: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6360: #endif
6361: printf("Current directory %s!\n",pathcd);
6362: strcpy(command,"mkdir ");
6363: strcat(command,optionfilefiname);
6364: if((outcmd=system(command)) != 0){
6365: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6366: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6367: /* fclose(ficlog); */
6368: /* exit(1); */
6369: }
6370: /* if((imk=mkdir(optionfilefiname))<0){ */
6371: /* perror("mkdir"); */
6372: /* } */
6373:
6374: /*-------- arguments in the command line --------*/
6375:
6376: /* Main Log file */
6377: strcat(filelog, optionfilefiname);
6378: strcat(filelog,".log"); /* */
6379: if((ficlog=fopen(filelog,"w"))==NULL) {
6380: printf("Problem with logfile %s\n",filelog);
6381: goto end;
6382: }
6383: fprintf(ficlog,"Log filename:%s\n",filelog);
6384: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6385: fprintf(ficlog,"\nEnter the parameter file name: \n");
6386: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6387: path=%s \n\
6388: optionfile=%s\n\
6389: optionfilext=%s\n\
6390: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6391:
6392: syscompilerinfo(0);
6393:
6394: printf("Local time (at start):%s",strstart);
6395: fprintf(ficlog,"Local time (at start): %s",strstart);
6396: fflush(ficlog);
6397: /* (void) gettimeofday(&curr_time,&tzp); */
6398: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6399:
6400: /* */
6401: strcpy(fileres,"r");
6402: strcat(fileres, optionfilefiname);
6403: strcat(fileres,".txt"); /* Other files have txt extension */
6404:
6405: /* Main ---------arguments file --------*/
6406:
6407: if((ficpar=fopen(optionfile,"r"))==NULL) {
6408: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6409: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6410: fflush(ficlog);
6411: /* goto end; */
6412: exit(70);
6413: }
6414:
6415:
6416:
6417: strcpy(filereso,"o");
6418: strcat(filereso,fileres);
6419: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6420: printf("Problem with Output resultfile: %s\n", filereso);
6421: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6422: fflush(ficlog);
6423: goto end;
6424: }
6425:
6426: /* Reads comments: lines beginning with '#' */
6427: numlinepar=0;
6428: while((c=getc(ficpar))=='#' && c!= EOF){
6429: ungetc(c,ficpar);
6430: fgets(line, MAXLINE, ficpar);
6431: numlinepar++;
6432: fputs(line,stdout);
6433: fputs(line,ficparo);
6434: fputs(line,ficlog);
6435: }
6436: ungetc(c,ficpar);
6437:
6438: 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);
6439: numlinepar++;
6440: 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);
6441: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6442: model[strlen(model)-1]='\0';
6443: 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);
6444: 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);
6445: fflush(ficlog);
6446: /* if(model[0]=='#'|| model[0]== '\0'){ */
6447: if(model[0]=='#'){
6448: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6449: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6450: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6451: if(mle != -1){
6452: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6453: exit(1);
6454: }
6455: }
6456: while((c=getc(ficpar))=='#' && c!= EOF){
6457: ungetc(c,ficpar);
6458: fgets(line, MAXLINE, ficpar);
6459: numlinepar++;
6460: fputs(line, stdout);
6461: //puts(line);
6462: fputs(line,ficparo);
6463: fputs(line,ficlog);
6464: }
6465: ungetc(c,ficpar);
6466:
6467:
6468: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6469: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6470: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6471: v1+v2*age+v2*v3 makes cptcovn = 3
6472: */
6473: if (strlen(model)>1)
6474: 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*/
6475: else
6476: ncovmodel=2; /* Constant and age */
6477: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6478: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6479: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6480: 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);
6481: 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);
6482: fflush(stdout);
6483: fclose (ficlog);
6484: goto end;
6485: }
6486: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6487: delti=delti3[1][1];
6488: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6489: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6490: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6491: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6492: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6493: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6494: fclose (ficparo);
6495: fclose (ficlog);
6496: goto end;
6497: exit(0);
6498: }
6499: else if(mle==-3) { /* Main Wizard */
6500: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6501: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6502: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6503: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6504: matcov=matrix(1,npar,1,npar);
6505: }
6506: else{
6507: /* Read guessed parameters */
6508: /* Reads comments: lines beginning with '#' */
6509: while((c=getc(ficpar))=='#' && c!= EOF){
6510: ungetc(c,ficpar);
6511: fgets(line, MAXLINE, ficpar);
6512: numlinepar++;
6513: fputs(line,stdout);
6514: fputs(line,ficparo);
6515: fputs(line,ficlog);
6516: }
6517: ungetc(c,ficpar);
6518:
6519: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6520: for(i=1; i <=nlstate; i++){
6521: j=0;
6522: for(jj=1; jj <=nlstate+ndeath; jj++){
6523: if(jj==i) continue;
6524: j++;
6525: fscanf(ficpar,"%1d%1d",&i1,&j1);
6526: if ((i1 != i) && (j1 != j)){
6527: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6528: It might be a problem of design; if ncovcol and the model are correct\n \
6529: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6530: exit(1);
6531: }
6532: fprintf(ficparo,"%1d%1d",i1,j1);
6533: if(mle==1)
6534: printf("%1d%1d",i,j);
6535: fprintf(ficlog,"%1d%1d",i,j);
6536: for(k=1; k<=ncovmodel;k++){
6537: fscanf(ficpar," %lf",¶m[i][j][k]);
6538: if(mle==1){
6539: printf(" %lf",param[i][j][k]);
6540: fprintf(ficlog," %lf",param[i][j][k]);
6541: }
6542: else
6543: fprintf(ficlog," %lf",param[i][j][k]);
6544: fprintf(ficparo," %lf",param[i][j][k]);
6545: }
6546: fscanf(ficpar,"\n");
6547: numlinepar++;
6548: if(mle==1)
6549: printf("\n");
6550: fprintf(ficlog,"\n");
6551: fprintf(ficparo,"\n");
6552: }
6553: }
6554: fflush(ficlog);
6555:
6556: /* Reads scales values */
6557: p=param[1][1];
6558:
6559: /* Reads comments: lines beginning with '#' */
6560: while((c=getc(ficpar))=='#' && c!= EOF){
6561: ungetc(c,ficpar);
6562: fgets(line, MAXLINE, ficpar);
6563: numlinepar++;
6564: fputs(line,stdout);
6565: fputs(line,ficparo);
6566: fputs(line,ficlog);
6567: }
6568: ungetc(c,ficpar);
6569:
6570: for(i=1; i <=nlstate; i++){
6571: for(j=1; j <=nlstate+ndeath-1; j++){
6572: fscanf(ficpar,"%1d%1d",&i1,&j1);
6573: if ( (i1-i) * (j1-j) != 0){
6574: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6575: exit(1);
6576: }
6577: printf("%1d%1d",i,j);
6578: fprintf(ficparo,"%1d%1d",i1,j1);
6579: fprintf(ficlog,"%1d%1d",i1,j1);
6580: for(k=1; k<=ncovmodel;k++){
6581: fscanf(ficpar,"%le",&delti3[i][j][k]);
6582: printf(" %le",delti3[i][j][k]);
6583: fprintf(ficparo," %le",delti3[i][j][k]);
6584: fprintf(ficlog," %le",delti3[i][j][k]);
6585: }
6586: fscanf(ficpar,"\n");
6587: numlinepar++;
6588: printf("\n");
6589: fprintf(ficparo,"\n");
6590: fprintf(ficlog,"\n");
6591: }
6592: }
6593: fflush(ficlog);
6594:
6595: /* Reads covariance matrix */
6596: delti=delti3[1][1];
6597:
6598:
6599: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6600:
6601: /* Reads comments: lines beginning with '#' */
6602: while((c=getc(ficpar))=='#' && c!= EOF){
6603: ungetc(c,ficpar);
6604: fgets(line, MAXLINE, ficpar);
6605: numlinepar++;
6606: fputs(line,stdout);
6607: fputs(line,ficparo);
6608: fputs(line,ficlog);
6609: }
6610: ungetc(c,ficpar);
6611:
6612: matcov=matrix(1,npar,1,npar);
6613: for(i=1; i <=npar; i++)
6614: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6615:
6616: for(i=1; i <=npar; i++){
6617: fscanf(ficpar,"%s",str);
6618: if(mle==1)
6619: printf("%s",str);
6620: fprintf(ficlog,"%s",str);
6621: fprintf(ficparo,"%s",str);
6622: for(j=1; j <=i; j++){
6623: fscanf(ficpar," %le",&matcov[i][j]);
6624: if(mle==1){
6625: printf(" %.5le",matcov[i][j]);
6626: }
6627: fprintf(ficlog," %.5le",matcov[i][j]);
6628: fprintf(ficparo," %.5le",matcov[i][j]);
6629: }
6630: fscanf(ficpar,"\n");
6631: numlinepar++;
6632: if(mle==1)
6633: printf("\n");
6634: fprintf(ficlog,"\n");
6635: fprintf(ficparo,"\n");
6636: }
6637: for(i=1; i <=npar; i++)
6638: for(j=i+1;j<=npar;j++)
6639: matcov[i][j]=matcov[j][i];
6640:
6641: if(mle==1)
6642: printf("\n");
6643: fprintf(ficlog,"\n");
6644:
6645: fflush(ficlog);
6646:
6647: /*-------- Rewriting parameter file ----------*/
6648: strcpy(rfileres,"r"); /* "Rparameterfile */
6649: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6650: strcat(rfileres,"."); /* */
6651: strcat(rfileres,optionfilext); /* Other files have txt extension */
6652: if((ficres =fopen(rfileres,"w"))==NULL) {
6653: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6654: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6655: }
6656: fprintf(ficres,"#%s\n",version);
6657: } /* End of mle != -3 */
6658:
6659: /* Main data
6660: */
6661: n= lastobs;
6662: num=lvector(1,n);
6663: moisnais=vector(1,n);
6664: annais=vector(1,n);
6665: moisdc=vector(1,n);
6666: andc=vector(1,n);
6667: agedc=vector(1,n);
6668: cod=ivector(1,n);
6669: weight=vector(1,n);
6670: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6671: mint=matrix(1,maxwav,1,n);
6672: anint=matrix(1,maxwav,1,n);
6673: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6674: tab=ivector(1,NCOVMAX);
6675: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6676:
6677: /* Reads data from file datafile */
6678: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6679: goto end;
6680:
6681: /* Calculation of the number of parameters from char model */
6682: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6683: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6684: k=3 V4 Tvar[k=3]= 4 (from V4)
6685: k=2 V1 Tvar[k=2]= 1 (from V1)
6686: k=1 Tvar[1]=2 (from V2)
6687: */
6688: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6689: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6690: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6691: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6692: */
6693: /* For model-covariate k tells which data-covariate to use but
6694: because this model-covariate is a construction we invent a new column
6695: ncovcol + k1
6696: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6697: Tvar[3=V1*V4]=4+1 etc */
6698: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6699: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6700: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6701: */
6702: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6703: 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
6704: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6705: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6706: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6707: 4 covariates (3 plus signs)
6708: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6709: */
6710:
6711: /* Main decodemodel */
6712:
6713:
6714: if(decodemodel(model, lastobs) == 1)
6715: goto end;
6716:
6717: if((double)(lastobs-imx)/(double)imx > 1.10){
6718: nbwarn++;
6719: 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);
6720: 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);
6721: }
6722: /* if(mle==1){*/
6723: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6724: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6725: }
6726:
6727: /*-calculation of age at interview from date of interview and age at death -*/
6728: agev=matrix(1,maxwav,1,imx);
6729:
6730: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6731: goto end;
6732:
6733:
6734: agegomp=(int)agemin;
6735: free_vector(moisnais,1,n);
6736: free_vector(annais,1,n);
6737: /* free_matrix(mint,1,maxwav,1,n);
6738: free_matrix(anint,1,maxwav,1,n);*/
6739: free_vector(moisdc,1,n);
6740: free_vector(andc,1,n);
6741: /* */
6742:
6743: wav=ivector(1,imx);
6744: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6745: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6746: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6747:
6748: /* Concatenates waves */
6749: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6750: /* */
6751:
6752: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6753:
6754: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6755: ncodemax[1]=1;
6756: Ndum =ivector(-1,NCOVMAX);
6757: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
6758: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6759: /* Nbcode gives the value of the lth modality of jth covariate, in
6760: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6761: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
6762:
6763: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6764: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6765: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
6766: h=0;
6767:
6768:
6769: /*if (cptcovn > 0) */
6770:
6771:
6772: m=pow(2,cptcoveff);
6773:
6774: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6775: 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 */
6776: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6777: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6778: h++;
6779: if (h>m)
6780: h=1;
6781: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6782: * For k=4 covariates, h goes from 1 to 2**k
6783: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6784: * h\k 1 2 3 4
6785: *______________________________
6786: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6787: * 2 2 1 1 1
6788: * 3 i=2 1 2 1 1
6789: * 4 2 2 1 1
6790: * 5 i=3 1 i=2 1 2 1
6791: * 6 2 1 2 1
6792: * 7 i=4 1 2 2 1
6793: * 8 2 2 2 1
6794: * 9 i=5 1 i=3 1 i=2 1 1
6795: * 10 2 1 1 1
6796: * 11 i=6 1 2 1 1
6797: * 12 2 2 1 1
6798: * 13 i=7 1 i=4 1 2 1
6799: * 14 2 1 2 1
6800: * 15 i=8 1 2 2 1
6801: * 16 2 2 2 1
6802: */
6803: codtab[h][k]=j;
6804: /* codtab[12][3]=1; */
6805: /*codtab[h][Tvar[k]]=j;*/
6806: 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]]);
6807: }
6808: }
6809: }
6810: }
6811: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6812: codtab[1][2]=1;codtab[2][2]=2; */
6813: /* for(i=1; i <=m ;i++){
6814: for(k=1; k <=cptcovn; k++){
6815: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6816: }
6817: printf("\n");
6818: }
6819: scanf("%d",i);*/
6820:
6821: free_ivector(Ndum,-1,NCOVMAX);
6822:
6823:
6824:
6825: /* Initialisation of ----------- gnuplot -------------*/
6826: strcpy(optionfilegnuplot,optionfilefiname);
6827: if(mle==-3)
6828: strcat(optionfilegnuplot,"-mort");
6829: strcat(optionfilegnuplot,".gp");
6830:
6831: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6832: printf("Problem with file %s",optionfilegnuplot);
6833: }
6834: else{
6835: fprintf(ficgp,"\n# %s\n", version);
6836: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6837: //fprintf(ficgp,"set missing 'NaNq'\n");
6838: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6839: }
6840: /* fclose(ficgp);*/
6841:
6842:
6843: /* Initialisation of --------- index.htm --------*/
6844:
6845: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6846: if(mle==-3)
6847: strcat(optionfilehtm,"-mort");
6848: strcat(optionfilehtm,".htm");
6849: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6850: printf("Problem with %s \n",optionfilehtm);
6851: exit(0);
6852: }
6853:
6854: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6855: strcat(optionfilehtmcov,"-cov.htm");
6856: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6857: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6858: }
6859: else{
6860: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6861: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6862: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6863: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6864: }
6865:
6866: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6867: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6868: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6869: \n\
6870: <hr size=\"2\" color=\"#EC5E5E\">\
6871: <ul><li><h4>Parameter files</h4>\n\
6872: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6873: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6874: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6875: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6876: - Date and time at start: %s</ul>\n",\
6877: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6878: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6879: fileres,fileres,\
6880: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6881: fflush(fichtm);
6882:
6883: strcpy(pathr,path);
6884: strcat(pathr,optionfilefiname);
6885: #ifdef WIN32
6886: _chdir(optionfilefiname); /* Move to directory named optionfile */
6887: #else
6888: chdir(optionfilefiname); /* Move to directory named optionfile */
6889: #endif
6890:
6891:
6892: /* Calculates basic frequencies. Computes observed prevalence at single age
6893: and prints on file fileres'p'. */
6894: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6895:
6896: fprintf(fichtm,"\n");
6897: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6898: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6899: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6900: imx,agemin,agemax,jmin,jmax,jmean);
6901: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6902: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6903: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6904: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6905: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6906:
6907:
6908: /* For Powell, parameters are in a vector p[] starting at p[1]
6909: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6910: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6911:
6912: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6913: /* For mortality only */
6914: if (mle==-3){
6915: ximort=matrix(1,NDIM,1,NDIM);
6916: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6917: cens=ivector(1,n);
6918: ageexmed=vector(1,n);
6919: agecens=vector(1,n);
6920: dcwave=ivector(1,n);
6921:
6922: for (i=1; i<=imx; i++){
6923: dcwave[i]=-1;
6924: for (m=firstpass; m<=lastpass; m++)
6925: if (s[m][i]>nlstate) {
6926: dcwave[i]=m;
6927: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6928: break;
6929: }
6930: }
6931:
6932: for (i=1; i<=imx; i++) {
6933: if (wav[i]>0){
6934: ageexmed[i]=agev[mw[1][i]][i];
6935: j=wav[i];
6936: agecens[i]=1.;
6937:
6938: if (ageexmed[i]> 1 && wav[i] > 0){
6939: agecens[i]=agev[mw[j][i]][i];
6940: cens[i]= 1;
6941: }else if (ageexmed[i]< 1)
6942: cens[i]= -1;
6943: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6944: cens[i]=0 ;
6945: }
6946: else cens[i]=-1;
6947: }
6948:
6949: for (i=1;i<=NDIM;i++) {
6950: for (j=1;j<=NDIM;j++)
6951: ximort[i][j]=(i == j ? 1.0 : 0.0);
6952: }
6953:
6954: /*p[1]=0.0268; p[NDIM]=0.083;*/
6955: /*printf("%lf %lf", p[1], p[2]);*/
6956:
6957:
6958: #ifdef GSL
6959: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6960: #else
6961: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6962: #endif
6963: strcpy(filerespow,"pow-mort");
6964: strcat(filerespow,fileres);
6965: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6966: printf("Problem with resultfile: %s\n", filerespow);
6967: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6968: }
6969: #ifdef GSL
6970: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6971: #else
6972: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6973: #endif
6974: /* for (i=1;i<=nlstate;i++)
6975: for(j=1;j<=nlstate+ndeath;j++)
6976: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6977: */
6978: fprintf(ficrespow,"\n");
6979: #ifdef GSL
6980: /* gsl starts here */
6981: T = gsl_multimin_fminimizer_nmsimplex;
6982: gsl_multimin_fminimizer *sfm = NULL;
6983: gsl_vector *ss, *x;
6984: gsl_multimin_function minex_func;
6985:
6986: /* Initial vertex size vector */
6987: ss = gsl_vector_alloc (NDIM);
6988:
6989: if (ss == NULL){
6990: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6991: }
6992: /* Set all step sizes to 1 */
6993: gsl_vector_set_all (ss, 0.001);
6994:
6995: /* Starting point */
6996:
6997: x = gsl_vector_alloc (NDIM);
6998:
6999: if (x == NULL){
7000: gsl_vector_free(ss);
7001: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7002: }
7003:
7004: /* Initialize method and iterate */
7005: /* p[1]=0.0268; p[NDIM]=0.083; */
7006: /* gsl_vector_set(x, 0, 0.0268); */
7007: /* gsl_vector_set(x, 1, 0.083); */
7008: gsl_vector_set(x, 0, p[1]);
7009: gsl_vector_set(x, 1, p[2]);
7010:
7011: minex_func.f = &gompertz_f;
7012: minex_func.n = NDIM;
7013: minex_func.params = (void *)&p; /* ??? */
7014:
7015: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7016: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7017:
7018: printf("Iterations beginning .....\n\n");
7019: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7020:
7021: iteri=0;
7022: while (rval == GSL_CONTINUE){
7023: iteri++;
7024: status = gsl_multimin_fminimizer_iterate(sfm);
7025:
7026: if (status) printf("error: %s\n", gsl_strerror (status));
7027: fflush(0);
7028:
7029: if (status)
7030: break;
7031:
7032: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7033: ssval = gsl_multimin_fminimizer_size (sfm);
7034:
7035: if (rval == GSL_SUCCESS)
7036: printf ("converged to a local maximum at\n");
7037:
7038: printf("%5d ", iteri);
7039: for (it = 0; it < NDIM; it++){
7040: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7041: }
7042: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7043: }
7044:
7045: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7046:
7047: gsl_vector_free(x); /* initial values */
7048: gsl_vector_free(ss); /* inital step size */
7049: for (it=0; it<NDIM; it++){
7050: p[it+1]=gsl_vector_get(sfm->x,it);
7051: fprintf(ficrespow," %.12lf", p[it]);
7052: }
7053: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7054: #endif
7055: #ifdef POWELL
7056: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7057: #endif
7058: fclose(ficrespow);
7059:
7060: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7061:
7062: for(i=1; i <=NDIM; i++)
7063: for(j=i+1;j<=NDIM;j++)
7064: matcov[i][j]=matcov[j][i];
7065:
7066: printf("\nCovariance matrix\n ");
7067: for(i=1; i <=NDIM; i++) {
7068: for(j=1;j<=NDIM;j++){
7069: printf("%f ",matcov[i][j]);
7070: }
7071: printf("\n ");
7072: }
7073:
7074: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7075: for (i=1;i<=NDIM;i++)
7076: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7077:
7078: lsurv=vector(1,AGESUP);
7079: lpop=vector(1,AGESUP);
7080: tpop=vector(1,AGESUP);
7081: lsurv[agegomp]=100000;
7082:
7083: for (k=agegomp;k<=AGESUP;k++) {
7084: agemortsup=k;
7085: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7086: }
7087:
7088: for (k=agegomp;k<agemortsup;k++)
7089: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7090:
7091: for (k=agegomp;k<agemortsup;k++){
7092: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7093: sumlpop=sumlpop+lpop[k];
7094: }
7095:
7096: tpop[agegomp]=sumlpop;
7097: for (k=agegomp;k<(agemortsup-3);k++){
7098: /* tpop[k+1]=2;*/
7099: tpop[k+1]=tpop[k]-lpop[k];
7100: }
7101:
7102:
7103: printf("\nAge lx qx dx Lx Tx e(x)\n");
7104: for (k=agegomp;k<(agemortsup-2);k++)
7105: 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]);
7106:
7107:
7108: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7109: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7110:
7111: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7112: stepm, weightopt,\
7113: model,imx,p,matcov,agemortsup);
7114:
7115: free_vector(lsurv,1,AGESUP);
7116: free_vector(lpop,1,AGESUP);
7117: free_vector(tpop,1,AGESUP);
7118: #ifdef GSL
7119: free_ivector(cens,1,n);
7120: free_vector(agecens,1,n);
7121: free_ivector(dcwave,1,n);
7122: free_matrix(ximort,1,NDIM,1,NDIM);
7123: #endif
7124: } /* Endof if mle==-3 mortality only */
7125: /* Standard maximisation */
7126: else{ /* For mle >=1 */
7127: globpr=0;/* debug */
7128: /* Computes likelihood for initial parameters */
7129: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7130: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7131: for (k=1; k<=npar;k++)
7132: printf(" %d %8.5f",k,p[k]);
7133: printf("\n");
7134: globpr=1; /* again, to print the contributions */
7135: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7136: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7137: for (k=1; k<=npar;k++)
7138: printf(" %d %8.5f",k,p[k]);
7139: printf("\n");
7140: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
7141: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7142: }
7143:
7144: /*--------- results files --------------*/
7145: 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);
7146:
7147:
7148: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7149: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7150: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7151: for(i=1,jk=1; i <=nlstate; i++){
7152: for(k=1; k <=(nlstate+ndeath); k++){
7153: if (k != i) {
7154: printf("%d%d ",i,k);
7155: fprintf(ficlog,"%d%d ",i,k);
7156: fprintf(ficres,"%1d%1d ",i,k);
7157: for(j=1; j <=ncovmodel; j++){
7158: printf("%12.7f ",p[jk]);
7159: fprintf(ficlog,"%12.7f ",p[jk]);
7160: fprintf(ficres,"%12.7f ",p[jk]);
7161: jk++;
7162: }
7163: printf("\n");
7164: fprintf(ficlog,"\n");
7165: fprintf(ficres,"\n");
7166: }
7167: }
7168: }
7169: if(mle!=0){
7170: /* Computing hessian and covariance matrix */
7171: ftolhess=ftol; /* Usually correct */
7172: hesscov(matcov, p, npar, delti, ftolhess, func);
7173: }
7174: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7175: printf("# Scales (for hessian or gradient estimation)\n");
7176: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7177: for(i=1,jk=1; i <=nlstate; i++){
7178: for(j=1; j <=nlstate+ndeath; j++){
7179: if (j!=i) {
7180: fprintf(ficres,"%1d%1d",i,j);
7181: printf("%1d%1d",i,j);
7182: fprintf(ficlog,"%1d%1d",i,j);
7183: for(k=1; k<=ncovmodel;k++){
7184: printf(" %.5e",delti[jk]);
7185: fprintf(ficlog," %.5e",delti[jk]);
7186: fprintf(ficres," %.5e",delti[jk]);
7187: jk++;
7188: }
7189: printf("\n");
7190: fprintf(ficlog,"\n");
7191: fprintf(ficres,"\n");
7192: }
7193: }
7194: }
7195:
7196: 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");
7197: if(mle>=1)
7198: 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");
7199: 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");
7200: /* # 121 Var(a12)\n\ */
7201: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7202: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7203: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7204: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7205: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7206: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7207: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7208:
7209:
7210: /* Just to have a covariance matrix which will be more understandable
7211: even is we still don't want to manage dictionary of variables
7212: */
7213: for(itimes=1;itimes<=2;itimes++){
7214: jj=0;
7215: for(i=1; i <=nlstate; i++){
7216: for(j=1; j <=nlstate+ndeath; j++){
7217: if(j==i) continue;
7218: for(k=1; k<=ncovmodel;k++){
7219: jj++;
7220: ca[0]= k+'a'-1;ca[1]='\0';
7221: if(itimes==1){
7222: if(mle>=1)
7223: printf("#%1d%1d%d",i,j,k);
7224: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7225: fprintf(ficres,"#%1d%1d%d",i,j,k);
7226: }else{
7227: if(mle>=1)
7228: printf("%1d%1d%d",i,j,k);
7229: fprintf(ficlog,"%1d%1d%d",i,j,k);
7230: fprintf(ficres,"%1d%1d%d",i,j,k);
7231: }
7232: ll=0;
7233: for(li=1;li <=nlstate; li++){
7234: for(lj=1;lj <=nlstate+ndeath; lj++){
7235: if(lj==li) continue;
7236: for(lk=1;lk<=ncovmodel;lk++){
7237: ll++;
7238: if(ll<=jj){
7239: cb[0]= lk +'a'-1;cb[1]='\0';
7240: if(ll<jj){
7241: if(itimes==1){
7242: if(mle>=1)
7243: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7244: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7245: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7246: }else{
7247: if(mle>=1)
7248: printf(" %.5e",matcov[jj][ll]);
7249: fprintf(ficlog," %.5e",matcov[jj][ll]);
7250: fprintf(ficres," %.5e",matcov[jj][ll]);
7251: }
7252: }else{
7253: if(itimes==1){
7254: if(mle>=1)
7255: printf(" Var(%s%1d%1d)",ca,i,j);
7256: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7257: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7258: }else{
7259: if(mle>=1)
7260: printf(" %.5e",matcov[jj][ll]);
7261: fprintf(ficlog," %.5e",matcov[jj][ll]);
7262: fprintf(ficres," %.5e",matcov[jj][ll]);
7263: }
7264: }
7265: }
7266: } /* end lk */
7267: } /* end lj */
7268: } /* end li */
7269: if(mle>=1)
7270: printf("\n");
7271: fprintf(ficlog,"\n");
7272: fprintf(ficres,"\n");
7273: numlinepar++;
7274: } /* end k*/
7275: } /*end j */
7276: } /* end i */
7277: } /* end itimes */
7278:
7279: fflush(ficlog);
7280: fflush(ficres);
7281:
7282: while((c=getc(ficpar))=='#' && c!= EOF){
7283: ungetc(c,ficpar);
7284: fgets(line, MAXLINE, ficpar);
7285: fputs(line,stdout);
7286: fputs(line,ficparo);
7287: }
7288: ungetc(c,ficpar);
7289:
7290: estepm=0;
7291: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7292: if (estepm==0 || estepm < stepm) estepm=stepm;
7293: if (fage <= 2) {
7294: bage = ageminpar;
7295: fage = agemaxpar;
7296: }
7297:
7298: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7299: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7300: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7301:
7302: /* Other stuffs, more or less useful */
7303: while((c=getc(ficpar))=='#' && c!= EOF){
7304: ungetc(c,ficpar);
7305: fgets(line, MAXLINE, ficpar);
7306: fputs(line,stdout);
7307: fputs(line,ficparo);
7308: }
7309: ungetc(c,ficpar);
7310:
7311: 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);
7312: 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);
7313: 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);
7314: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7315: 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);
7316:
7317: while((c=getc(ficpar))=='#' && c!= EOF){
7318: ungetc(c,ficpar);
7319: fgets(line, MAXLINE, ficpar);
7320: fputs(line,stdout);
7321: fputs(line,ficparo);
7322: }
7323: ungetc(c,ficpar);
7324:
7325:
7326: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7327: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7328:
7329: fscanf(ficpar,"pop_based=%d\n",&popbased);
7330: fprintf(ficparo,"pop_based=%d\n",popbased);
7331: fprintf(ficres,"pop_based=%d\n",popbased);
7332:
7333: while((c=getc(ficpar))=='#' && c!= EOF){
7334: ungetc(c,ficpar);
7335: fgets(line, MAXLINE, ficpar);
7336: fputs(line,stdout);
7337: fputs(line,ficparo);
7338: }
7339: ungetc(c,ficpar);
7340:
7341: 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);
7342: 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);
7343: 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);
7344: 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);
7345: 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);
7346: /* day and month of proj2 are not used but only year anproj2.*/
7347:
7348:
7349:
7350: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7351: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
7352:
7353: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7354: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7355:
7356: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7357: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7358: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7359:
7360: /*------------ free_vector -------------*/
7361: /* chdir(path); */
7362:
7363: free_ivector(wav,1,imx);
7364: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7365: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7366: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7367: free_lvector(num,1,n);
7368: free_vector(agedc,1,n);
7369: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7370: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7371: fclose(ficparo);
7372: fclose(ficres);
7373:
7374:
7375: /* Other results (useful)*/
7376:
7377:
7378: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
7379: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7380: prlim=matrix(1,nlstate,1,nlstate);
7381: prevalence_limit(p, prlim, ageminpar, agemaxpar);
7382: fclose(ficrespl);
7383:
7384: #ifdef FREEEXIT2
7385: #include "freeexit2.h"
7386: #endif
7387:
7388: /*------------- h Pij x at various ages ------------*/
7389: /*#include "hpijx.h"*/
7390: hPijx(p, bage, fage);
7391: fclose(ficrespij);
7392:
7393: /*-------------- Variance of one-step probabilities---*/
7394: k=1;
7395: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7396:
7397:
7398: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7399: for(i=1;i<=AGESUP;i++)
7400: for(j=1;j<=NCOVMAX;j++)
7401: for(k=1;k<=NCOVMAX;k++)
7402: probs[i][j][k]=0.;
7403:
7404: /*---------- Forecasting ------------------*/
7405: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7406: if(prevfcast==1){
7407: /* if(stepm ==1){*/
7408: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7409: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7410: /* } */
7411: /* else{ */
7412: /* erreur=108; */
7413: /* 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); */
7414: /* 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); */
7415: /* } */
7416: }
7417:
7418: /* ------ Other prevalence ratios------------ */
7419:
7420: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7421:
7422: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7423: /* 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",\
7424: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7425: */
7426:
7427: if (mobilav!=0) {
7428: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7429: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7430: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7431: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7432: }
7433: }
7434:
7435:
7436: /*---------- Health expectancies, no variances ------------*/
7437:
7438: strcpy(filerese,"e");
7439: strcat(filerese,fileres);
7440: if((ficreseij=fopen(filerese,"w"))==NULL) {
7441: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7442: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7443: }
7444: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7445: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
7446: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7447: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7448:
7449: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7450: fprintf(ficreseij,"\n#****** ");
7451: for(j=1;j<=cptcoveff;j++) {
7452: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7453: }
7454: fprintf(ficreseij,"******\n");
7455:
7456: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7457: oldm=oldms;savm=savms;
7458: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7459:
7460: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7461: /*}*/
7462: }
7463: fclose(ficreseij);
7464:
7465:
7466: /*---------- Health expectancies and variances ------------*/
7467:
7468:
7469: strcpy(filerest,"t");
7470: strcat(filerest,fileres);
7471: if((ficrest=fopen(filerest,"w"))==NULL) {
7472: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7473: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7474: }
7475: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7476: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7477:
7478:
7479: strcpy(fileresstde,"stde");
7480: strcat(fileresstde,fileres);
7481: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7482: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7483: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7484: }
7485: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7486: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7487:
7488: strcpy(filerescve,"cve");
7489: strcat(filerescve,fileres);
7490: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7491: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7492: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7493: }
7494: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7495: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7496:
7497: strcpy(fileresv,"v");
7498: strcat(fileresv,fileres);
7499: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7500: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7501: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7502: }
7503: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7504: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7505:
7506: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7507: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7508:
7509: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7510: fprintf(ficrest,"\n#****** ");
7511: for(j=1;j<=cptcoveff;j++)
7512: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7513: fprintf(ficrest,"******\n");
7514:
7515: fprintf(ficresstdeij,"\n#****** ");
7516: fprintf(ficrescveij,"\n#****** ");
7517: for(j=1;j<=cptcoveff;j++) {
7518: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7519: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7520: }
7521: fprintf(ficresstdeij,"******\n");
7522: fprintf(ficrescveij,"******\n");
7523:
7524: fprintf(ficresvij,"\n#****** ");
7525: for(j=1;j<=cptcoveff;j++)
7526: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7527: fprintf(ficresvij,"******\n");
7528:
7529: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7530: oldm=oldms;savm=savms;
7531: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7532: /*
7533: */
7534: /* goto endfree; */
7535:
7536: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7537: pstamp(ficrest);
7538:
7539:
7540: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7541: oldm=oldms;savm=savms; /* Segmentation fault */
7542: cptcod= 0; /* To be deleted */
7543: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
7544: 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 ");
7545: if(vpopbased==1)
7546: 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);
7547: else
7548: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7549: fprintf(ficrest,"# Age e.. (std) ");
7550: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7551: fprintf(ficrest,"\n");
7552:
7553: epj=vector(1,nlstate+1);
7554: for(age=bage; age <=fage ;age++){
7555: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7556: if (vpopbased==1) {
7557: if(mobilav ==0){
7558: for(i=1; i<=nlstate;i++)
7559: prlim[i][i]=probs[(int)age][i][k];
7560: }else{ /* mobilav */
7561: for(i=1; i<=nlstate;i++)
7562: prlim[i][i]=mobaverage[(int)age][i][k];
7563: }
7564: }
7565:
7566: fprintf(ficrest," %4.0f",age);
7567: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7568: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7569: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7570: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7571: }
7572: epj[nlstate+1] +=epj[j];
7573: }
7574:
7575: for(i=1, vepp=0.;i <=nlstate;i++)
7576: for(j=1;j <=nlstate;j++)
7577: vepp += vareij[i][j][(int)age];
7578: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7579: for(j=1;j <=nlstate;j++){
7580: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7581: }
7582: fprintf(ficrest,"\n");
7583: }
7584: }
7585: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7586: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7587: free_vector(epj,1,nlstate+1);
7588: /*}*/
7589: }
7590: free_vector(weight,1,n);
7591: free_imatrix(Tvard,1,NCOVMAX,1,2);
7592: free_imatrix(s,1,maxwav+1,1,n);
7593: free_matrix(anint,1,maxwav,1,n);
7594: free_matrix(mint,1,maxwav,1,n);
7595: free_ivector(cod,1,n);
7596: free_ivector(tab,1,NCOVMAX);
7597: fclose(ficresstdeij);
7598: fclose(ficrescveij);
7599: fclose(ficresvij);
7600: fclose(ficrest);
7601: fclose(ficpar);
7602:
7603: /*------- Variance of period (stable) prevalence------*/
7604:
7605: strcpy(fileresvpl,"vpl");
7606: strcat(fileresvpl,fileres);
7607: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7608: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7609: exit(0);
7610: }
7611: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7612:
7613: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7614: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7615:
7616: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7617: fprintf(ficresvpl,"\n#****** ");
7618: for(j=1;j<=cptcoveff;j++)
7619: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7620: fprintf(ficresvpl,"******\n");
7621:
7622: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7623: oldm=oldms;savm=savms;
7624: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7625: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7626: /*}*/
7627: }
7628:
7629: fclose(ficresvpl);
7630:
7631: /*---------- End : free ----------------*/
7632: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7633: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7634: } /* mle==-3 arrives here for freeing */
7635: /* endfree:*/
7636: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7637: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7638: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7639: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7640: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7641: free_matrix(covar,0,NCOVMAX,1,n);
7642: free_matrix(matcov,1,npar,1,npar);
7643: /*free_vector(delti,1,npar);*/
7644: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7645: free_matrix(agev,1,maxwav,1,imx);
7646: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7647:
7648: free_ivector(ncodemax,1,NCOVMAX);
7649: free_ivector(Tvar,1,NCOVMAX);
7650: free_ivector(Tprod,1,NCOVMAX);
7651: free_ivector(Tvaraff,1,NCOVMAX);
7652: free_ivector(Tage,1,NCOVMAX);
7653:
7654: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7655: free_imatrix(codtab,1,100,1,10);
7656: fflush(fichtm);
7657: fflush(ficgp);
7658:
7659:
7660: if((nberr >0) || (nbwarn>0)){
7661: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7662: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7663: }else{
7664: printf("End of Imach\n");
7665: fprintf(ficlog,"End of Imach\n");
7666: }
7667: printf("See log file on %s\n",filelog);
7668: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7669: /*(void) gettimeofday(&end_time,&tzp);*/
7670: rend_time = time(NULL);
7671: end_time = *localtime(&rend_time);
7672: /* tml = *localtime(&end_time.tm_sec); */
7673: strcpy(strtend,asctime(&end_time));
7674: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7675: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7676: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7677:
7678: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7679: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7680: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7681: /* printf("Total time was %d uSec.\n", total_usecs);*/
7682: /* if(fileappend(fichtm,optionfilehtm)){ */
7683: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7684: fclose(fichtm);
7685: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7686: fclose(fichtmcov);
7687: fclose(ficgp);
7688: fclose(ficlog);
7689: /*------ End -----------*/
7690:
7691:
7692: printf("Before Current directory %s!\n",pathcd);
7693: #ifdef WIN32
7694: if (_chdir(pathcd) != 0)
7695: printf("Can't move to directory %s!\n",path);
7696: if(_getcwd(pathcd,MAXLINE) > 0)
7697: #else
7698: if(chdir(pathcd) != 0)
7699: printf("Can't move to directory %s!\n", path);
7700: if (getcwd(pathcd, MAXLINE) > 0)
7701: #endif
7702: printf("Current directory %s!\n",pathcd);
7703: /*strcat(plotcmd,CHARSEPARATOR);*/
7704: sprintf(plotcmd,"gnuplot");
7705: #ifdef _WIN32
7706: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7707: #endif
7708: if(!stat(plotcmd,&info)){
7709: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7710: if(!stat(getenv("GNUPLOTBIN"),&info)){
7711: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7712: }else
7713: strcpy(pplotcmd,plotcmd);
7714: #ifdef __unix
7715: strcpy(plotcmd,GNUPLOTPROGRAM);
7716: if(!stat(plotcmd,&info)){
7717: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7718: }else
7719: strcpy(pplotcmd,plotcmd);
7720: #endif
7721: }else
7722: strcpy(pplotcmd,plotcmd);
7723:
7724: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7725: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7726:
7727: if((outcmd=system(plotcmd)) != 0){
7728: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7729: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7730: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7731: if((outcmd=system(plotcmd)) != 0)
7732: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7733: }
7734: printf(" Successful, please wait...");
7735: while (z[0] != 'q') {
7736: /* chdir(path); */
7737: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7738: scanf("%s",z);
7739: /* if (z[0] == 'c') system("./imach"); */
7740: if (z[0] == 'e') {
7741: #ifdef __APPLE__
7742: sprintf(pplotcmd, "open %s", optionfilehtm);
7743: #elif __linux
7744: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7745: #else
7746: sprintf(pplotcmd, "%s", optionfilehtm);
7747: #endif
7748: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7749: system(pplotcmd);
7750: }
7751: else if (z[0] == 'g') system(plotcmd);
7752: else if (z[0] == 'q') exit(0);
7753: }
7754: end:
7755: while (z[0] != 'q') {
7756: printf("\nType q for exiting: ");
7757: scanf("%s",z);
7758: }
7759: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>