File:
[Local Repository] /
imach /
src /
imach.c
Revision
1.183:
download - view:
text,
annotated -
select for diffs
Tue Mar 10 20:34:32 2015 UTC (9 years, 5 months ago) by
brouard
Branches:
MAIN
CVS tags:
HEAD
Summary: 0.98q0, trying with directest, mnbrak fixed
We use directest instead of original Powell test; probably no
incidence on the results, but better justifications;
We fixed Numerical Recipes mnbrak routine which was wrong and gave
wrong results.
1: /* $Id: imach.c,v 1.183 2015/03/10 20:34:32 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.183 2015/03/10 20:34:32 brouard
5: Summary: 0.98q0, trying with directest, mnbrak fixed
6:
7: We use directest instead of original Powell test; probably no
8: incidence on the results, but better justifications;
9: We fixed Numerical Recipes mnbrak routine which was wrong and gave
10: wrong results.
11:
12: Revision 1.182 2015/02/12 08:19:57 brouard
13: Summary: Trying to keep directest which seems simpler and more general
14: Author: Nicolas Brouard
15:
16: Revision 1.181 2015/02/11 23:22:24 brouard
17: Summary: Comments on Powell added
18:
19: Author:
20:
21: Revision 1.180 2015/02/11 17:33:45 brouard
22: Summary: Finishing move from main to function (hpijx and prevalence_limit)
23:
24: Revision 1.179 2015/01/04 09:57:06 brouard
25: Summary: back to OS/X
26:
27: Revision 1.178 2015/01/04 09:35:48 brouard
28: *** empty log message ***
29:
30: Revision 1.177 2015/01/03 18:40:56 brouard
31: Summary: Still testing ilc32 on OSX
32:
33: Revision 1.176 2015/01/03 16:45:04 brouard
34: *** empty log message ***
35:
36: Revision 1.175 2015/01/03 16:33:42 brouard
37: *** empty log message ***
38:
39: Revision 1.174 2015/01/03 16:15:49 brouard
40: Summary: Still in cross-compilation
41:
42: Revision 1.173 2015/01/03 12:06:26 brouard
43: Summary: trying to detect cross-compilation
44:
45: Revision 1.172 2014/12/27 12:07:47 brouard
46: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
47:
48: Revision 1.171 2014/12/23 13:26:59 brouard
49: Summary: Back from Visual C
50:
51: Still problem with utsname.h on Windows
52:
53: Revision 1.170 2014/12/23 11:17:12 brouard
54: Summary: Cleaning some \%% back to %%
55:
56: The escape was mandatory for a specific compiler (which one?), but too many warnings.
57:
58: Revision 1.169 2014/12/22 23:08:31 brouard
59: Summary: 0.98p
60:
61: Outputs some informations on compiler used, OS etc. Testing on different platforms.
62:
63: Revision 1.168 2014/12/22 15:17:42 brouard
64: Summary: update
65:
66: Revision 1.167 2014/12/22 13:50:56 brouard
67: Summary: Testing uname and compiler version and if compiled 32 or 64
68:
69: Testing on Linux 64
70:
71: Revision 1.166 2014/12/22 11:40:47 brouard
72: *** empty log message ***
73:
74: Revision 1.165 2014/12/16 11:20:36 brouard
75: Summary: After compiling on Visual C
76:
77: * imach.c (Module): Merging 1.61 to 1.162
78:
79: Revision 1.164 2014/12/16 10:52:11 brouard
80: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
81:
82: * imach.c (Module): Merging 1.61 to 1.162
83:
84: Revision 1.163 2014/12/16 10:30:11 brouard
85: * imach.c (Module): Merging 1.61 to 1.162
86:
87: Revision 1.162 2014/09/25 11:43:39 brouard
88: Summary: temporary backup 0.99!
89:
90: Revision 1.1 2014/09/16 11:06:58 brouard
91: Summary: With some code (wrong) for nlopt
92:
93: Author:
94:
95: Revision 1.161 2014/09/15 20:41:41 brouard
96: Summary: Problem with macro SQR on Intel compiler
97:
98: Revision 1.160 2014/09/02 09:24:05 brouard
99: *** empty log message ***
100:
101: Revision 1.159 2014/09/01 10:34:10 brouard
102: Summary: WIN32
103: Author: Brouard
104:
105: Revision 1.158 2014/08/27 17:11:51 brouard
106: *** empty log message ***
107:
108: Revision 1.157 2014/08/27 16:26:55 brouard
109: Summary: Preparing windows Visual studio version
110: Author: Brouard
111:
112: In order to compile on Visual studio, time.h is now correct and time_t
113: and tm struct should be used. difftime should be used but sometimes I
114: just make the differences in raw time format (time(&now).
115: Trying to suppress #ifdef LINUX
116: Add xdg-open for __linux in order to open default browser.
117:
118: Revision 1.156 2014/08/25 20:10:10 brouard
119: *** empty log message ***
120:
121: Revision 1.155 2014/08/25 18:32:34 brouard
122: Summary: New compile, minor changes
123: Author: Brouard
124:
125: Revision 1.154 2014/06/20 17:32:08 brouard
126: Summary: Outputs now all graphs of convergence to period prevalence
127:
128: Revision 1.153 2014/06/20 16:45:46 brouard
129: Summary: If 3 live state, convergence to period prevalence on same graph
130: Author: Brouard
131:
132: Revision 1.152 2014/06/18 17:54:09 brouard
133: Summary: open browser, use gnuplot on same dir than imach if not found in the path
134:
135: Revision 1.151 2014/06/18 16:43:30 brouard
136: *** empty log message ***
137:
138: Revision 1.150 2014/06/18 16:42:35 brouard
139: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
140: Author: brouard
141:
142: Revision 1.149 2014/06/18 15:51:14 brouard
143: Summary: Some fixes in parameter files errors
144: Author: Nicolas Brouard
145:
146: Revision 1.148 2014/06/17 17:38:48 brouard
147: Summary: Nothing new
148: Author: Brouard
149:
150: Just a new packaging for OS/X version 0.98nS
151:
152: Revision 1.147 2014/06/16 10:33:11 brouard
153: *** empty log message ***
154:
155: Revision 1.146 2014/06/16 10:20:28 brouard
156: Summary: Merge
157: Author: Brouard
158:
159: Merge, before building revised version.
160:
161: Revision 1.145 2014/06/10 21:23:15 brouard
162: Summary: Debugging with valgrind
163: Author: Nicolas Brouard
164:
165: Lot of changes in order to output the results with some covariates
166: After the Edimburgh REVES conference 2014, it seems mandatory to
167: improve the code.
168: No more memory valgrind error but a lot has to be done in order to
169: continue the work of splitting the code into subroutines.
170: Also, decodemodel has been improved. Tricode is still not
171: optimal. nbcode should be improved. Documentation has been added in
172: the source code.
173:
174: Revision 1.143 2014/01/26 09:45:38 brouard
175: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
176:
177: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
178: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
179:
180: Revision 1.142 2014/01/26 03:57:36 brouard
181: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
182:
183: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
184:
185: Revision 1.141 2014/01/26 02:42:01 brouard
186: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
187:
188: Revision 1.140 2011/09/02 10:37:54 brouard
189: Summary: times.h is ok with mingw32 now.
190:
191: Revision 1.139 2010/06/14 07:50:17 brouard
192: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
193: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
194:
195: Revision 1.138 2010/04/30 18:19:40 brouard
196: *** empty log message ***
197:
198: Revision 1.137 2010/04/29 18:11:38 brouard
199: (Module): Checking covariates for more complex models
200: than V1+V2. A lot of change to be done. Unstable.
201:
202: Revision 1.136 2010/04/26 20:30:53 brouard
203: (Module): merging some libgsl code. Fixing computation
204: of likelione (using inter/intrapolation if mle = 0) in order to
205: get same likelihood as if mle=1.
206: Some cleaning of code and comments added.
207:
208: Revision 1.135 2009/10/29 15:33:14 brouard
209: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
210:
211: Revision 1.134 2009/10/29 13:18:53 brouard
212: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
213:
214: Revision 1.133 2009/07/06 10:21:25 brouard
215: just nforces
216:
217: Revision 1.132 2009/07/06 08:22:05 brouard
218: Many tings
219:
220: Revision 1.131 2009/06/20 16:22:47 brouard
221: Some dimensions resccaled
222:
223: Revision 1.130 2009/05/26 06:44:34 brouard
224: (Module): Max Covariate is now set to 20 instead of 8. A
225: lot of cleaning with variables initialized to 0. Trying to make
226: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
227:
228: Revision 1.129 2007/08/31 13:49:27 lievre
229: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
230:
231: Revision 1.128 2006/06/30 13:02:05 brouard
232: (Module): Clarifications on computing e.j
233:
234: Revision 1.127 2006/04/28 18:11:50 brouard
235: (Module): Yes the sum of survivors was wrong since
236: imach-114 because nhstepm was no more computed in the age
237: loop. Now we define nhstepma in the age loop.
238: (Module): In order to speed up (in case of numerous covariates) we
239: compute health expectancies (without variances) in a first step
240: and then all the health expectancies with variances or standard
241: deviation (needs data from the Hessian matrices) which slows the
242: computation.
243: In the future we should be able to stop the program is only health
244: expectancies and graph are needed without standard deviations.
245:
246: Revision 1.126 2006/04/28 17:23:28 brouard
247: (Module): Yes the sum of survivors was wrong since
248: imach-114 because nhstepm was no more computed in the age
249: loop. Now we define nhstepma in the age loop.
250: Version 0.98h
251:
252: Revision 1.125 2006/04/04 15:20:31 lievre
253: Errors in calculation of health expectancies. Age was not initialized.
254: Forecasting file added.
255:
256: Revision 1.124 2006/03/22 17:13:53 lievre
257: Parameters are printed with %lf instead of %f (more numbers after the comma).
258: The log-likelihood is printed in the log file
259:
260: Revision 1.123 2006/03/20 10:52:43 brouard
261: * imach.c (Module): <title> changed, corresponds to .htm file
262: name. <head> headers where missing.
263:
264: * imach.c (Module): Weights can have a decimal point as for
265: English (a comma might work with a correct LC_NUMERIC environment,
266: otherwise the weight is truncated).
267: Modification of warning when the covariates values are not 0 or
268: 1.
269: Version 0.98g
270:
271: Revision 1.122 2006/03/20 09:45:41 brouard
272: (Module): Weights can have a decimal point as for
273: English (a comma might work with a correct LC_NUMERIC environment,
274: otherwise the weight is truncated).
275: Modification of warning when the covariates values are not 0 or
276: 1.
277: Version 0.98g
278:
279: Revision 1.121 2006/03/16 17:45:01 lievre
280: * imach.c (Module): Comments concerning covariates added
281:
282: * imach.c (Module): refinements in the computation of lli if
283: status=-2 in order to have more reliable computation if stepm is
284: not 1 month. Version 0.98f
285:
286: Revision 1.120 2006/03/16 15:10:38 lievre
287: (Module): refinements in the computation of lli if
288: status=-2 in order to have more reliable computation if stepm is
289: not 1 month. Version 0.98f
290:
291: Revision 1.119 2006/03/15 17:42:26 brouard
292: (Module): Bug if status = -2, the loglikelihood was
293: computed as likelihood omitting the logarithm. Version O.98e
294:
295: Revision 1.118 2006/03/14 18:20:07 brouard
296: (Module): varevsij Comments added explaining the second
297: table of variances if popbased=1 .
298: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
299: (Module): Function pstamp added
300: (Module): Version 0.98d
301:
302: Revision 1.117 2006/03/14 17:16:22 brouard
303: (Module): varevsij Comments added explaining the second
304: table of variances if popbased=1 .
305: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
306: (Module): Function pstamp added
307: (Module): Version 0.98d
308:
309: Revision 1.116 2006/03/06 10:29:27 brouard
310: (Module): Variance-covariance wrong links and
311: varian-covariance of ej. is needed (Saito).
312:
313: Revision 1.115 2006/02/27 12:17:45 brouard
314: (Module): One freematrix added in mlikeli! 0.98c
315:
316: Revision 1.114 2006/02/26 12:57:58 brouard
317: (Module): Some improvements in processing parameter
318: filename with strsep.
319:
320: Revision 1.113 2006/02/24 14:20:24 brouard
321: (Module): Memory leaks checks with valgrind and:
322: datafile was not closed, some imatrix were not freed and on matrix
323: allocation too.
324:
325: Revision 1.112 2006/01/30 09:55:26 brouard
326: (Module): Back to gnuplot.exe instead of wgnuplot.exe
327:
328: Revision 1.111 2006/01/25 20:38:18 brouard
329: (Module): Lots of cleaning and bugs added (Gompertz)
330: (Module): Comments can be added in data file. Missing date values
331: can be a simple dot '.'.
332:
333: Revision 1.110 2006/01/25 00:51:50 brouard
334: (Module): Lots of cleaning and bugs added (Gompertz)
335:
336: Revision 1.109 2006/01/24 19:37:15 brouard
337: (Module): Comments (lines starting with a #) are allowed in data.
338:
339: Revision 1.108 2006/01/19 18:05:42 lievre
340: Gnuplot problem appeared...
341: To be fixed
342:
343: Revision 1.107 2006/01/19 16:20:37 brouard
344: Test existence of gnuplot in imach path
345:
346: Revision 1.106 2006/01/19 13:24:36 brouard
347: Some cleaning and links added in html output
348:
349: Revision 1.105 2006/01/05 20:23:19 lievre
350: *** empty log message ***
351:
352: Revision 1.104 2005/09/30 16:11:43 lievre
353: (Module): sump fixed, loop imx fixed, and simplifications.
354: (Module): If the status is missing at the last wave but we know
355: that the person is alive, then we can code his/her status as -2
356: (instead of missing=-1 in earlier versions) and his/her
357: contributions to the likelihood is 1 - Prob of dying from last
358: health status (= 1-p13= p11+p12 in the easiest case of somebody in
359: the healthy state at last known wave). Version is 0.98
360:
361: Revision 1.103 2005/09/30 15:54:49 lievre
362: (Module): sump fixed, loop imx fixed, and simplifications.
363:
364: Revision 1.102 2004/09/15 17:31:30 brouard
365: Add the possibility to read data file including tab characters.
366:
367: Revision 1.101 2004/09/15 10:38:38 brouard
368: Fix on curr_time
369:
370: Revision 1.100 2004/07/12 18:29:06 brouard
371: Add version for Mac OS X. Just define UNIX in Makefile
372:
373: Revision 1.99 2004/06/05 08:57:40 brouard
374: *** empty log message ***
375:
376: Revision 1.98 2004/05/16 15:05:56 brouard
377: New version 0.97 . First attempt to estimate force of mortality
378: directly from the data i.e. without the need of knowing the health
379: state at each age, but using a Gompertz model: log u =a + b*age .
380: This is the basic analysis of mortality and should be done before any
381: other analysis, in order to test if the mortality estimated from the
382: cross-longitudinal survey is different from the mortality estimated
383: from other sources like vital statistic data.
384:
385: The same imach parameter file can be used but the option for mle should be -3.
386:
387: Agnès, who wrote this part of the code, tried to keep most of the
388: former routines in order to include the new code within the former code.
389:
390: The output is very simple: only an estimate of the intercept and of
391: the slope with 95% confident intervals.
392:
393: Current limitations:
394: A) Even if you enter covariates, i.e. with the
395: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
396: B) There is no computation of Life Expectancy nor Life Table.
397:
398: Revision 1.97 2004/02/20 13:25:42 lievre
399: Version 0.96d. Population forecasting command line is (temporarily)
400: suppressed.
401:
402: Revision 1.96 2003/07/15 15:38:55 brouard
403: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
404: rewritten within the same printf. Workaround: many printfs.
405:
406: Revision 1.95 2003/07/08 07:54:34 brouard
407: * imach.c (Repository):
408: (Repository): Using imachwizard code to output a more meaningful covariance
409: matrix (cov(a12,c31) instead of numbers.
410:
411: Revision 1.94 2003/06/27 13:00:02 brouard
412: Just cleaning
413:
414: Revision 1.93 2003/06/25 16:33:55 brouard
415: (Module): On windows (cygwin) function asctime_r doesn't
416: exist so I changed back to asctime which exists.
417: (Module): Version 0.96b
418:
419: Revision 1.92 2003/06/25 16:30:45 brouard
420: (Module): On windows (cygwin) function asctime_r doesn't
421: exist so I changed back to asctime which exists.
422:
423: Revision 1.91 2003/06/25 15:30:29 brouard
424: * imach.c (Repository): Duplicated warning errors corrected.
425: (Repository): Elapsed time after each iteration is now output. It
426: helps to forecast when convergence will be reached. Elapsed time
427: is stamped in powell. We created a new html file for the graphs
428: concerning matrix of covariance. It has extension -cov.htm.
429:
430: Revision 1.90 2003/06/24 12:34:15 brouard
431: (Module): Some bugs corrected for windows. Also, when
432: mle=-1 a template is output in file "or"mypar.txt with the design
433: of the covariance matrix to be input.
434:
435: Revision 1.89 2003/06/24 12:30:52 brouard
436: (Module): Some bugs corrected for windows. Also, when
437: mle=-1 a template is output in file "or"mypar.txt with the design
438: of the covariance matrix to be input.
439:
440: Revision 1.88 2003/06/23 17:54:56 brouard
441: * 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.
442:
443: Revision 1.87 2003/06/18 12:26:01 brouard
444: Version 0.96
445:
446: Revision 1.86 2003/06/17 20:04:08 brouard
447: (Module): Change position of html and gnuplot routines and added
448: routine fileappend.
449:
450: Revision 1.85 2003/06/17 13:12:43 brouard
451: * imach.c (Repository): Check when date of death was earlier that
452: current date of interview. It may happen when the death was just
453: prior to the death. In this case, dh was negative and likelihood
454: was wrong (infinity). We still send an "Error" but patch by
455: assuming that the date of death was just one stepm after the
456: interview.
457: (Repository): Because some people have very long ID (first column)
458: we changed int to long in num[] and we added a new lvector for
459: memory allocation. But we also truncated to 8 characters (left
460: truncation)
461: (Repository): No more line truncation errors.
462:
463: Revision 1.84 2003/06/13 21:44:43 brouard
464: * imach.c (Repository): Replace "freqsummary" at a correct
465: place. It differs from routine "prevalence" which may be called
466: many times. Probs is memory consuming and must be used with
467: parcimony.
468: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
469:
470: Revision 1.83 2003/06/10 13:39:11 lievre
471: *** empty log message ***
472:
473: Revision 1.82 2003/06/05 15:57:20 brouard
474: Add log in imach.c and fullversion number is now printed.
475:
476: */
477: /*
478: Interpolated Markov Chain
479:
480: Short summary of the programme:
481:
482: This program computes Healthy Life Expectancies from
483: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
484: first survey ("cross") where individuals from different ages are
485: interviewed on their health status or degree of disability (in the
486: case of a health survey which is our main interest) -2- at least a
487: second wave of interviews ("longitudinal") which measure each change
488: (if any) in individual health status. Health expectancies are
489: computed from the time spent in each health state according to a
490: model. More health states you consider, more time is necessary to reach the
491: Maximum Likelihood of the parameters involved in the model. The
492: simplest model is the multinomial logistic model where pij is the
493: probability to be observed in state j at the second wave
494: conditional to be observed in state i at the first wave. Therefore
495: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
496: 'age' is age and 'sex' is a covariate. If you want to have a more
497: complex model than "constant and age", you should modify the program
498: where the markup *Covariates have to be included here again* invites
499: you to do it. More covariates you add, slower the
500: convergence.
501:
502: The advantage of this computer programme, compared to a simple
503: multinomial logistic model, is clear when the delay between waves is not
504: identical for each individual. Also, if a individual missed an
505: intermediate interview, the information is lost, but taken into
506: account using an interpolation or extrapolation.
507:
508: hPijx is the probability to be observed in state i at age x+h
509: conditional to the observed state i at age x. The delay 'h' can be
510: split into an exact number (nh*stepm) of unobserved intermediate
511: states. This elementary transition (by month, quarter,
512: semester or year) is modelled as a multinomial logistic. The hPx
513: matrix is simply the matrix product of nh*stepm elementary matrices
514: and the contribution of each individual to the likelihood is simply
515: hPijx.
516:
517: Also this programme outputs the covariance matrix of the parameters but also
518: of the life expectancies. It also computes the period (stable) prevalence.
519:
520: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
521: Institut national d'études démographiques, Paris.
522: This software have been partly granted by Euro-REVES, a concerted action
523: from the European Union.
524: It is copyrighted identically to a GNU software product, ie programme and
525: software can be distributed freely for non commercial use. Latest version
526: can be accessed at http://euroreves.ined.fr/imach .
527:
528: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
529: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
530:
531: **********************************************************************/
532: /*
533: main
534: read parameterfile
535: read datafile
536: concatwav
537: freqsummary
538: if (mle >= 1)
539: mlikeli
540: print results files
541: if mle==1
542: computes hessian
543: read end of parameter file: agemin, agemax, bage, fage, estepm
544: begin-prev-date,...
545: open gnuplot file
546: open html file
547: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
548: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
549: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
550: freexexit2 possible for memory heap.
551:
552: h Pij x | pij_nom ficrestpij
553: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
554: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
555: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
556:
557: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
558: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
559: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
560: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
561: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
562:
563: forecasting if prevfcast==1 prevforecast call prevalence()
564: health expectancies
565: Variance-covariance of DFLE
566: prevalence()
567: movingaverage()
568: varevsij()
569: if popbased==1 varevsij(,popbased)
570: total life expectancies
571: Variance of period (stable) prevalence
572: end
573: */
574:
575: #define POWELL /* Instead of NLOPT */
576: /* #define POWELLORIGINAL */ /* Don't use Directest to decide new direction but original Powell test */
577:
578: #include <math.h>
579: #include <stdio.h>
580: #include <stdlib.h>
581: #include <string.h>
582:
583: #ifdef _WIN32
584: #include <io.h>
585: #include <windows.h>
586: #include <tchar.h>
587: #else
588: #include <unistd.h>
589: #endif
590:
591: #include <limits.h>
592: #include <sys/types.h>
593:
594: #if defined(__GNUC__)
595: #include <sys/utsname.h> /* Doesn't work on Windows */
596: #endif
597:
598: #include <sys/stat.h>
599: #include <errno.h>
600: /* extern int errno; */
601:
602: /* #ifdef LINUX */
603: /* #include <time.h> */
604: /* #include "timeval.h" */
605: /* #else */
606: /* #include <sys/time.h> */
607: /* #endif */
608:
609: #include <time.h>
610:
611: #ifdef GSL
612: #include <gsl/gsl_errno.h>
613: #include <gsl/gsl_multimin.h>
614: #endif
615:
616:
617: #ifdef NLOPT
618: #include <nlopt.h>
619: typedef struct {
620: double (* function)(double [] );
621: } myfunc_data ;
622: #endif
623:
624: /* #include <libintl.h> */
625: /* #define _(String) gettext (String) */
626:
627: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
628:
629: #define GNUPLOTPROGRAM "gnuplot"
630: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
631: #define FILENAMELENGTH 132
632:
633: #define GLOCK_ERROR_NOPATH -1 /* empty path */
634: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
635:
636: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
637: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
638:
639: #define NINTERVMAX 8
640: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
641: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
642: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
643: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
644: #define MAXN 20000
645: #define YEARM 12. /**< Number of months per year */
646: #define AGESUP 130
647: #define AGEBASE 40
648: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
649: #ifdef _WIN32
650: #define DIRSEPARATOR '\\'
651: #define CHARSEPARATOR "\\"
652: #define ODIRSEPARATOR '/'
653: #else
654: #define DIRSEPARATOR '/'
655: #define CHARSEPARATOR "/"
656: #define ODIRSEPARATOR '\\'
657: #endif
658:
659: /* $Id: imach.c,v 1.183 2015/03/10 20:34:32 brouard Exp $ */
660: /* $State: Exp $ */
661:
662: char version[]="Imach version 0.98q0, March 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
663: char fullversion[]="$Revision: 1.183 $ $Date: 2015/03/10 20:34:32 $";
664: char strstart[80];
665: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
666: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
667: int nvar=0, nforce=0; /* Number of variables, number of forces */
668: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
669: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
670: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
671: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
672: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
673: int cptcovprodnoage=0; /**< Number of covariate products without age */
674: int cptcoveff=0; /* Total number of covariates to vary for printing results */
675: int cptcov=0; /* Working variable */
676: int npar=NPARMAX;
677: int nlstate=2; /* Number of live states */
678: int ndeath=1; /* Number of dead states */
679: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
680: int popbased=0;
681:
682: int *wav; /* Number of waves for this individuual 0 is possible */
683: int maxwav=0; /* Maxim number of waves */
684: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
685: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
686: int gipmx=0, gsw=0; /* Global variables on the number of contributions
687: to the likelihood and the sum of weights (done by funcone)*/
688: int mle=1, weightopt=0;
689: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
690: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
691: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
692: * wave mi and wave mi+1 is not an exact multiple of stepm. */
693: int countcallfunc=0; /* Count the number of calls to func */
694: double jmean=1; /* Mean space between 2 waves */
695: double **matprod2(); /* test */
696: double **oldm, **newm, **savm; /* Working pointers to matrices */
697: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
698: /*FILE *fic ; */ /* Used in readdata only */
699: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
700: FILE *ficlog, *ficrespow;
701: int globpr=0; /* Global variable for printing or not */
702: double fretone; /* Only one call to likelihood */
703: long ipmx=0; /* Number of contributions */
704: double sw; /* Sum of weights */
705: char filerespow[FILENAMELENGTH];
706: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
707: FILE *ficresilk;
708: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
709: FILE *ficresprobmorprev;
710: FILE *fichtm, *fichtmcov; /* Html File */
711: FILE *ficreseij;
712: char filerese[FILENAMELENGTH];
713: FILE *ficresstdeij;
714: char fileresstde[FILENAMELENGTH];
715: FILE *ficrescveij;
716: char filerescve[FILENAMELENGTH];
717: FILE *ficresvij;
718: char fileresv[FILENAMELENGTH];
719: FILE *ficresvpl;
720: char fileresvpl[FILENAMELENGTH];
721: char title[MAXLINE];
722: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
723: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
724: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
725: char command[FILENAMELENGTH];
726: int outcmd=0;
727:
728: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
729:
730: char filelog[FILENAMELENGTH]; /* Log file */
731: char filerest[FILENAMELENGTH];
732: char fileregp[FILENAMELENGTH];
733: char popfile[FILENAMELENGTH];
734:
735: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
736:
737: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
738: /* struct timezone tzp; */
739: /* extern int gettimeofday(); */
740: struct tm tml, *gmtime(), *localtime();
741:
742: extern time_t time();
743:
744: struct tm start_time, end_time, curr_time, last_time, forecast_time;
745: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
746: struct tm tm;
747:
748: char strcurr[80], strfor[80];
749:
750: char *endptr;
751: long lval;
752: double dval;
753:
754: #define NR_END 1
755: #define FREE_ARG char*
756: #define FTOL 1.0e-10
757:
758: #define NRANSI
759: #define ITMAX 200
760:
761: #define TOL 2.0e-4
762:
763: #define CGOLD 0.3819660
764: #define ZEPS 1.0e-10
765: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
766:
767: #define GOLD 1.618034
768: #define GLIMIT 100.0
769: #define TINY 1.0e-20
770:
771: static double maxarg1,maxarg2;
772: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
773: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
774:
775: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
776: #define rint(a) floor(a+0.5)
777: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
778: #define mytinydouble 1.0e-16
779: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
780: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
781: /* static double dsqrarg; */
782: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
783: static double sqrarg;
784: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
785: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
786: int agegomp= AGEGOMP;
787:
788: int imx;
789: int stepm=1;
790: /* Stepm, step in month: minimum step interpolation*/
791:
792: int estepm;
793: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
794:
795: int m,nb;
796: long *num;
797: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
798: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
799: double **pmmij, ***probs;
800: double *ageexmed,*agecens;
801: double dateintmean=0;
802:
803: double *weight;
804: int **s; /* Status */
805: double *agedc;
806: double **covar; /**< covar[j,i], value of jth covariate for individual i,
807: * covar=matrix(0,NCOVMAX,1,n);
808: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
809: double idx;
810: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
811: int *Ndum; /** Freq of modality (tricode */
812: int **codtab; /**< codtab=imatrix(1,100,1,10); */
813: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
814: double *lsurv, *lpop, *tpop;
815:
816: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
817: double ftolhess; /**< Tolerance for computing hessian */
818:
819: /**************** split *************************/
820: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
821: {
822: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
823: the name of the file (name), its extension only (ext) and its first part of the name (finame)
824: */
825: char *ss; /* pointer */
826: int l1, l2; /* length counters */
827:
828: l1 = strlen(path ); /* length of path */
829: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
830: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
831: if ( ss == NULL ) { /* no directory, so determine current directory */
832: strcpy( name, path ); /* we got the fullname name because no directory */
833: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
834: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
835: /* get current working directory */
836: /* extern char* getcwd ( char *buf , int len);*/
837: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
838: return( GLOCK_ERROR_GETCWD );
839: }
840: /* got dirc from getcwd*/
841: printf(" DIRC = %s \n",dirc);
842: } else { /* strip direcotry from path */
843: ss++; /* after this, the filename */
844: l2 = strlen( ss ); /* length of filename */
845: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
846: strcpy( name, ss ); /* save file name */
847: strncpy( dirc, path, l1 - l2 ); /* now the directory */
848: dirc[l1-l2] = 0; /* add zero */
849: printf(" DIRC2 = %s \n",dirc);
850: }
851: /* We add a separator at the end of dirc if not exists */
852: l1 = strlen( dirc ); /* length of directory */
853: if( dirc[l1-1] != DIRSEPARATOR ){
854: dirc[l1] = DIRSEPARATOR;
855: dirc[l1+1] = 0;
856: printf(" DIRC3 = %s \n",dirc);
857: }
858: ss = strrchr( name, '.' ); /* find last / */
859: if (ss >0){
860: ss++;
861: strcpy(ext,ss); /* save extension */
862: l1= strlen( name);
863: l2= strlen(ss)+1;
864: strncpy( finame, name, l1-l2);
865: finame[l1-l2]= 0;
866: }
867:
868: return( 0 ); /* we're done */
869: }
870:
871:
872: /******************************************/
873:
874: void replace_back_to_slash(char *s, char*t)
875: {
876: int i;
877: int lg=0;
878: i=0;
879: lg=strlen(t);
880: for(i=0; i<= lg; i++) {
881: (s[i] = t[i]);
882: if (t[i]== '\\') s[i]='/';
883: }
884: }
885:
886: char *trimbb(char *out, char *in)
887: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
888: char *s;
889: s=out;
890: while (*in != '\0'){
891: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
892: in++;
893: }
894: *out++ = *in++;
895: }
896: *out='\0';
897: return s;
898: }
899:
900: char *cutl(char *blocc, char *alocc, char *in, char occ)
901: {
902: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
903: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
904: gives blocc="abcdef2ghi" and alocc="j".
905: If occ is not found blocc is null and alocc is equal to in. Returns blocc
906: */
907: char *s, *t;
908: t=in;s=in;
909: while ((*in != occ) && (*in != '\0')){
910: *alocc++ = *in++;
911: }
912: if( *in == occ){
913: *(alocc)='\0';
914: s=++in;
915: }
916:
917: if (s == t) {/* occ not found */
918: *(alocc-(in-s))='\0';
919: in=s;
920: }
921: while ( *in != '\0'){
922: *blocc++ = *in++;
923: }
924:
925: *blocc='\0';
926: return t;
927: }
928: char *cutv(char *blocc, char *alocc, char *in, char occ)
929: {
930: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
931: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
932: gives blocc="abcdef2ghi" and alocc="j".
933: If occ is not found blocc is null and alocc is equal to in. Returns alocc
934: */
935: char *s, *t;
936: t=in;s=in;
937: while (*in != '\0'){
938: while( *in == occ){
939: *blocc++ = *in++;
940: s=in;
941: }
942: *blocc++ = *in++;
943: }
944: if (s == t) /* occ not found */
945: *(blocc-(in-s))='\0';
946: else
947: *(blocc-(in-s)-1)='\0';
948: in=s;
949: while ( *in != '\0'){
950: *alocc++ = *in++;
951: }
952:
953: *alocc='\0';
954: return s;
955: }
956:
957: int nbocc(char *s, char occ)
958: {
959: int i,j=0;
960: int lg=20;
961: i=0;
962: lg=strlen(s);
963: for(i=0; i<= lg; i++) {
964: if (s[i] == occ ) j++;
965: }
966: return j;
967: }
968:
969: /* void cutv(char *u,char *v, char*t, char occ) */
970: /* { */
971: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
972: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
973: /* gives u="abcdef2ghi" and v="j" *\/ */
974: /* int i,lg,j,p=0; */
975: /* i=0; */
976: /* lg=strlen(t); */
977: /* for(j=0; j<=lg-1; j++) { */
978: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
979: /* } */
980:
981: /* for(j=0; j<p; j++) { */
982: /* (u[j] = t[j]); */
983: /* } */
984: /* u[p]='\0'; */
985:
986: /* for(j=0; j<= lg; j++) { */
987: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
988: /* } */
989: /* } */
990:
991: #ifdef _WIN32
992: char * strsep(char **pp, const char *delim)
993: {
994: char *p, *q;
995:
996: if ((p = *pp) == NULL)
997: return 0;
998: if ((q = strpbrk (p, delim)) != NULL)
999: {
1000: *pp = q + 1;
1001: *q = '\0';
1002: }
1003: else
1004: *pp = 0;
1005: return p;
1006: }
1007: #endif
1008:
1009: /********************** nrerror ********************/
1010:
1011: void nrerror(char error_text[])
1012: {
1013: fprintf(stderr,"ERREUR ...\n");
1014: fprintf(stderr,"%s\n",error_text);
1015: exit(EXIT_FAILURE);
1016: }
1017: /*********************** vector *******************/
1018: double *vector(int nl, int nh)
1019: {
1020: double *v;
1021: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1022: if (!v) nrerror("allocation failure in vector");
1023: return v-nl+NR_END;
1024: }
1025:
1026: /************************ free vector ******************/
1027: void free_vector(double*v, int nl, int nh)
1028: {
1029: free((FREE_ARG)(v+nl-NR_END));
1030: }
1031:
1032: /************************ivector *******************************/
1033: int *ivector(long nl,long nh)
1034: {
1035: int *v;
1036: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1037: if (!v) nrerror("allocation failure in ivector");
1038: return v-nl+NR_END;
1039: }
1040:
1041: /******************free ivector **************************/
1042: void free_ivector(int *v, long nl, long nh)
1043: {
1044: free((FREE_ARG)(v+nl-NR_END));
1045: }
1046:
1047: /************************lvector *******************************/
1048: long *lvector(long nl,long nh)
1049: {
1050: long *v;
1051: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1052: if (!v) nrerror("allocation failure in ivector");
1053: return v-nl+NR_END;
1054: }
1055:
1056: /******************free lvector **************************/
1057: void free_lvector(long *v, long nl, long nh)
1058: {
1059: free((FREE_ARG)(v+nl-NR_END));
1060: }
1061:
1062: /******************* imatrix *******************************/
1063: int **imatrix(long nrl, long nrh, long ncl, long nch)
1064: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1065: {
1066: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1067: int **m;
1068:
1069: /* allocate pointers to rows */
1070: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1071: if (!m) nrerror("allocation failure 1 in matrix()");
1072: m += NR_END;
1073: m -= nrl;
1074:
1075:
1076: /* allocate rows and set pointers to them */
1077: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1078: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1079: m[nrl] += NR_END;
1080: m[nrl] -= ncl;
1081:
1082: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1083:
1084: /* return pointer to array of pointers to rows */
1085: return m;
1086: }
1087:
1088: /****************** free_imatrix *************************/
1089: void free_imatrix(m,nrl,nrh,ncl,nch)
1090: int **m;
1091: long nch,ncl,nrh,nrl;
1092: /* free an int matrix allocated by imatrix() */
1093: {
1094: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1095: free((FREE_ARG) (m+nrl-NR_END));
1096: }
1097:
1098: /******************* matrix *******************************/
1099: double **matrix(long nrl, long nrh, long ncl, long nch)
1100: {
1101: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1102: double **m;
1103:
1104: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1105: if (!m) nrerror("allocation failure 1 in matrix()");
1106: m += NR_END;
1107: m -= nrl;
1108:
1109: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1110: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1111: m[nrl] += NR_END;
1112: m[nrl] -= ncl;
1113:
1114: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1115: return m;
1116: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1117: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1118: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1119: */
1120: }
1121:
1122: /*************************free matrix ************************/
1123: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1124: {
1125: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1126: free((FREE_ARG)(m+nrl-NR_END));
1127: }
1128:
1129: /******************* ma3x *******************************/
1130: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1131: {
1132: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1133: double ***m;
1134:
1135: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1136: if (!m) nrerror("allocation failure 1 in matrix()");
1137: m += NR_END;
1138: m -= nrl;
1139:
1140: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1141: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1142: m[nrl] += NR_END;
1143: m[nrl] -= ncl;
1144:
1145: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1146:
1147: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1148: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1149: m[nrl][ncl] += NR_END;
1150: m[nrl][ncl] -= nll;
1151: for (j=ncl+1; j<=nch; j++)
1152: m[nrl][j]=m[nrl][j-1]+nlay;
1153:
1154: for (i=nrl+1; i<=nrh; i++) {
1155: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1156: for (j=ncl+1; j<=nch; j++)
1157: m[i][j]=m[i][j-1]+nlay;
1158: }
1159: return m;
1160: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1161: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1162: */
1163: }
1164:
1165: /*************************free ma3x ************************/
1166: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1167: {
1168: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1169: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1170: free((FREE_ARG)(m+nrl-NR_END));
1171: }
1172:
1173: /*************** function subdirf ***********/
1174: char *subdirf(char fileres[])
1175: {
1176: /* Caution optionfilefiname is hidden */
1177: strcpy(tmpout,optionfilefiname);
1178: strcat(tmpout,"/"); /* Add to the right */
1179: strcat(tmpout,fileres);
1180: return tmpout;
1181: }
1182:
1183: /*************** function subdirf2 ***********/
1184: char *subdirf2(char fileres[], char *preop)
1185: {
1186:
1187: /* Caution optionfilefiname is hidden */
1188: strcpy(tmpout,optionfilefiname);
1189: strcat(tmpout,"/");
1190: strcat(tmpout,preop);
1191: strcat(tmpout,fileres);
1192: return tmpout;
1193: }
1194:
1195: /*************** function subdirf3 ***********/
1196: char *subdirf3(char fileres[], char *preop, char *preop2)
1197: {
1198:
1199: /* Caution optionfilefiname is hidden */
1200: strcpy(tmpout,optionfilefiname);
1201: strcat(tmpout,"/");
1202: strcat(tmpout,preop);
1203: strcat(tmpout,preop2);
1204: strcat(tmpout,fileres);
1205: return tmpout;
1206: }
1207:
1208: char *asc_diff_time(long time_sec, char ascdiff[])
1209: {
1210: long sec_left, days, hours, minutes;
1211: days = (time_sec) / (60*60*24);
1212: sec_left = (time_sec) % (60*60*24);
1213: hours = (sec_left) / (60*60) ;
1214: sec_left = (sec_left) %(60*60);
1215: minutes = (sec_left) /60;
1216: sec_left = (sec_left) % (60);
1217: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1218: return ascdiff;
1219: }
1220:
1221: /***************** f1dim *************************/
1222: extern int ncom;
1223: extern double *pcom,*xicom;
1224: extern double (*nrfunc)(double []);
1225:
1226: double f1dim(double x)
1227: {
1228: int j;
1229: double f;
1230: double *xt;
1231:
1232: xt=vector(1,ncom);
1233: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1234: f=(*nrfunc)(xt);
1235: free_vector(xt,1,ncom);
1236: return f;
1237: }
1238:
1239: /*****************brent *************************/
1240: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1241: {
1242: int iter;
1243: double a,b,d,etemp;
1244: double fu=0,fv,fw,fx;
1245: double ftemp=0.;
1246: double p,q,r,tol1,tol2,u,v,w,x,xm;
1247: double e=0.0;
1248:
1249: a=(ax < cx ? ax : cx);
1250: b=(ax > cx ? ax : cx);
1251: x=w=v=bx;
1252: fw=fv=fx=(*f)(x);
1253: for (iter=1;iter<=ITMAX;iter++) {
1254: xm=0.5*(a+b);
1255: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1256: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1257: printf(".");fflush(stdout);
1258: fprintf(ficlog,".");fflush(ficlog);
1259: #ifdef DEBUGBRENT
1260: 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);
1261: 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);
1262: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1263: #endif
1264: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1265: *xmin=x;
1266: return fx;
1267: }
1268: ftemp=fu;
1269: if (fabs(e) > tol1) {
1270: r=(x-w)*(fx-fv);
1271: q=(x-v)*(fx-fw);
1272: p=(x-v)*q-(x-w)*r;
1273: q=2.0*(q-r);
1274: if (q > 0.0) p = -p;
1275: q=fabs(q);
1276: etemp=e;
1277: e=d;
1278: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1279: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1280: else {
1281: d=p/q;
1282: u=x+d;
1283: if (u-a < tol2 || b-u < tol2)
1284: d=SIGN(tol1,xm-x);
1285: }
1286: } else {
1287: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1288: }
1289: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1290: fu=(*f)(u);
1291: if (fu <= fx) {
1292: if (u >= x) a=x; else b=x;
1293: SHFT(v,w,x,u)
1294: SHFT(fv,fw,fx,fu)
1295: } else {
1296: if (u < x) a=u; else b=u;
1297: if (fu <= fw || w == x) {
1298: v=w;
1299: w=u;
1300: fv=fw;
1301: fw=fu;
1302: } else if (fu <= fv || v == x || v == w) {
1303: v=u;
1304: fv=fu;
1305: }
1306: }
1307: }
1308: nrerror("Too many iterations in brent");
1309: *xmin=x;
1310: return fx;
1311: }
1312:
1313: /****************** mnbrak ***********************/
1314:
1315: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1316: double (*func)(double))
1317: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1318: the downhill direction (defined by the function as evaluated at the initial points) and returns
1319: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1320: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1321: */
1322: double ulim,u,r,q, dum;
1323: double fu;
1324:
1325: *fa=(*func)(*ax);
1326: *fb=(*func)(*bx);
1327: if (*fb > *fa) {
1328: SHFT(dum,*ax,*bx,dum)
1329: SHFT(dum,*fb,*fa,dum)
1330: }
1331: *cx=(*bx)+GOLD*(*bx-*ax);
1332: *fc=(*func)(*cx);
1333: #ifdef DEBUG
1334: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1335: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1336: #endif
1337: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1338: r=(*bx-*ax)*(*fb-*fc);
1339: q=(*bx-*cx)*(*fb-*fa);
1340: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1341: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1342: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1343: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1344: fu=(*func)(u);
1345: #ifdef DEBUG
1346: /* f(x)=A(x-u)**2+f(u) */
1347: double A, fparabu;
1348: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1349: fparabu= *fa - A*(*ax-u)*(*ax-u);
1350: 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);
1351: 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);
1352: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1353: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1354: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1355: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1356: #endif
1357: #ifdef MNBRAKORI
1358: #else
1359: if (fu > *fc) {
1360: #ifdef DEBUG
1361: printf("mnbrak4 fu > fc \n");
1362: fprintf(ficlog, "mnbrak4 fu > fc\n");
1363: #endif
1364: /* 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 *\/ */
1365: /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\/ */
1366: dum=u; /* Shifting c and u */
1367: u = *cx;
1368: *cx = dum;
1369: dum = fu;
1370: fu = *fc;
1371: *fc =dum;
1372: } else { /* end */
1373: #ifdef DEBUG
1374: printf("mnbrak3 fu < fc \n");
1375: fprintf(ficlog, "mnbrak3 fu < fc\n");
1376: #endif
1377: dum=u; /* Shifting c and u */
1378: u = *cx;
1379: *cx = dum;
1380: dum = fu;
1381: fu = *fc;
1382: *fc =dum;
1383: }
1384: #endif
1385: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1386: #ifdef DEBUG
1387: printf("mnbrak2 u after c but before ulim\n");
1388: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1389: #endif
1390: fu=(*func)(u);
1391: if (fu < *fc) {
1392: #ifdef DEBUG
1393: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1394: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1395: #endif
1396: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1397: SHFT(*fb,*fc,fu,(*func)(u))
1398: }
1399: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1400: #ifdef DEBUG
1401: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1402: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1403: #endif
1404: u=ulim;
1405: fu=(*func)(u);
1406: } else { /* u could be left to b (if r > q parabola has a maximum) */
1407: #ifdef DEBUG
1408: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1409: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1410: #endif
1411: u=(*cx)+GOLD*(*cx-*bx);
1412: fu=(*func)(u);
1413: } /* end tests */
1414: SHFT(*ax,*bx,*cx,u)
1415: SHFT(*fa,*fb,*fc,fu)
1416: #ifdef DEBUG
1417: 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);
1418: 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);
1419: #endif
1420: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1421: }
1422:
1423: /*************** linmin ************************/
1424: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1425: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1426: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1427: the value of func at the returned location p . This is actually all accomplished by calling the
1428: routines mnbrak and brent .*/
1429: int ncom;
1430: double *pcom,*xicom;
1431: double (*nrfunc)(double []);
1432:
1433: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1434: {
1435: double brent(double ax, double bx, double cx,
1436: double (*f)(double), double tol, double *xmin);
1437: double f1dim(double x);
1438: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1439: double *fc, double (*func)(double));
1440: int j;
1441: double xx,xmin,bx,ax;
1442: double fx,fb,fa;
1443:
1444: ncom=n;
1445: pcom=vector(1,n);
1446: xicom=vector(1,n);
1447: nrfunc=func;
1448: for (j=1;j<=n;j++) {
1449: pcom[j]=p[j];
1450: xicom[j]=xi[j];
1451: }
1452: ax=0.0;
1453: xx=1.0;
1454: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1455: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1456: #ifdef DEBUG
1457: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1458: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1459: #endif
1460: for (j=1;j<=n;j++) {
1461: xi[j] *= xmin;
1462: p[j] += xi[j];
1463: }
1464: free_vector(xicom,1,n);
1465: free_vector(pcom,1,n);
1466: }
1467:
1468:
1469: /*************** powell ************************/
1470: /*
1471: Minimization of a function func of n variables. Input consists of an initial starting point
1472: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1473: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1474: such that failure to decrease by more than this amount on one iteration signals doneness. On
1475: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1476: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1477: */
1478: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1479: double (*func)(double []))
1480: {
1481: void linmin(double p[], double xi[], int n, double *fret,
1482: double (*func)(double []));
1483: int i,ibig,j;
1484: double del,t,*pt,*ptt,*xit;
1485: double directest;
1486: double fp,fptt;
1487: double *xits;
1488: int niterf, itmp;
1489:
1490: pt=vector(1,n);
1491: ptt=vector(1,n);
1492: xit=vector(1,n);
1493: xits=vector(1,n);
1494: *fret=(*func)(p);
1495: for (j=1;j<=n;j++) pt[j]=p[j];
1496: rcurr_time = time(NULL);
1497: for (*iter=1;;++(*iter)) {
1498: fp=(*fret);
1499: ibig=0;
1500: del=0.0;
1501: rlast_time=rcurr_time;
1502: /* (void) gettimeofday(&curr_time,&tzp); */
1503: rcurr_time = time(NULL);
1504: curr_time = *localtime(&rcurr_time);
1505: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1506: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1507: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1508: for (i=1;i<=n;i++) {
1509: printf(" %d %.12f",i, p[i]);
1510: fprintf(ficlog," %d %.12lf",i, p[i]);
1511: fprintf(ficrespow," %.12lf", p[i]);
1512: }
1513: printf("\n");
1514: fprintf(ficlog,"\n");
1515: fprintf(ficrespow,"\n");fflush(ficrespow);
1516: if(*iter <=3){
1517: tml = *localtime(&rcurr_time);
1518: strcpy(strcurr,asctime(&tml));
1519: rforecast_time=rcurr_time;
1520: itmp = strlen(strcurr);
1521: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1522: strcurr[itmp-1]='\0';
1523: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1524: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1525: for(niterf=10;niterf<=30;niterf+=10){
1526: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1527: forecast_time = *localtime(&rforecast_time);
1528: strcpy(strfor,asctime(&forecast_time));
1529: itmp = strlen(strfor);
1530: if(strfor[itmp-1]=='\n')
1531: strfor[itmp-1]='\0';
1532: 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);
1533: 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);
1534: }
1535: }
1536: for (i=1;i<=n;i++) {
1537: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1538: fptt=(*fret);
1539: #ifdef DEBUG
1540: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1541: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1542: #endif
1543: printf("%d",i);fflush(stdout);
1544: fprintf(ficlog,"%d",i);fflush(ficlog);
1545: linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
1546: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1547: because that direction will be replaced unless the gain del is small
1548: in comparison with the 'probable' gain, mu^2, with the last average direction.
1549: Unless the n directions are conjugate some gain in the determinant may be obtained
1550: with the new direction.
1551: */
1552: del=fabs(fptt-(*fret));
1553: ibig=i;
1554: }
1555: #ifdef DEBUG
1556: printf("%d %.12e",i,(*fret));
1557: fprintf(ficlog,"%d %.12e",i,(*fret));
1558: for (j=1;j<=n;j++) {
1559: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1560: printf(" x(%d)=%.12e",j,xit[j]);
1561: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1562: }
1563: for(j=1;j<=n;j++) {
1564: printf(" p(%d)=%.12e",j,p[j]);
1565: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1566: }
1567: printf("\n");
1568: fprintf(ficlog,"\n");
1569: #endif
1570: } /* end i */
1571: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1572: #ifdef DEBUG
1573: int k[2],l;
1574: k[0]=1;
1575: k[1]=-1;
1576: printf("Max: %.12e",(*func)(p));
1577: fprintf(ficlog,"Max: %.12e",(*func)(p));
1578: for (j=1;j<=n;j++) {
1579: printf(" %.12e",p[j]);
1580: fprintf(ficlog," %.12e",p[j]);
1581: }
1582: printf("\n");
1583: fprintf(ficlog,"\n");
1584: for(l=0;l<=1;l++) {
1585: for (j=1;j<=n;j++) {
1586: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1587: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1588: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1589: }
1590: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1591: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1592: }
1593: #endif
1594:
1595:
1596: free_vector(xit,1,n);
1597: free_vector(xits,1,n);
1598: free_vector(ptt,1,n);
1599: free_vector(pt,1,n);
1600: return;
1601: }
1602: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1603: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1604: ptt[j]=2.0*p[j]-pt[j];
1605: xit[j]=p[j]-pt[j];
1606: pt[j]=p[j];
1607: }
1608: fptt=(*func)(ptt); /* f_3 */
1609: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1610: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1611: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1612: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1613: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1614: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1615: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1616: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1617: #ifdef NRCORIGINAL
1618: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1619: #else
1620: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1621: t= t- del*SQR(fp-fptt);
1622: #endif
1623: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1624: #ifdef DEBUG
1625: 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);
1626: 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);
1627: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1628: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1629: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1630: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1631: 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);
1632: 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);
1633: #endif
1634: #ifdef POWELLORIGINAL
1635: if (t < 0.0) { /* Then we use it for new direction */
1636: #else
1637: if (directest*t < 0.0) { /* Contradiction between both tests */
1638: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1639: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1640: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1641: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1642: }
1643: if (directest < 0.0) { /* Then we use it for new direction */
1644: #endif
1645: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1646: for (j=1;j<=n;j++) {
1647: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1648: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1649: }
1650: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1651: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1652:
1653: #ifdef DEBUG
1654: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1655: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1656: for(j=1;j<=n;j++){
1657: printf(" %.12e",xit[j]);
1658: fprintf(ficlog," %.12e",xit[j]);
1659: }
1660: printf("\n");
1661: fprintf(ficlog,"\n");
1662: #endif
1663: } /* end of t negative */
1664: } /* end if (fptt < fp) */
1665: }
1666: }
1667:
1668: /**** Prevalence limit (stable or period prevalence) ****************/
1669:
1670: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1671: {
1672: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1673: matrix by transitions matrix until convergence is reached */
1674:
1675: int i, ii,j,k;
1676: double min, max, maxmin, maxmax,sumnew=0.;
1677: /* double **matprod2(); */ /* test */
1678: double **out, cov[NCOVMAX+1], **pmij();
1679: double **newm;
1680: double agefin, delaymax=50 ; /* Max number of years to converge */
1681:
1682: for (ii=1;ii<=nlstate+ndeath;ii++)
1683: for (j=1;j<=nlstate+ndeath;j++){
1684: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1685: }
1686:
1687: cov[1]=1.;
1688:
1689: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1690: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1691: newm=savm;
1692: /* Covariates have to be included here again */
1693: cov[2]=agefin;
1694:
1695: for (k=1; k<=cptcovn;k++) {
1696: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1697: /*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]]);*/
1698: }
1699: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1700: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1701: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1702:
1703: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1704: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1705: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1706: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1707: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1708: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1709:
1710: savm=oldm;
1711: oldm=newm;
1712: maxmax=0.;
1713: for(j=1;j<=nlstate;j++){
1714: min=1.;
1715: max=0.;
1716: for(i=1; i<=nlstate; i++) {
1717: sumnew=0;
1718: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1719: prlim[i][j]= newm[i][j]/(1-sumnew);
1720: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1721: max=FMAX(max,prlim[i][j]);
1722: min=FMIN(min,prlim[i][j]);
1723: }
1724: maxmin=max-min;
1725: maxmax=FMAX(maxmax,maxmin);
1726: } /* j loop */
1727: if(maxmax < ftolpl){
1728: return prlim;
1729: }
1730: } /* age loop */
1731: return prlim; /* should not reach here */
1732: }
1733:
1734: /*************** transition probabilities ***************/
1735:
1736: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1737: {
1738: /* According to parameters values stored in x and the covariate's values stored in cov,
1739: computes the probability to be observed in state j being in state i by appying the
1740: model to the ncovmodel covariates (including constant and age).
1741: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1742: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1743: ncth covariate in the global vector x is given by the formula:
1744: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1745: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1746: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1747: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1748: Outputs ps[i][j] the probability to be observed in j being in j according to
1749: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1750: */
1751: double s1, lnpijopii;
1752: /*double t34;*/
1753: int i,j, nc, ii, jj;
1754:
1755: for(i=1; i<= nlstate; i++){
1756: for(j=1; j<i;j++){
1757: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1758: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1759: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1760: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1761: }
1762: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1763: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1764: }
1765: for(j=i+1; j<=nlstate+ndeath;j++){
1766: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1767: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1768: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1769: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1770: }
1771: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1772: }
1773: }
1774:
1775: for(i=1; i<= nlstate; i++){
1776: s1=0;
1777: for(j=1; j<i; j++){
1778: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1779: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1780: }
1781: for(j=i+1; j<=nlstate+ndeath; j++){
1782: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1783: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1784: }
1785: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1786: ps[i][i]=1./(s1+1.);
1787: /* Computing other pijs */
1788: for(j=1; j<i; j++)
1789: ps[i][j]= exp(ps[i][j])*ps[i][i];
1790: for(j=i+1; j<=nlstate+ndeath; j++)
1791: ps[i][j]= exp(ps[i][j])*ps[i][i];
1792: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1793: } /* end i */
1794:
1795: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1796: for(jj=1; jj<= nlstate+ndeath; jj++){
1797: ps[ii][jj]=0;
1798: ps[ii][ii]=1;
1799: }
1800: }
1801:
1802:
1803: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1804: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1805: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1806: /* } */
1807: /* printf("\n "); */
1808: /* } */
1809: /* printf("\n ");printf("%lf ",cov[2]);*/
1810: /*
1811: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1812: goto end;*/
1813: return ps;
1814: }
1815:
1816: /**************** Product of 2 matrices ******************/
1817:
1818: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1819: {
1820: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1821: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1822: /* in, b, out are matrice of pointers which should have been initialized
1823: before: only the contents of out is modified. The function returns
1824: a pointer to pointers identical to out */
1825: int i, j, k;
1826: for(i=nrl; i<= nrh; i++)
1827: for(k=ncolol; k<=ncoloh; k++){
1828: out[i][k]=0.;
1829: for(j=ncl; j<=nch; j++)
1830: out[i][k] +=in[i][j]*b[j][k];
1831: }
1832: return out;
1833: }
1834:
1835:
1836: /************* Higher Matrix Product ***************/
1837:
1838: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1839: {
1840: /* Computes the transition matrix starting at age 'age' over
1841: 'nhstepm*hstepm*stepm' months (i.e. until
1842: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1843: nhstepm*hstepm matrices.
1844: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1845: (typically every 2 years instead of every month which is too big
1846: for the memory).
1847: Model is determined by parameters x and covariates have to be
1848: included manually here.
1849:
1850: */
1851:
1852: int i, j, d, h, k;
1853: double **out, cov[NCOVMAX+1];
1854: double **newm;
1855:
1856: /* Hstepm could be zero and should return the unit matrix */
1857: for (i=1;i<=nlstate+ndeath;i++)
1858: for (j=1;j<=nlstate+ndeath;j++){
1859: oldm[i][j]=(i==j ? 1.0 : 0.0);
1860: po[i][j][0]=(i==j ? 1.0 : 0.0);
1861: }
1862: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1863: for(h=1; h <=nhstepm; h++){
1864: for(d=1; d <=hstepm; d++){
1865: newm=savm;
1866: /* Covariates have to be included here again */
1867: cov[1]=1.;
1868: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1869: for (k=1; k<=cptcovn;k++)
1870: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1871: for (k=1; k<=cptcovage;k++)
1872: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1873: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1874: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1875:
1876:
1877: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1878: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1879: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1880: pmij(pmmij,cov,ncovmodel,x,nlstate));
1881: savm=oldm;
1882: oldm=newm;
1883: }
1884: for(i=1; i<=nlstate+ndeath; i++)
1885: for(j=1;j<=nlstate+ndeath;j++) {
1886: po[i][j][h]=newm[i][j];
1887: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1888: }
1889: /*printf("h=%d ",h);*/
1890: } /* end h */
1891: /* printf("\n H=%d \n",h); */
1892: return po;
1893: }
1894:
1895: #ifdef NLOPT
1896: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1897: double fret;
1898: double *xt;
1899: int j;
1900: myfunc_data *d2 = (myfunc_data *) pd;
1901: /* xt = (p1-1); */
1902: xt=vector(1,n);
1903: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1904:
1905: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1906: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1907: printf("Function = %.12lf ",fret);
1908: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1909: printf("\n");
1910: free_vector(xt,1,n);
1911: return fret;
1912: }
1913: #endif
1914:
1915: /*************** log-likelihood *************/
1916: double func( double *x)
1917: {
1918: int i, ii, j, k, mi, d, kk;
1919: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1920: double **out;
1921: double sw; /* Sum of weights */
1922: double lli; /* Individual log likelihood */
1923: int s1, s2;
1924: double bbh, survp;
1925: long ipmx;
1926: /*extern weight */
1927: /* We are differentiating ll according to initial status */
1928: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1929: /*for(i=1;i<imx;i++)
1930: printf(" %d\n",s[4][i]);
1931: */
1932:
1933: ++countcallfunc;
1934:
1935: cov[1]=1.;
1936:
1937: for(k=1; k<=nlstate; k++) ll[k]=0.;
1938:
1939: if(mle==1){
1940: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1941: /* Computes the values of the ncovmodel covariates of the model
1942: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1943: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1944: to be observed in j being in i according to the model.
1945: */
1946: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1947: cov[2+k]=covar[Tvar[k]][i];
1948: }
1949: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1950: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1951: has been calculated etc */
1952: for(mi=1; mi<= wav[i]-1; mi++){
1953: for (ii=1;ii<=nlstate+ndeath;ii++)
1954: for (j=1;j<=nlstate+ndeath;j++){
1955: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1956: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1957: }
1958: for(d=0; d<dh[mi][i]; d++){
1959: newm=savm;
1960: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1961: for (kk=1; kk<=cptcovage;kk++) {
1962: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1963: }
1964: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1965: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1966: savm=oldm;
1967: oldm=newm;
1968: } /* end mult */
1969:
1970: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1971: /* But now since version 0.9 we anticipate for bias at large stepm.
1972: * If stepm is larger than one month (smallest stepm) and if the exact delay
1973: * (in months) between two waves is not a multiple of stepm, we rounded to
1974: * the nearest (and in case of equal distance, to the lowest) interval but now
1975: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1976: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1977: * probability in order to take into account the bias as a fraction of the way
1978: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1979: * -stepm/2 to stepm/2 .
1980: * For stepm=1 the results are the same as for previous versions of Imach.
1981: * For stepm > 1 the results are less biased than in previous versions.
1982: */
1983: s1=s[mw[mi][i]][i];
1984: s2=s[mw[mi+1][i]][i];
1985: bbh=(double)bh[mi][i]/(double)stepm;
1986: /* bias bh is positive if real duration
1987: * is higher than the multiple of stepm and negative otherwise.
1988: */
1989: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1990: if( s2 > nlstate){
1991: /* i.e. if s2 is a death state and if the date of death is known
1992: then the contribution to the likelihood is the probability to
1993: die between last step unit time and current step unit time,
1994: which is also equal to probability to die before dh
1995: minus probability to die before dh-stepm .
1996: In version up to 0.92 likelihood was computed
1997: as if date of death was unknown. Death was treated as any other
1998: health state: the date of the interview describes the actual state
1999: and not the date of a change in health state. The former idea was
2000: to consider that at each interview the state was recorded
2001: (healthy, disable or death) and IMaCh was corrected; but when we
2002: introduced the exact date of death then we should have modified
2003: the contribution of an exact death to the likelihood. This new
2004: contribution is smaller and very dependent of the step unit
2005: stepm. It is no more the probability to die between last interview
2006: and month of death but the probability to survive from last
2007: interview up to one month before death multiplied by the
2008: probability to die within a month. Thanks to Chris
2009: Jackson for correcting this bug. Former versions increased
2010: mortality artificially. The bad side is that we add another loop
2011: which slows down the processing. The difference can be up to 10%
2012: lower mortality.
2013: */
2014: /* If, at the beginning of the maximization mostly, the
2015: cumulative probability or probability to be dead is
2016: constant (ie = 1) over time d, the difference is equal to
2017: 0. out[s1][3] = savm[s1][3]: probability, being at state
2018: s1 at precedent wave, to be dead a month before current
2019: wave is equal to probability, being at state s1 at
2020: precedent wave, to be dead at mont of the current
2021: wave. Then the observed probability (that this person died)
2022: is null according to current estimated parameter. In fact,
2023: it should be very low but not zero otherwise the log go to
2024: infinity.
2025: */
2026: /* #ifdef INFINITYORIGINAL */
2027: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2028: /* #else */
2029: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2030: /* lli=log(mytinydouble); */
2031: /* else */
2032: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2033: /* #endif */
2034: lli=log(out[s1][s2] - savm[s1][s2]);
2035:
2036: } else if (s2==-2) {
2037: for (j=1,survp=0. ; j<=nlstate; j++)
2038: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2039: /*survp += out[s1][j]; */
2040: lli= log(survp);
2041: }
2042:
2043: else if (s2==-4) {
2044: for (j=3,survp=0. ; j<=nlstate; j++)
2045: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2046: lli= log(survp);
2047: }
2048:
2049: else if (s2==-5) {
2050: for (j=1,survp=0. ; j<=2; j++)
2051: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2052: lli= log(survp);
2053: }
2054:
2055: else{
2056: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2057: /* 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 */
2058: }
2059: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2060: /*if(lli ==000.0)*/
2061: /*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); */
2062: ipmx +=1;
2063: sw += weight[i];
2064: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2065: /* if (lli < log(mytinydouble)){ */
2066: /* 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); */
2067: /* 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]); */
2068: /* } */
2069: } /* end of wave */
2070: } /* end of individual */
2071: } else if(mle==2){
2072: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2073: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2074: for(mi=1; mi<= wav[i]-1; mi++){
2075: for (ii=1;ii<=nlstate+ndeath;ii++)
2076: for (j=1;j<=nlstate+ndeath;j++){
2077: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2078: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2079: }
2080: for(d=0; d<=dh[mi][i]; d++){
2081: newm=savm;
2082: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2083: for (kk=1; kk<=cptcovage;kk++) {
2084: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2085: }
2086: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2087: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2088: savm=oldm;
2089: oldm=newm;
2090: } /* end mult */
2091:
2092: s1=s[mw[mi][i]][i];
2093: s2=s[mw[mi+1][i]][i];
2094: bbh=(double)bh[mi][i]/(double)stepm;
2095: 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 */
2096: ipmx +=1;
2097: sw += weight[i];
2098: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2099: } /* end of wave */
2100: } /* end of individual */
2101: } else if(mle==3){ /* exponential inter-extrapolation */
2102: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2103: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2104: for(mi=1; mi<= wav[i]-1; mi++){
2105: for (ii=1;ii<=nlstate+ndeath;ii++)
2106: for (j=1;j<=nlstate+ndeath;j++){
2107: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2108: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2109: }
2110: for(d=0; d<dh[mi][i]; d++){
2111: newm=savm;
2112: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2113: for (kk=1; kk<=cptcovage;kk++) {
2114: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2115: }
2116: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2117: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2118: savm=oldm;
2119: oldm=newm;
2120: } /* end mult */
2121:
2122: s1=s[mw[mi][i]][i];
2123: s2=s[mw[mi+1][i]][i];
2124: bbh=(double)bh[mi][i]/(double)stepm;
2125: 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 */
2126: ipmx +=1;
2127: sw += weight[i];
2128: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2129: } /* end of wave */
2130: } /* end of individual */
2131: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2132: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2133: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2134: for(mi=1; mi<= wav[i]-1; mi++){
2135: for (ii=1;ii<=nlstate+ndeath;ii++)
2136: for (j=1;j<=nlstate+ndeath;j++){
2137: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2138: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2139: }
2140: for(d=0; d<dh[mi][i]; d++){
2141: newm=savm;
2142: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2143: for (kk=1; kk<=cptcovage;kk++) {
2144: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2145: }
2146:
2147: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2148: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2149: savm=oldm;
2150: oldm=newm;
2151: } /* end mult */
2152:
2153: s1=s[mw[mi][i]][i];
2154: s2=s[mw[mi+1][i]][i];
2155: if( s2 > nlstate){
2156: lli=log(out[s1][s2] - savm[s1][s2]);
2157: }else{
2158: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2159: }
2160: ipmx +=1;
2161: sw += weight[i];
2162: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2163: /* 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]); */
2164: } /* end of wave */
2165: } /* end of individual */
2166: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2167: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2168: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2169: for(mi=1; mi<= wav[i]-1; mi++){
2170: for (ii=1;ii<=nlstate+ndeath;ii++)
2171: for (j=1;j<=nlstate+ndeath;j++){
2172: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2173: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2174: }
2175: for(d=0; d<dh[mi][i]; d++){
2176: newm=savm;
2177: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2178: for (kk=1; kk<=cptcovage;kk++) {
2179: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2180: }
2181:
2182: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2183: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2184: savm=oldm;
2185: oldm=newm;
2186: } /* end mult */
2187:
2188: s1=s[mw[mi][i]][i];
2189: s2=s[mw[mi+1][i]][i];
2190: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2191: ipmx +=1;
2192: sw += weight[i];
2193: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2194: /*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]);*/
2195: } /* end of wave */
2196: } /* end of individual */
2197: } /* End of if */
2198: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2199: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2200: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2201: return -l;
2202: }
2203:
2204: /*************** log-likelihood *************/
2205: double funcone( double *x)
2206: {
2207: /* Same as likeli but slower because of a lot of printf and if */
2208: int i, ii, j, k, mi, d, kk;
2209: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2210: double **out;
2211: double lli; /* Individual log likelihood */
2212: double llt;
2213: int s1, s2;
2214: double bbh, survp;
2215: /*extern weight */
2216: /* We are differentiating ll according to initial status */
2217: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2218: /*for(i=1;i<imx;i++)
2219: printf(" %d\n",s[4][i]);
2220: */
2221: cov[1]=1.;
2222:
2223: for(k=1; k<=nlstate; k++) ll[k]=0.;
2224:
2225: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2226: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2227: for(mi=1; mi<= wav[i]-1; mi++){
2228: for (ii=1;ii<=nlstate+ndeath;ii++)
2229: for (j=1;j<=nlstate+ndeath;j++){
2230: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2231: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2232: }
2233: for(d=0; d<dh[mi][i]; d++){
2234: newm=savm;
2235: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2236: for (kk=1; kk<=cptcovage;kk++) {
2237: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2238: }
2239: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2240: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2241: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2242: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2243: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2244: savm=oldm;
2245: oldm=newm;
2246: } /* end mult */
2247:
2248: s1=s[mw[mi][i]][i];
2249: s2=s[mw[mi+1][i]][i];
2250: bbh=(double)bh[mi][i]/(double)stepm;
2251: /* bias is positive if real duration
2252: * is higher than the multiple of stepm and negative otherwise.
2253: */
2254: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2255: lli=log(out[s1][s2] - savm[s1][s2]);
2256: } else if (s2==-2) {
2257: for (j=1,survp=0. ; j<=nlstate; j++)
2258: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2259: lli= log(survp);
2260: }else if (mle==1){
2261: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2262: } else if(mle==2){
2263: 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 */
2264: } else if(mle==3){ /* exponential inter-extrapolation */
2265: 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 */
2266: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2267: lli=log(out[s1][s2]); /* Original formula */
2268: } else{ /* mle=0 back to 1 */
2269: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2270: /*lli=log(out[s1][s2]); */ /* Original formula */
2271: } /* End of if */
2272: ipmx +=1;
2273: sw += weight[i];
2274: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2275: /*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]); */
2276: if(globpr){
2277: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2278: %11.6f %11.6f %11.6f ", \
2279: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2280: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2281: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2282: llt +=ll[k]*gipmx/gsw;
2283: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2284: }
2285: fprintf(ficresilk," %10.6f\n", -llt);
2286: }
2287: } /* end of wave */
2288: } /* end of individual */
2289: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2290: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2291: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2292: if(globpr==0){ /* First time we count the contributions and weights */
2293: gipmx=ipmx;
2294: gsw=sw;
2295: }
2296: return -l;
2297: }
2298:
2299:
2300: /*************** function likelione ***********/
2301: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2302: {
2303: /* This routine should help understanding what is done with
2304: the selection of individuals/waves and
2305: to check the exact contribution to the likelihood.
2306: Plotting could be done.
2307: */
2308: int k;
2309:
2310: if(*globpri !=0){ /* Just counts and sums, no printings */
2311: strcpy(fileresilk,"ilk");
2312: strcat(fileresilk,fileres);
2313: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2314: printf("Problem with resultfile: %s\n", fileresilk);
2315: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2316: }
2317: 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");
2318: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2319: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2320: for(k=1; k<=nlstate; k++)
2321: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2322: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2323: }
2324:
2325: *fretone=(*funcone)(p);
2326: if(*globpri !=0){
2327: fclose(ficresilk);
2328: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2329: fflush(fichtm);
2330: }
2331: return;
2332: }
2333:
2334:
2335: /*********** Maximum Likelihood Estimation ***************/
2336:
2337: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2338: {
2339: int i,j, iter=0;
2340: double **xi;
2341: double fret;
2342: double fretone; /* Only one call to likelihood */
2343: /* char filerespow[FILENAMELENGTH];*/
2344:
2345: #ifdef NLOPT
2346: int creturn;
2347: nlopt_opt opt;
2348: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2349: double *lb;
2350: double minf; /* the minimum objective value, upon return */
2351: double * p1; /* Shifted parameters from 0 instead of 1 */
2352: myfunc_data dinst, *d = &dinst;
2353: #endif
2354:
2355:
2356: xi=matrix(1,npar,1,npar);
2357: for (i=1;i<=npar;i++)
2358: for (j=1;j<=npar;j++)
2359: xi[i][j]=(i==j ? 1.0 : 0.0);
2360: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2361: strcpy(filerespow,"pow");
2362: strcat(filerespow,fileres);
2363: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2364: printf("Problem with resultfile: %s\n", filerespow);
2365: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2366: }
2367: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2368: for (i=1;i<=nlstate;i++)
2369: for(j=1;j<=nlstate+ndeath;j++)
2370: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2371: fprintf(ficrespow,"\n");
2372: #ifdef POWELL
2373: powell(p,xi,npar,ftol,&iter,&fret,func);
2374: #endif
2375:
2376: #ifdef NLOPT
2377: #ifdef NEWUOA
2378: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2379: #else
2380: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2381: #endif
2382: lb=vector(0,npar-1);
2383: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2384: nlopt_set_lower_bounds(opt, lb);
2385: nlopt_set_initial_step1(opt, 0.1);
2386:
2387: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2388: d->function = func;
2389: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2390: nlopt_set_min_objective(opt, myfunc, d);
2391: nlopt_set_xtol_rel(opt, ftol);
2392: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2393: printf("nlopt failed! %d\n",creturn);
2394: }
2395: else {
2396: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2397: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2398: iter=1; /* not equal */
2399: }
2400: nlopt_destroy(opt);
2401: #endif
2402: free_matrix(xi,1,npar,1,npar);
2403: fclose(ficrespow);
2404: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2405: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2406: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2407:
2408: }
2409:
2410: /**** Computes Hessian and covariance matrix ***/
2411: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2412: {
2413: double **a,**y,*x,pd;
2414: double **hess;
2415: int i, j;
2416: int *indx;
2417:
2418: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2419: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2420: void lubksb(double **a, int npar, int *indx, double b[]) ;
2421: void ludcmp(double **a, int npar, int *indx, double *d) ;
2422: double gompertz(double p[]);
2423: hess=matrix(1,npar,1,npar);
2424:
2425: printf("\nCalculation of the hessian matrix. Wait...\n");
2426: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2427: for (i=1;i<=npar;i++){
2428: printf("%d",i);fflush(stdout);
2429: fprintf(ficlog,"%d",i);fflush(ficlog);
2430:
2431: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2432:
2433: /* printf(" %f ",p[i]);
2434: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2435: }
2436:
2437: for (i=1;i<=npar;i++) {
2438: for (j=1;j<=npar;j++) {
2439: if (j>i) {
2440: printf(".%d%d",i,j);fflush(stdout);
2441: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2442: hess[i][j]=hessij(p,delti,i,j,func,npar);
2443:
2444: hess[j][i]=hess[i][j];
2445: /*printf(" %lf ",hess[i][j]);*/
2446: }
2447: }
2448: }
2449: printf("\n");
2450: fprintf(ficlog,"\n");
2451:
2452: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2453: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2454:
2455: a=matrix(1,npar,1,npar);
2456: y=matrix(1,npar,1,npar);
2457: x=vector(1,npar);
2458: indx=ivector(1,npar);
2459: for (i=1;i<=npar;i++)
2460: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2461: ludcmp(a,npar,indx,&pd);
2462:
2463: for (j=1;j<=npar;j++) {
2464: for (i=1;i<=npar;i++) x[i]=0;
2465: x[j]=1;
2466: lubksb(a,npar,indx,x);
2467: for (i=1;i<=npar;i++){
2468: matcov[i][j]=x[i];
2469: }
2470: }
2471:
2472: printf("\n#Hessian matrix#\n");
2473: fprintf(ficlog,"\n#Hessian matrix#\n");
2474: for (i=1;i<=npar;i++) {
2475: for (j=1;j<=npar;j++) {
2476: printf("%.3e ",hess[i][j]);
2477: fprintf(ficlog,"%.3e ",hess[i][j]);
2478: }
2479: printf("\n");
2480: fprintf(ficlog,"\n");
2481: }
2482:
2483: /* Recompute Inverse */
2484: for (i=1;i<=npar;i++)
2485: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2486: ludcmp(a,npar,indx,&pd);
2487:
2488: /* printf("\n#Hessian matrix recomputed#\n");
2489:
2490: for (j=1;j<=npar;j++) {
2491: for (i=1;i<=npar;i++) x[i]=0;
2492: x[j]=1;
2493: lubksb(a,npar,indx,x);
2494: for (i=1;i<=npar;i++){
2495: y[i][j]=x[i];
2496: printf("%.3e ",y[i][j]);
2497: fprintf(ficlog,"%.3e ",y[i][j]);
2498: }
2499: printf("\n");
2500: fprintf(ficlog,"\n");
2501: }
2502: */
2503:
2504: free_matrix(a,1,npar,1,npar);
2505: free_matrix(y,1,npar,1,npar);
2506: free_vector(x,1,npar);
2507: free_ivector(indx,1,npar);
2508: free_matrix(hess,1,npar,1,npar);
2509:
2510:
2511: }
2512:
2513: /*************** hessian matrix ****************/
2514: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2515: {
2516: int i;
2517: int l=1, lmax=20;
2518: double k1,k2;
2519: double p2[MAXPARM+1]; /* identical to x */
2520: double res;
2521: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2522: double fx;
2523: int k=0,kmax=10;
2524: double l1;
2525:
2526: fx=func(x);
2527: for (i=1;i<=npar;i++) p2[i]=x[i];
2528: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2529: l1=pow(10,l);
2530: delts=delt;
2531: for(k=1 ; k <kmax; k=k+1){
2532: delt = delta*(l1*k);
2533: p2[theta]=x[theta] +delt;
2534: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2535: p2[theta]=x[theta]-delt;
2536: k2=func(p2)-fx;
2537: /*res= (k1-2.0*fx+k2)/delt/delt; */
2538: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2539:
2540: #ifdef DEBUGHESS
2541: 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);
2542: 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);
2543: #endif
2544: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2545: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2546: k=kmax;
2547: }
2548: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2549: k=kmax; l=lmax*10;
2550: }
2551: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2552: delts=delt;
2553: }
2554: }
2555: }
2556: delti[theta]=delts;
2557: return res;
2558:
2559: }
2560:
2561: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2562: {
2563: int i;
2564: int l=1, lmax=20;
2565: double k1,k2,k3,k4,res,fx;
2566: double p2[MAXPARM+1];
2567: int k;
2568:
2569: fx=func(x);
2570: for (k=1; k<=2; k++) {
2571: for (i=1;i<=npar;i++) p2[i]=x[i];
2572: p2[thetai]=x[thetai]+delti[thetai]/k;
2573: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2574: k1=func(p2)-fx;
2575:
2576: p2[thetai]=x[thetai]+delti[thetai]/k;
2577: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2578: k2=func(p2)-fx;
2579:
2580: p2[thetai]=x[thetai]-delti[thetai]/k;
2581: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2582: k3=func(p2)-fx;
2583:
2584: p2[thetai]=x[thetai]-delti[thetai]/k;
2585: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2586: k4=func(p2)-fx;
2587: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2588: #ifdef DEBUG
2589: 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);
2590: 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);
2591: #endif
2592: }
2593: return res;
2594: }
2595:
2596: /************** Inverse of matrix **************/
2597: void ludcmp(double **a, int n, int *indx, double *d)
2598: {
2599: int i,imax,j,k;
2600: double big,dum,sum,temp;
2601: double *vv;
2602:
2603: vv=vector(1,n);
2604: *d=1.0;
2605: for (i=1;i<=n;i++) {
2606: big=0.0;
2607: for (j=1;j<=n;j++)
2608: if ((temp=fabs(a[i][j])) > big) big=temp;
2609: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2610: vv[i]=1.0/big;
2611: }
2612: for (j=1;j<=n;j++) {
2613: for (i=1;i<j;i++) {
2614: sum=a[i][j];
2615: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2616: a[i][j]=sum;
2617: }
2618: big=0.0;
2619: for (i=j;i<=n;i++) {
2620: sum=a[i][j];
2621: for (k=1;k<j;k++)
2622: sum -= a[i][k]*a[k][j];
2623: a[i][j]=sum;
2624: if ( (dum=vv[i]*fabs(sum)) >= big) {
2625: big=dum;
2626: imax=i;
2627: }
2628: }
2629: if (j != imax) {
2630: for (k=1;k<=n;k++) {
2631: dum=a[imax][k];
2632: a[imax][k]=a[j][k];
2633: a[j][k]=dum;
2634: }
2635: *d = -(*d);
2636: vv[imax]=vv[j];
2637: }
2638: indx[j]=imax;
2639: if (a[j][j] == 0.0) a[j][j]=TINY;
2640: if (j != n) {
2641: dum=1.0/(a[j][j]);
2642: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2643: }
2644: }
2645: free_vector(vv,1,n); /* Doesn't work */
2646: ;
2647: }
2648:
2649: void lubksb(double **a, int n, int *indx, double b[])
2650: {
2651: int i,ii=0,ip,j;
2652: double sum;
2653:
2654: for (i=1;i<=n;i++) {
2655: ip=indx[i];
2656: sum=b[ip];
2657: b[ip]=b[i];
2658: if (ii)
2659: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2660: else if (sum) ii=i;
2661: b[i]=sum;
2662: }
2663: for (i=n;i>=1;i--) {
2664: sum=b[i];
2665: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2666: b[i]=sum/a[i][i];
2667: }
2668: }
2669:
2670: void pstamp(FILE *fichier)
2671: {
2672: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2673: }
2674:
2675: /************ Frequencies ********************/
2676: 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[])
2677: { /* Some frequencies */
2678:
2679: int i, m, jk, j1, bool, z1,j;
2680: int first;
2681: double ***freq; /* Frequencies */
2682: double *pp, **prop;
2683: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2684: char fileresp[FILENAMELENGTH];
2685:
2686: pp=vector(1,nlstate);
2687: prop=matrix(1,nlstate,iagemin,iagemax+3);
2688: strcpy(fileresp,"p");
2689: strcat(fileresp,fileres);
2690: if((ficresp=fopen(fileresp,"w"))==NULL) {
2691: printf("Problem with prevalence resultfile: %s\n", fileresp);
2692: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2693: exit(0);
2694: }
2695: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2696: j1=0;
2697:
2698: j=cptcoveff;
2699: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2700:
2701: first=1;
2702:
2703: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2704: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2705: /* j1++; */
2706: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2707: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2708: scanf("%d", i);*/
2709: for (i=-5; i<=nlstate+ndeath; i++)
2710: for (jk=-5; jk<=nlstate+ndeath; jk++)
2711: for(m=iagemin; m <= iagemax+3; m++)
2712: freq[i][jk][m]=0;
2713:
2714: for (i=1; i<=nlstate; i++)
2715: for(m=iagemin; m <= iagemax+3; m++)
2716: prop[i][m]=0;
2717:
2718: dateintsum=0;
2719: k2cpt=0;
2720: for (i=1; i<=imx; i++) {
2721: bool=1;
2722: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2723: for (z1=1; z1<=cptcoveff; z1++)
2724: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2725: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2726: bool=0;
2727: /* 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",
2728: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2729: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2730: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2731: }
2732: }
2733:
2734: if (bool==1){
2735: for(m=firstpass; m<=lastpass; m++){
2736: k2=anint[m][i]+(mint[m][i]/12.);
2737: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2738: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2739: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2740: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2741: if (m<lastpass) {
2742: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2743: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2744: }
2745:
2746: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2747: dateintsum=dateintsum+k2;
2748: k2cpt++;
2749: }
2750: /*}*/
2751: }
2752: }
2753: } /* end i */
2754:
2755: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2756: pstamp(ficresp);
2757: if (cptcovn>0) {
2758: fprintf(ficresp, "\n#********** Variable ");
2759: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2760: fprintf(ficresp, "**********\n#");
2761: fprintf(ficlog, "\n#********** Variable ");
2762: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2763: fprintf(ficlog, "**********\n#");
2764: }
2765: for(i=1; i<=nlstate;i++)
2766: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2767: fprintf(ficresp, "\n");
2768:
2769: for(i=iagemin; i <= iagemax+3; i++){
2770: if(i==iagemax+3){
2771: fprintf(ficlog,"Total");
2772: }else{
2773: if(first==1){
2774: first=0;
2775: printf("See log file for details...\n");
2776: }
2777: fprintf(ficlog,"Age %d", i);
2778: }
2779: for(jk=1; jk <=nlstate ; jk++){
2780: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2781: pp[jk] += freq[jk][m][i];
2782: }
2783: for(jk=1; jk <=nlstate ; jk++){
2784: for(m=-1, pos=0; m <=0 ; m++)
2785: pos += freq[jk][m][i];
2786: if(pp[jk]>=1.e-10){
2787: if(first==1){
2788: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2789: }
2790: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2791: }else{
2792: if(first==1)
2793: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2794: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2795: }
2796: }
2797:
2798: for(jk=1; jk <=nlstate ; jk++){
2799: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2800: pp[jk] += freq[jk][m][i];
2801: }
2802: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2803: pos += pp[jk];
2804: posprop += prop[jk][i];
2805: }
2806: for(jk=1; jk <=nlstate ; jk++){
2807: if(pos>=1.e-5){
2808: if(first==1)
2809: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2810: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2811: }else{
2812: if(first==1)
2813: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2814: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2815: }
2816: if( i <= iagemax){
2817: if(pos>=1.e-5){
2818: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2819: /*probs[i][jk][j1]= pp[jk]/pos;*/
2820: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2821: }
2822: else
2823: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2824: }
2825: }
2826:
2827: for(jk=-1; jk <=nlstate+ndeath; jk++)
2828: for(m=-1; m <=nlstate+ndeath; m++)
2829: if(freq[jk][m][i] !=0 ) {
2830: if(first==1)
2831: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2832: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2833: }
2834: if(i <= iagemax)
2835: fprintf(ficresp,"\n");
2836: if(first==1)
2837: printf("Others in log...\n");
2838: fprintf(ficlog,"\n");
2839: }
2840: /*}*/
2841: }
2842: dateintmean=dateintsum/k2cpt;
2843:
2844: fclose(ficresp);
2845: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2846: free_vector(pp,1,nlstate);
2847: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2848: /* End of Freq */
2849: }
2850:
2851: /************ Prevalence ********************/
2852: 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)
2853: {
2854: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2855: in each health status at the date of interview (if between dateprev1 and dateprev2).
2856: We still use firstpass and lastpass as another selection.
2857: */
2858:
2859: int i, m, jk, j1, bool, z1,j;
2860:
2861: double **prop;
2862: double posprop;
2863: double y2; /* in fractional years */
2864: int iagemin, iagemax;
2865: int first; /** to stop verbosity which is redirected to log file */
2866:
2867: iagemin= (int) agemin;
2868: iagemax= (int) agemax;
2869: /*pp=vector(1,nlstate);*/
2870: prop=matrix(1,nlstate,iagemin,iagemax+3);
2871: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2872: j1=0;
2873:
2874: /*j=cptcoveff;*/
2875: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2876:
2877: first=1;
2878: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2879: /*for(i1=1; i1<=ncodemax[k1];i1++){
2880: j1++;*/
2881:
2882: for (i=1; i<=nlstate; i++)
2883: for(m=iagemin; m <= iagemax+3; m++)
2884: prop[i][m]=0.0;
2885:
2886: for (i=1; i<=imx; i++) { /* Each individual */
2887: bool=1;
2888: if (cptcovn>0) {
2889: for (z1=1; z1<=cptcoveff; z1++)
2890: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2891: bool=0;
2892: }
2893: if (bool==1) {
2894: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2895: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2896: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2897: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2898: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2899: 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);
2900: if (s[m][i]>0 && s[m][i]<=nlstate) {
2901: /*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]]);*/
2902: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2903: prop[s[m][i]][iagemax+3] += weight[i];
2904: }
2905: }
2906: } /* end selection of waves */
2907: }
2908: }
2909: for(i=iagemin; i <= iagemax+3; i++){
2910: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2911: posprop += prop[jk][i];
2912: }
2913:
2914: for(jk=1; jk <=nlstate ; jk++){
2915: if( i <= iagemax){
2916: if(posprop>=1.e-5){
2917: probs[i][jk][j1]= prop[jk][i]/posprop;
2918: } else{
2919: if(first==1){
2920: first=0;
2921: 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]);
2922: }
2923: }
2924: }
2925: }/* end jk */
2926: }/* end i */
2927: /*} *//* end i1 */
2928: } /* end j1 */
2929:
2930: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2931: /*free_vector(pp,1,nlstate);*/
2932: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2933: } /* End of prevalence */
2934:
2935: /************* Waves Concatenation ***************/
2936:
2937: 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)
2938: {
2939: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2940: Death is a valid wave (if date is known).
2941: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2942: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2943: and mw[mi+1][i]. dh depends on stepm.
2944: */
2945:
2946: int i, mi, m;
2947: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2948: double sum=0., jmean=0.;*/
2949: int first;
2950: int j, k=0,jk, ju, jl;
2951: double sum=0.;
2952: first=0;
2953: jmin=100000;
2954: jmax=-1;
2955: jmean=0.;
2956: for(i=1; i<=imx; i++){
2957: mi=0;
2958: m=firstpass;
2959: while(s[m][i] <= nlstate){
2960: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2961: mw[++mi][i]=m;
2962: if(m >=lastpass)
2963: break;
2964: else
2965: m++;
2966: }/* end while */
2967: if (s[m][i] > nlstate){
2968: mi++; /* Death is another wave */
2969: /* if(mi==0) never been interviewed correctly before death */
2970: /* Only death is a correct wave */
2971: mw[mi][i]=m;
2972: }
2973:
2974: wav[i]=mi;
2975: if(mi==0){
2976: nbwarn++;
2977: if(first==0){
2978: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2979: first=1;
2980: }
2981: if(first==1){
2982: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2983: }
2984: } /* end mi==0 */
2985: } /* End individuals */
2986:
2987: for(i=1; i<=imx; i++){
2988: for(mi=1; mi<wav[i];mi++){
2989: if (stepm <=0)
2990: dh[mi][i]=1;
2991: else{
2992: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2993: if (agedc[i] < 2*AGESUP) {
2994: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2995: if(j==0) j=1; /* Survives at least one month after exam */
2996: else if(j<0){
2997: nberr++;
2998: 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]);
2999: j=1; /* Temporary Dangerous patch */
3000: 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);
3001: 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]);
3002: 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);
3003: }
3004: k=k+1;
3005: if (j >= jmax){
3006: jmax=j;
3007: ijmax=i;
3008: }
3009: if (j <= jmin){
3010: jmin=j;
3011: ijmin=i;
3012: }
3013: sum=sum+j;
3014: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3015: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3016: }
3017: }
3018: else{
3019: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3020: /* 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]); */
3021:
3022: k=k+1;
3023: if (j >= jmax) {
3024: jmax=j;
3025: ijmax=i;
3026: }
3027: else if (j <= jmin){
3028: jmin=j;
3029: ijmin=i;
3030: }
3031: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3032: /*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]);*/
3033: if(j<0){
3034: nberr++;
3035: 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]);
3036: 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]);
3037: }
3038: sum=sum+j;
3039: }
3040: jk= j/stepm;
3041: jl= j -jk*stepm;
3042: ju= j -(jk+1)*stepm;
3043: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3044: if(jl==0){
3045: dh[mi][i]=jk;
3046: bh[mi][i]=0;
3047: }else{ /* We want a negative bias in order to only have interpolation ie
3048: * to avoid the price of an extra matrix product in likelihood */
3049: dh[mi][i]=jk+1;
3050: bh[mi][i]=ju;
3051: }
3052: }else{
3053: if(jl <= -ju){
3054: dh[mi][i]=jk;
3055: bh[mi][i]=jl; /* bias is positive if real duration
3056: * is higher than the multiple of stepm and negative otherwise.
3057: */
3058: }
3059: else{
3060: dh[mi][i]=jk+1;
3061: bh[mi][i]=ju;
3062: }
3063: if(dh[mi][i]==0){
3064: dh[mi][i]=1; /* At least one step */
3065: bh[mi][i]=ju; /* At least one step */
3066: /* 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);*/
3067: }
3068: } /* end if mle */
3069: }
3070: } /* end wave */
3071: }
3072: jmean=sum/k;
3073: 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);
3074: 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);
3075: }
3076:
3077: /*********** Tricode ****************************/
3078: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3079: {
3080: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3081: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3082: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3083: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3084: * nbcode[Tvar[j]][1]=
3085: */
3086:
3087: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3088: int modmaxcovj=0; /* Modality max of covariates j */
3089: int cptcode=0; /* Modality max of covariates j */
3090: int modmincovj=0; /* Modality min of covariates j */
3091:
3092:
3093: cptcoveff=0;
3094:
3095: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3096: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3097:
3098: /* Loop on covariates without age and products */
3099: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
3100: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
3101: modality of this covariate Vj*/
3102: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3103: * If product of Vn*Vm, still boolean *:
3104: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3105: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3106: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3107: modality of the nth covariate of individual i. */
3108: if (ij > modmaxcovj)
3109: modmaxcovj=ij;
3110: else if (ij < modmincovj)
3111: modmincovj=ij;
3112: if ((ij < -1) && (ij > NCOVMAX)){
3113: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3114: exit(1);
3115: }else
3116: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3117: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3118: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3119: /* getting the maximum value of the modality of the covariate
3120: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3121: female is 1, then modmaxcovj=1.*/
3122: }
3123: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3124: cptcode=modmaxcovj;
3125: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3126: /*for (i=0; i<=cptcode; i++) {*/
3127: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3128: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3129: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3130: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3131: }
3132: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3133: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3134: } /* Ndum[-1] number of undefined modalities */
3135:
3136: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3137: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3138: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3139: modmincovj=3; modmaxcovj = 7;
3140: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3141: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3142: variables V1_1 and V1_2.
3143: nbcode[Tvar[j]][ij]=k;
3144: nbcode[Tvar[j]][1]=0;
3145: nbcode[Tvar[j]][2]=1;
3146: nbcode[Tvar[j]][3]=2;
3147: */
3148: ij=1; /* ij is similar to i but can jumps over null modalities */
3149: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3150: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3151: /*recode from 0 */
3152: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3153: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3154: k is a modality. If we have model=V1+V1*sex
3155: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3156: ij++;
3157: }
3158: if (ij > ncodemax[j]) break;
3159: } /* end of loop on */
3160: } /* end of loop on modality */
3161: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3162:
3163: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3164:
3165: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3166: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3167: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3168: Ndum[ij]++;
3169: }
3170:
3171: ij=1;
3172: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3173: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3174: if((Ndum[i]!=0) && (i<=ncovcol)){
3175: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3176: Tvaraff[ij]=i; /*For printing (unclear) */
3177: ij++;
3178: }else
3179: Tvaraff[ij]=0;
3180: }
3181: ij--;
3182: cptcoveff=ij; /*Number of total covariates*/
3183:
3184: }
3185:
3186:
3187: /*********** Health Expectancies ****************/
3188:
3189: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3190:
3191: {
3192: /* Health expectancies, no variances */
3193: int i, j, nhstepm, hstepm, h, nstepm;
3194: int nhstepma, nstepma; /* Decreasing with age */
3195: double age, agelim, hf;
3196: double ***p3mat;
3197: double eip;
3198:
3199: pstamp(ficreseij);
3200: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3201: fprintf(ficreseij,"# Age");
3202: for(i=1; i<=nlstate;i++){
3203: for(j=1; j<=nlstate;j++){
3204: fprintf(ficreseij," e%1d%1d ",i,j);
3205: }
3206: fprintf(ficreseij," e%1d. ",i);
3207: }
3208: fprintf(ficreseij,"\n");
3209:
3210:
3211: if(estepm < stepm){
3212: printf ("Problem %d lower than %d\n",estepm, stepm);
3213: }
3214: else hstepm=estepm;
3215: /* We compute the life expectancy from trapezoids spaced every estepm months
3216: * This is mainly to measure the difference between two models: for example
3217: * if stepm=24 months pijx are given only every 2 years and by summing them
3218: * we are calculating an estimate of the Life Expectancy assuming a linear
3219: * progression in between and thus overestimating or underestimating according
3220: * to the curvature of the survival function. If, for the same date, we
3221: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3222: * to compare the new estimate of Life expectancy with the same linear
3223: * hypothesis. A more precise result, taking into account a more precise
3224: * curvature will be obtained if estepm is as small as stepm. */
3225:
3226: /* For example we decided to compute the life expectancy with the smallest unit */
3227: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3228: nhstepm is the number of hstepm from age to agelim
3229: nstepm is the number of stepm from age to agelin.
3230: Look at hpijx to understand the reason of that which relies in memory size
3231: and note for a fixed period like estepm months */
3232: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3233: survival function given by stepm (the optimization length). Unfortunately it
3234: means that if the survival funtion is printed only each two years of age and if
3235: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3236: results. So we changed our mind and took the option of the best precision.
3237: */
3238: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3239:
3240: agelim=AGESUP;
3241: /* If stepm=6 months */
3242: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3243: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3244:
3245: /* nhstepm age range expressed in number of stepm */
3246: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3247: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3248: /* if (stepm >= YEARM) hstepm=1;*/
3249: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3250: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3251:
3252: for (age=bage; age<=fage; age ++){
3253: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3254: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3255: /* if (stepm >= YEARM) hstepm=1;*/
3256: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3257:
3258: /* If stepm=6 months */
3259: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3260: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3261:
3262: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3263:
3264: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3265:
3266: printf("%d|",(int)age);fflush(stdout);
3267: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3268:
3269: /* Computing expectancies */
3270: for(i=1; i<=nlstate;i++)
3271: for(j=1; j<=nlstate;j++)
3272: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3273: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3274:
3275: /* 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]);*/
3276:
3277: }
3278:
3279: fprintf(ficreseij,"%3.0f",age );
3280: for(i=1; i<=nlstate;i++){
3281: eip=0;
3282: for(j=1; j<=nlstate;j++){
3283: eip +=eij[i][j][(int)age];
3284: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3285: }
3286: fprintf(ficreseij,"%9.4f", eip );
3287: }
3288: fprintf(ficreseij,"\n");
3289:
3290: }
3291: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3292: printf("\n");
3293: fprintf(ficlog,"\n");
3294:
3295: }
3296:
3297: 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[] )
3298:
3299: {
3300: /* Covariances of health expectancies eij and of total life expectancies according
3301: to initial status i, ei. .
3302: */
3303: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3304: int nhstepma, nstepma; /* Decreasing with age */
3305: double age, agelim, hf;
3306: double ***p3matp, ***p3matm, ***varhe;
3307: double **dnewm,**doldm;
3308: double *xp, *xm;
3309: double **gp, **gm;
3310: double ***gradg, ***trgradg;
3311: int theta;
3312:
3313: double eip, vip;
3314:
3315: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3316: xp=vector(1,npar);
3317: xm=vector(1,npar);
3318: dnewm=matrix(1,nlstate*nlstate,1,npar);
3319: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3320:
3321: pstamp(ficresstdeij);
3322: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3323: fprintf(ficresstdeij,"# Age");
3324: for(i=1; i<=nlstate;i++){
3325: for(j=1; j<=nlstate;j++)
3326: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3327: fprintf(ficresstdeij," e%1d. ",i);
3328: }
3329: fprintf(ficresstdeij,"\n");
3330:
3331: pstamp(ficrescveij);
3332: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3333: fprintf(ficrescveij,"# Age");
3334: for(i=1; i<=nlstate;i++)
3335: for(j=1; j<=nlstate;j++){
3336: cptj= (j-1)*nlstate+i;
3337: for(i2=1; i2<=nlstate;i2++)
3338: for(j2=1; j2<=nlstate;j2++){
3339: cptj2= (j2-1)*nlstate+i2;
3340: if(cptj2 <= cptj)
3341: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3342: }
3343: }
3344: fprintf(ficrescveij,"\n");
3345:
3346: if(estepm < stepm){
3347: printf ("Problem %d lower than %d\n",estepm, stepm);
3348: }
3349: else hstepm=estepm;
3350: /* We compute the life expectancy from trapezoids spaced every estepm months
3351: * This is mainly to measure the difference between two models: for example
3352: * if stepm=24 months pijx are given only every 2 years and by summing them
3353: * we are calculating an estimate of the Life Expectancy assuming a linear
3354: * progression in between and thus overestimating or underestimating according
3355: * to the curvature of the survival function. If, for the same date, we
3356: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3357: * to compare the new estimate of Life expectancy with the same linear
3358: * hypothesis. A more precise result, taking into account a more precise
3359: * curvature will be obtained if estepm is as small as stepm. */
3360:
3361: /* For example we decided to compute the life expectancy with the smallest unit */
3362: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3363: nhstepm is the number of hstepm from age to agelim
3364: nstepm is the number of stepm from age to agelin.
3365: Look at hpijx to understand the reason of that which relies in memory size
3366: and note for a fixed period like estepm months */
3367: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3368: survival function given by stepm (the optimization length). Unfortunately it
3369: means that if the survival funtion is printed only each two years of age and if
3370: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3371: results. So we changed our mind and took the option of the best precision.
3372: */
3373: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3374:
3375: /* If stepm=6 months */
3376: /* nhstepm age range expressed in number of stepm */
3377: agelim=AGESUP;
3378: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3379: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3380: /* if (stepm >= YEARM) hstepm=1;*/
3381: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3382:
3383: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3384: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3385: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3386: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3387: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3388: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3389:
3390: for (age=bage; age<=fage; age ++){
3391: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3392: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3393: /* if (stepm >= YEARM) hstepm=1;*/
3394: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3395:
3396: /* If stepm=6 months */
3397: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3398: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3399:
3400: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3401:
3402: /* Computing Variances of health expectancies */
3403: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3404: decrease memory allocation */
3405: for(theta=1; theta <=npar; theta++){
3406: for(i=1; i<=npar; i++){
3407: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3408: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3409: }
3410: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3411: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3412:
3413: for(j=1; j<= nlstate; j++){
3414: for(i=1; i<=nlstate; i++){
3415: for(h=0; h<=nhstepm-1; h++){
3416: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3417: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3418: }
3419: }
3420: }
3421:
3422: for(ij=1; ij<= nlstate*nlstate; ij++)
3423: for(h=0; h<=nhstepm-1; h++){
3424: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3425: }
3426: }/* End theta */
3427:
3428:
3429: for(h=0; h<=nhstepm-1; h++)
3430: for(j=1; j<=nlstate*nlstate;j++)
3431: for(theta=1; theta <=npar; theta++)
3432: trgradg[h][j][theta]=gradg[h][theta][j];
3433:
3434:
3435: for(ij=1;ij<=nlstate*nlstate;ij++)
3436: for(ji=1;ji<=nlstate*nlstate;ji++)
3437: varhe[ij][ji][(int)age] =0.;
3438:
3439: printf("%d|",(int)age);fflush(stdout);
3440: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3441: for(h=0;h<=nhstepm-1;h++){
3442: for(k=0;k<=nhstepm-1;k++){
3443: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3444: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3445: for(ij=1;ij<=nlstate*nlstate;ij++)
3446: for(ji=1;ji<=nlstate*nlstate;ji++)
3447: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3448: }
3449: }
3450:
3451: /* Computing expectancies */
3452: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3453: for(i=1; i<=nlstate;i++)
3454: for(j=1; j<=nlstate;j++)
3455: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3456: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3457:
3458: /* 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]);*/
3459:
3460: }
3461:
3462: fprintf(ficresstdeij,"%3.0f",age );
3463: for(i=1; i<=nlstate;i++){
3464: eip=0.;
3465: vip=0.;
3466: for(j=1; j<=nlstate;j++){
3467: eip += eij[i][j][(int)age];
3468: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3469: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3470: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3471: }
3472: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3473: }
3474: fprintf(ficresstdeij,"\n");
3475:
3476: fprintf(ficrescveij,"%3.0f",age );
3477: for(i=1; i<=nlstate;i++)
3478: for(j=1; j<=nlstate;j++){
3479: cptj= (j-1)*nlstate+i;
3480: for(i2=1; i2<=nlstate;i2++)
3481: for(j2=1; j2<=nlstate;j2++){
3482: cptj2= (j2-1)*nlstate+i2;
3483: if(cptj2 <= cptj)
3484: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3485: }
3486: }
3487: fprintf(ficrescveij,"\n");
3488:
3489: }
3490: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3491: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3492: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3493: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3494: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3495: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3496: printf("\n");
3497: fprintf(ficlog,"\n");
3498:
3499: free_vector(xm,1,npar);
3500: free_vector(xp,1,npar);
3501: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3502: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3503: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3504: }
3505:
3506: /************ Variance ******************/
3507: 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[])
3508: {
3509: /* Variance of health expectancies */
3510: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3511: /* double **newm;*/
3512: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3513:
3514: int movingaverage();
3515: double **dnewm,**doldm;
3516: double **dnewmp,**doldmp;
3517: int i, j, nhstepm, hstepm, h, nstepm ;
3518: int k;
3519: double *xp;
3520: double **gp, **gm; /* for var eij */
3521: double ***gradg, ***trgradg; /*for var eij */
3522: double **gradgp, **trgradgp; /* for var p point j */
3523: double *gpp, *gmp; /* for var p point j */
3524: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3525: double ***p3mat;
3526: double age,agelim, hf;
3527: double ***mobaverage;
3528: int theta;
3529: char digit[4];
3530: char digitp[25];
3531:
3532: char fileresprobmorprev[FILENAMELENGTH];
3533:
3534: if(popbased==1){
3535: if(mobilav!=0)
3536: strcpy(digitp,"-populbased-mobilav-");
3537: else strcpy(digitp,"-populbased-nomobil-");
3538: }
3539: else
3540: strcpy(digitp,"-stablbased-");
3541:
3542: if (mobilav!=0) {
3543: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3544: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3545: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3546: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3547: }
3548: }
3549:
3550: strcpy(fileresprobmorprev,"prmorprev");
3551: sprintf(digit,"%-d",ij);
3552: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3553: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3554: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3555: strcat(fileresprobmorprev,fileres);
3556: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3557: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3558: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3559: }
3560: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3561:
3562: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3563: pstamp(ficresprobmorprev);
3564: 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);
3565: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3566: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3567: fprintf(ficresprobmorprev," p.%-d SE",j);
3568: for(i=1; i<=nlstate;i++)
3569: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3570: }
3571: fprintf(ficresprobmorprev,"\n");
3572: fprintf(ficgp,"\n# Routine varevsij");
3573: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3574: 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");
3575: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3576: /* } */
3577: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3578: pstamp(ficresvij);
3579: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3580: if(popbased==1)
3581: 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);
3582: else
3583: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3584: fprintf(ficresvij,"# Age");
3585: for(i=1; i<=nlstate;i++)
3586: for(j=1; j<=nlstate;j++)
3587: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3588: fprintf(ficresvij,"\n");
3589:
3590: xp=vector(1,npar);
3591: dnewm=matrix(1,nlstate,1,npar);
3592: doldm=matrix(1,nlstate,1,nlstate);
3593: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3594: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3595:
3596: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3597: gpp=vector(nlstate+1,nlstate+ndeath);
3598: gmp=vector(nlstate+1,nlstate+ndeath);
3599: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3600:
3601: if(estepm < stepm){
3602: printf ("Problem %d lower than %d\n",estepm, stepm);
3603: }
3604: else hstepm=estepm;
3605: /* For example we decided to compute the life expectancy with the smallest unit */
3606: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3607: nhstepm is the number of hstepm from age to agelim
3608: nstepm is the number of stepm from age to agelin.
3609: Look at function hpijx to understand why (it is linked to memory size questions) */
3610: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3611: survival function given by stepm (the optimization length). Unfortunately it
3612: means that if the survival funtion is printed every two years of age and if
3613: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3614: results. So we changed our mind and took the option of the best precision.
3615: */
3616: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3617: agelim = AGESUP;
3618: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3619: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3620: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3621: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3622: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3623: gp=matrix(0,nhstepm,1,nlstate);
3624: gm=matrix(0,nhstepm,1,nlstate);
3625:
3626:
3627: for(theta=1; theta <=npar; theta++){
3628: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3629: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3630: }
3631: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3632: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3633:
3634: if (popbased==1) {
3635: if(mobilav ==0){
3636: for(i=1; i<=nlstate;i++)
3637: prlim[i][i]=probs[(int)age][i][ij];
3638: }else{ /* mobilav */
3639: for(i=1; i<=nlstate;i++)
3640: prlim[i][i]=mobaverage[(int)age][i][ij];
3641: }
3642: }
3643:
3644: for(j=1; j<= nlstate; j++){
3645: for(h=0; h<=nhstepm; h++){
3646: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3647: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3648: }
3649: }
3650: /* This for computing probability of death (h=1 means
3651: computed over hstepm matrices product = hstepm*stepm months)
3652: as a weighted average of prlim.
3653: */
3654: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3655: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3656: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3657: }
3658: /* end probability of death */
3659:
3660: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3661: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3662: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3663: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3664:
3665: if (popbased==1) {
3666: if(mobilav ==0){
3667: for(i=1; i<=nlstate;i++)
3668: prlim[i][i]=probs[(int)age][i][ij];
3669: }else{ /* mobilav */
3670: for(i=1; i<=nlstate;i++)
3671: prlim[i][i]=mobaverage[(int)age][i][ij];
3672: }
3673: }
3674:
3675: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3676: for(h=0; h<=nhstepm; h++){
3677: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3678: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3679: }
3680: }
3681: /* This for computing probability of death (h=1 means
3682: computed over hstepm matrices product = hstepm*stepm months)
3683: as a weighted average of prlim.
3684: */
3685: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3686: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3687: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3688: }
3689: /* end probability of death */
3690:
3691: for(j=1; j<= nlstate; j++) /* vareij */
3692: for(h=0; h<=nhstepm; h++){
3693: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3694: }
3695:
3696: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3697: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3698: }
3699:
3700: } /* End theta */
3701:
3702: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3703:
3704: for(h=0; h<=nhstepm; h++) /* veij */
3705: for(j=1; j<=nlstate;j++)
3706: for(theta=1; theta <=npar; theta++)
3707: trgradg[h][j][theta]=gradg[h][theta][j];
3708:
3709: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3710: for(theta=1; theta <=npar; theta++)
3711: trgradgp[j][theta]=gradgp[theta][j];
3712:
3713:
3714: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3715: for(i=1;i<=nlstate;i++)
3716: for(j=1;j<=nlstate;j++)
3717: vareij[i][j][(int)age] =0.;
3718:
3719: for(h=0;h<=nhstepm;h++){
3720: for(k=0;k<=nhstepm;k++){
3721: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3722: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3723: for(i=1;i<=nlstate;i++)
3724: for(j=1;j<=nlstate;j++)
3725: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3726: }
3727: }
3728:
3729: /* pptj */
3730: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3731: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3732: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3733: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3734: varppt[j][i]=doldmp[j][i];
3735: /* end ppptj */
3736: /* x centered again */
3737: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3738: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3739:
3740: if (popbased==1) {
3741: if(mobilav ==0){
3742: for(i=1; i<=nlstate;i++)
3743: prlim[i][i]=probs[(int)age][i][ij];
3744: }else{ /* mobilav */
3745: for(i=1; i<=nlstate;i++)
3746: prlim[i][i]=mobaverage[(int)age][i][ij];
3747: }
3748: }
3749:
3750: /* This for computing probability of death (h=1 means
3751: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3752: as a weighted average of prlim.
3753: */
3754: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3755: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3756: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3757: }
3758: /* end probability of death */
3759:
3760: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3761: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3762: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3763: for(i=1; i<=nlstate;i++){
3764: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3765: }
3766: }
3767: fprintf(ficresprobmorprev,"\n");
3768:
3769: fprintf(ficresvij,"%.0f ",age );
3770: for(i=1; i<=nlstate;i++)
3771: for(j=1; j<=nlstate;j++){
3772: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3773: }
3774: fprintf(ficresvij,"\n");
3775: free_matrix(gp,0,nhstepm,1,nlstate);
3776: free_matrix(gm,0,nhstepm,1,nlstate);
3777: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3778: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3779: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3780: } /* End age */
3781: free_vector(gpp,nlstate+1,nlstate+ndeath);
3782: free_vector(gmp,nlstate+1,nlstate+ndeath);
3783: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3784: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3785: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3786: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3787: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3788: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3789: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3790: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3791: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3792: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3793: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3794: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3795: 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);
3796: /* 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);
3797: */
3798: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3799: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3800:
3801: free_vector(xp,1,npar);
3802: free_matrix(doldm,1,nlstate,1,nlstate);
3803: free_matrix(dnewm,1,nlstate,1,npar);
3804: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3805: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3806: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3807: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3808: fclose(ficresprobmorprev);
3809: fflush(ficgp);
3810: fflush(fichtm);
3811: } /* end varevsij */
3812:
3813: /************ Variance of prevlim ******************/
3814: 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[])
3815: {
3816: /* Variance of prevalence limit */
3817: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3818:
3819: double **dnewm,**doldm;
3820: int i, j, nhstepm, hstepm;
3821: double *xp;
3822: double *gp, *gm;
3823: double **gradg, **trgradg;
3824: double age,agelim;
3825: int theta;
3826:
3827: pstamp(ficresvpl);
3828: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3829: fprintf(ficresvpl,"# Age");
3830: for(i=1; i<=nlstate;i++)
3831: fprintf(ficresvpl," %1d-%1d",i,i);
3832: fprintf(ficresvpl,"\n");
3833:
3834: xp=vector(1,npar);
3835: dnewm=matrix(1,nlstate,1,npar);
3836: doldm=matrix(1,nlstate,1,nlstate);
3837:
3838: hstepm=1*YEARM; /* Every year of age */
3839: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3840: agelim = AGESUP;
3841: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3842: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3843: if (stepm >= YEARM) hstepm=1;
3844: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3845: gradg=matrix(1,npar,1,nlstate);
3846: gp=vector(1,nlstate);
3847: gm=vector(1,nlstate);
3848:
3849: for(theta=1; theta <=npar; theta++){
3850: for(i=1; i<=npar; i++){ /* Computes gradient */
3851: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3852: }
3853: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3854: for(i=1;i<=nlstate;i++)
3855: gp[i] = prlim[i][i];
3856:
3857: for(i=1; i<=npar; i++) /* Computes gradient */
3858: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3859: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3860: for(i=1;i<=nlstate;i++)
3861: gm[i] = prlim[i][i];
3862:
3863: for(i=1;i<=nlstate;i++)
3864: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3865: } /* End theta */
3866:
3867: trgradg =matrix(1,nlstate,1,npar);
3868:
3869: for(j=1; j<=nlstate;j++)
3870: for(theta=1; theta <=npar; theta++)
3871: trgradg[j][theta]=gradg[theta][j];
3872:
3873: for(i=1;i<=nlstate;i++)
3874: varpl[i][(int)age] =0.;
3875: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3876: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3877: for(i=1;i<=nlstate;i++)
3878: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3879:
3880: fprintf(ficresvpl,"%.0f ",age );
3881: for(i=1; i<=nlstate;i++)
3882: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3883: fprintf(ficresvpl,"\n");
3884: free_vector(gp,1,nlstate);
3885: free_vector(gm,1,nlstate);
3886: free_matrix(gradg,1,npar,1,nlstate);
3887: free_matrix(trgradg,1,nlstate,1,npar);
3888: } /* End age */
3889:
3890: free_vector(xp,1,npar);
3891: free_matrix(doldm,1,nlstate,1,npar);
3892: free_matrix(dnewm,1,nlstate,1,nlstate);
3893:
3894: }
3895:
3896: /************ Variance of one-step probabilities ******************/
3897: 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[])
3898: {
3899: int i, j=0, k1, l1, tj;
3900: int k2, l2, j1, z1;
3901: int k=0, l;
3902: int first=1, first1, first2;
3903: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3904: double **dnewm,**doldm;
3905: double *xp;
3906: double *gp, *gm;
3907: double **gradg, **trgradg;
3908: double **mu;
3909: double age, cov[NCOVMAX+1];
3910: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3911: int theta;
3912: char fileresprob[FILENAMELENGTH];
3913: char fileresprobcov[FILENAMELENGTH];
3914: char fileresprobcor[FILENAMELENGTH];
3915: double ***varpij;
3916:
3917: strcpy(fileresprob,"prob");
3918: strcat(fileresprob,fileres);
3919: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3920: printf("Problem with resultfile: %s\n", fileresprob);
3921: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3922: }
3923: strcpy(fileresprobcov,"probcov");
3924: strcat(fileresprobcov,fileres);
3925: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3926: printf("Problem with resultfile: %s\n", fileresprobcov);
3927: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3928: }
3929: strcpy(fileresprobcor,"probcor");
3930: strcat(fileresprobcor,fileres);
3931: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3932: printf("Problem with resultfile: %s\n", fileresprobcor);
3933: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3934: }
3935: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3936: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3937: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3938: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3939: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3940: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3941: pstamp(ficresprob);
3942: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3943: fprintf(ficresprob,"# Age");
3944: pstamp(ficresprobcov);
3945: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3946: fprintf(ficresprobcov,"# Age");
3947: pstamp(ficresprobcor);
3948: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3949: fprintf(ficresprobcor,"# Age");
3950:
3951:
3952: for(i=1; i<=nlstate;i++)
3953: for(j=1; j<=(nlstate+ndeath);j++){
3954: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3955: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3956: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3957: }
3958: /* fprintf(ficresprob,"\n");
3959: fprintf(ficresprobcov,"\n");
3960: fprintf(ficresprobcor,"\n");
3961: */
3962: xp=vector(1,npar);
3963: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3964: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3965: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3966: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3967: first=1;
3968: fprintf(ficgp,"\n# Routine varprob");
3969: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3970: fprintf(fichtm,"\n");
3971:
3972: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3973: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3974: file %s<br>\n",optionfilehtmcov);
3975: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3976: and drawn. It helps understanding how is the covariance between two incidences.\
3977: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3978: 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. \
3979: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3980: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3981: standard deviations wide on each axis. <br>\
3982: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3983: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3984: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3985:
3986: cov[1]=1;
3987: /* tj=cptcoveff; */
3988: tj = (int) pow(2,cptcoveff);
3989: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3990: j1=0;
3991: for(j1=1; j1<=tj;j1++){
3992: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3993: /*j1++;*/
3994: if (cptcovn>0) {
3995: fprintf(ficresprob, "\n#********** Variable ");
3996: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3997: fprintf(ficresprob, "**********\n#\n");
3998: fprintf(ficresprobcov, "\n#********** Variable ");
3999: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4000: fprintf(ficresprobcov, "**********\n#\n");
4001:
4002: fprintf(ficgp, "\n#********** Variable ");
4003: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4004: fprintf(ficgp, "**********\n#\n");
4005:
4006:
4007: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4008: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4009: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4010:
4011: fprintf(ficresprobcor, "\n#********** Variable ");
4012: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4013: fprintf(ficresprobcor, "**********\n#");
4014: }
4015:
4016: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4017: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4018: gp=vector(1,(nlstate)*(nlstate+ndeath));
4019: gm=vector(1,(nlstate)*(nlstate+ndeath));
4020: for (age=bage; age<=fage; age ++){
4021: cov[2]=age;
4022: for (k=1; k<=cptcovn;k++) {
4023: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
4024: * 1 1 1 1 1
4025: * 2 2 1 1 1
4026: * 3 1 2 1 1
4027: */
4028: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4029: }
4030: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
4031: for (k=1; k<=cptcovprod;k++)
4032: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
4033:
4034:
4035: for(theta=1; theta <=npar; theta++){
4036: for(i=1; i<=npar; i++)
4037: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4038:
4039: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4040:
4041: k=0;
4042: for(i=1; i<= (nlstate); i++){
4043: for(j=1; j<=(nlstate+ndeath);j++){
4044: k=k+1;
4045: gp[k]=pmmij[i][j];
4046: }
4047: }
4048:
4049: for(i=1; i<=npar; i++)
4050: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4051:
4052: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4053: k=0;
4054: for(i=1; i<=(nlstate); i++){
4055: for(j=1; j<=(nlstate+ndeath);j++){
4056: k=k+1;
4057: gm[k]=pmmij[i][j];
4058: }
4059: }
4060:
4061: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4062: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4063: }
4064:
4065: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4066: for(theta=1; theta <=npar; theta++)
4067: trgradg[j][theta]=gradg[theta][j];
4068:
4069: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4070: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4071:
4072: pmij(pmmij,cov,ncovmodel,x,nlstate);
4073:
4074: k=0;
4075: for(i=1; i<=(nlstate); i++){
4076: for(j=1; j<=(nlstate+ndeath);j++){
4077: k=k+1;
4078: mu[k][(int) age]=pmmij[i][j];
4079: }
4080: }
4081: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4082: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4083: varpij[i][j][(int)age] = doldm[i][j];
4084:
4085: /*printf("\n%d ",(int)age);
4086: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4087: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4088: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4089: }*/
4090:
4091: fprintf(ficresprob,"\n%d ",(int)age);
4092: fprintf(ficresprobcov,"\n%d ",(int)age);
4093: fprintf(ficresprobcor,"\n%d ",(int)age);
4094:
4095: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4096: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4097: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4098: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4099: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4100: }
4101: i=0;
4102: for (k=1; k<=(nlstate);k++){
4103: for (l=1; l<=(nlstate+ndeath);l++){
4104: i++;
4105: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4106: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4107: for (j=1; j<=i;j++){
4108: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4109: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4110: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4111: }
4112: }
4113: }/* end of loop for state */
4114: } /* end of loop for age */
4115: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4116: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4117: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4118: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4119:
4120: /* Confidence intervalle of pij */
4121: /*
4122: fprintf(ficgp,"\nunset parametric;unset label");
4123: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4124: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4125: 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);
4126: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4127: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4128: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4129: */
4130:
4131: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4132: first1=1;first2=2;
4133: for (k2=1; k2<=(nlstate);k2++){
4134: for (l2=1; l2<=(nlstate+ndeath);l2++){
4135: if(l2==k2) continue;
4136: j=(k2-1)*(nlstate+ndeath)+l2;
4137: for (k1=1; k1<=(nlstate);k1++){
4138: for (l1=1; l1<=(nlstate+ndeath);l1++){
4139: if(l1==k1) continue;
4140: i=(k1-1)*(nlstate+ndeath)+l1;
4141: if(i<=j) continue;
4142: for (age=bage; age<=fage; age ++){
4143: if ((int)age %5==0){
4144: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4145: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4146: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4147: mu1=mu[i][(int) age]/stepm*YEARM ;
4148: mu2=mu[j][(int) age]/stepm*YEARM;
4149: c12=cv12/sqrt(v1*v2);
4150: /* Computing eigen value of matrix of covariance */
4151: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4152: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4153: if ((lc2 <0) || (lc1 <0) ){
4154: if(first2==1){
4155: first1=0;
4156: 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);
4157: }
4158: 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);
4159: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4160: /* lc2=fabs(lc2); */
4161: }
4162:
4163: /* Eigen vectors */
4164: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4165: /*v21=sqrt(1.-v11*v11); *//* error */
4166: v21=(lc1-v1)/cv12*v11;
4167: v12=-v21;
4168: v22=v11;
4169: tnalp=v21/v11;
4170: if(first1==1){
4171: first1=0;
4172: 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);
4173: }
4174: 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);
4175: /*printf(fignu*/
4176: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4177: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4178: if(first==1){
4179: first=0;
4180: fprintf(ficgp,"\nset parametric;unset label");
4181: 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);
4182: fprintf(ficgp,"\nset ter png small size 320, 240");
4183: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4184: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4185: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4186: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4187: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4188: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4189: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4190: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4191: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4192: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4193: 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",\
4194: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4195: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4196: }else{
4197: first=0;
4198: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4199: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4200: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4201: 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",\
4202: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4203: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4204: }/* if first */
4205: } /* age mod 5 */
4206: } /* end loop age */
4207: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4208: first=1;
4209: } /*l12 */
4210: } /* k12 */
4211: } /*l1 */
4212: }/* k1 */
4213: /* } */ /* loop covariates */
4214: }
4215: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4216: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4217: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4218: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4219: free_vector(xp,1,npar);
4220: fclose(ficresprob);
4221: fclose(ficresprobcov);
4222: fclose(ficresprobcor);
4223: fflush(ficgp);
4224: fflush(fichtmcov);
4225: }
4226:
4227:
4228: /******************* Printing html file ***********/
4229: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4230: int lastpass, int stepm, int weightopt, char model[],\
4231: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4232: int popforecast, int estepm ,\
4233: double jprev1, double mprev1,double anprev1, \
4234: double jprev2, double mprev2,double anprev2){
4235: int jj1, k1, i1, cpt;
4236:
4237: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4238: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4239: </ul>");
4240: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4241: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4242: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4243: fprintf(fichtm,"\
4244: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4245: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4246: fprintf(fichtm,"\
4247: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4248: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4249: fprintf(fichtm,"\
4250: - (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): \
4251: <a href=\"%s\">%s</a> <br>\n",
4252: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4253: fprintf(fichtm,"\
4254: - Population projections by age and states: \
4255: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4256:
4257: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4258:
4259: m=pow(2,cptcoveff);
4260: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4261:
4262: jj1=0;
4263: for(k1=1; k1<=m;k1++){
4264: for(i1=1; i1<=ncodemax[k1];i1++){
4265: jj1++;
4266: if (cptcovn > 0) {
4267: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4268: for (cpt=1; cpt<=cptcoveff;cpt++)
4269: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4270: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4271: }
4272: /* Pij */
4273: 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> \
4274: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4275: /* Quasi-incidences */
4276: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4277: 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> \
4278: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4279: /* Period (stable) prevalence in each health state */
4280: for(cpt=1; cpt<=nlstate;cpt++){
4281: 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> \
4282: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4283: }
4284: for(cpt=1; cpt<=nlstate;cpt++) {
4285: 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> \
4286: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4287: }
4288: } /* end i1 */
4289: }/* End k1 */
4290: fprintf(fichtm,"</ul>");
4291:
4292:
4293: fprintf(fichtm,"\
4294: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4295: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4296:
4297: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4298: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4299: fprintf(fichtm,"\
4300: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4301: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4302:
4303: fprintf(fichtm,"\
4304: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4305: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4306: fprintf(fichtm,"\
4307: - 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): \
4308: <a href=\"%s\">%s</a> <br>\n</li>",
4309: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4310: fprintf(fichtm,"\
4311: - (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): \
4312: <a href=\"%s\">%s</a> <br>\n</li>",
4313: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4314: fprintf(fichtm,"\
4315: - 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",
4316: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4317: fprintf(fichtm,"\
4318: - 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",
4319: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4320: fprintf(fichtm,"\
4321: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4322: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4323:
4324: /* if(popforecast==1) fprintf(fichtm,"\n */
4325: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4326: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4327: /* <br>",fileres,fileres,fileres,fileres); */
4328: /* else */
4329: /* 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); */
4330: fflush(fichtm);
4331: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4332:
4333: m=pow(2,cptcoveff);
4334: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4335:
4336: jj1=0;
4337: for(k1=1; k1<=m;k1++){
4338: for(i1=1; i1<=ncodemax[k1];i1++){
4339: jj1++;
4340: if (cptcovn > 0) {
4341: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4342: for (cpt=1; cpt<=cptcoveff;cpt++)
4343: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4344: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4345: }
4346: for(cpt=1; cpt<=nlstate;cpt++) {
4347: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4348: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4349: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4350: }
4351: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4352: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4353: true period expectancies (those weighted with period prevalences are also\
4354: drawn in addition to the population based expectancies computed using\
4355: observed and cahotic prevalences: %s%d.png<br>\
4356: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4357: } /* end i1 */
4358: }/* End k1 */
4359: fprintf(fichtm,"</ul>");
4360: fflush(fichtm);
4361: }
4362:
4363: /******************* Gnuplot file **************/
4364: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4365:
4366: char dirfileres[132],optfileres[132];
4367: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4368: int ng=0;
4369: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4370: /* printf("Problem with file %s",optionfilegnuplot); */
4371: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4372: /* } */
4373:
4374: /*#ifdef windows */
4375: fprintf(ficgp,"cd \"%s\" \n",pathc);
4376: /*#endif */
4377: m=pow(2,cptcoveff);
4378:
4379: strcpy(dirfileres,optionfilefiname);
4380: strcpy(optfileres,"vpl");
4381: /* 1eme*/
4382: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4383: for (cpt=1; cpt<= nlstate ; cpt ++) {
4384: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4385: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4386: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4387: fprintf(ficgp,"set xlabel \"Age\" \n\
4388: set ylabel \"Probability\" \n\
4389: set ter png small size 320, 240\n\
4390: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4391:
4392: for (i=1; i<= nlstate ; i ++) {
4393: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4394: else fprintf(ficgp," %%*lf (%%*lf)");
4395: }
4396: 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);
4397: for (i=1; i<= nlstate ; i ++) {
4398: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4399: else fprintf(ficgp," %%*lf (%%*lf)");
4400: }
4401: 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);
4402: for (i=1; i<= nlstate ; i ++) {
4403: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4404: else fprintf(ficgp," %%*lf (%%*lf)");
4405: }
4406: 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));
4407: }
4408: }
4409: /*2 eme*/
4410: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4411: for (k1=1; k1<= m ; k1 ++) {
4412: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4413: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4414:
4415: for (i=1; i<= nlstate+1 ; i ++) {
4416: k=2*i;
4417: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4418: for (j=1; j<= nlstate+1 ; j ++) {
4419: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4420: else fprintf(ficgp," %%*lf (%%*lf)");
4421: }
4422: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4423: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4424: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4425: for (j=1; j<= nlstate+1 ; j ++) {
4426: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4427: else fprintf(ficgp," %%*lf (%%*lf)");
4428: }
4429: fprintf(ficgp,"\" t\"\" w l lt 0,");
4430: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4431: for (j=1; j<= nlstate+1 ; j ++) {
4432: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4433: else fprintf(ficgp," %%*lf (%%*lf)");
4434: }
4435: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4436: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4437: }
4438: }
4439:
4440: /*3eme*/
4441:
4442: for (k1=1; k1<= m ; k1 ++) {
4443: for (cpt=1; cpt<= nlstate ; cpt ++) {
4444: /* k=2+nlstate*(2*cpt-2); */
4445: k=2+(nlstate+1)*(cpt-1);
4446: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4447: fprintf(ficgp,"set ter png small size 320, 240\n\
4448: 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);
4449: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4450: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4451: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4452: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4453: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4454: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4455:
4456: */
4457: for (i=1; i< nlstate ; i ++) {
4458: 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);
4459: /* 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);*/
4460:
4461: }
4462: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4463: }
4464: }
4465:
4466: /* CV preval stable (period) */
4467: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4468: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4469: k=3;
4470: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4471: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4472: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4473: set ter png small size 320, 240\n\
4474: unset log y\n\
4475: plot [%.f:%.f] ", ageminpar, agemaxpar);
4476: for (i=1; i<= nlstate ; i ++){
4477: if(i==1)
4478: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4479: else
4480: fprintf(ficgp,", '' ");
4481: l=(nlstate+ndeath)*(i-1)+1;
4482: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4483: for (j=1; j<= (nlstate-1) ; j ++)
4484: fprintf(ficgp,"+$%d",k+l+j);
4485: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4486: } /* nlstate */
4487: fprintf(ficgp,"\n");
4488: } /* end cpt state*/
4489: } /* end covariate */
4490:
4491: /* proba elementaires */
4492: for(i=1,jk=1; i <=nlstate; i++){
4493: for(k=1; k <=(nlstate+ndeath); k++){
4494: if (k != i) {
4495: for(j=1; j <=ncovmodel; j++){
4496: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4497: jk++;
4498: fprintf(ficgp,"\n");
4499: }
4500: }
4501: }
4502: }
4503: /*goto avoid;*/
4504: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4505: for(jk=1; jk <=m; jk++) {
4506: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4507: if (ng==2)
4508: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4509: else
4510: fprintf(ficgp,"\nset title \"Probability\"\n");
4511: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4512: i=1;
4513: for(k2=1; k2<=nlstate; k2++) {
4514: k3=i;
4515: for(k=1; k<=(nlstate+ndeath); k++) {
4516: if (k != k2){
4517: if(ng==2)
4518: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4519: else
4520: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4521: ij=1;/* To be checked else nbcode[0][0] wrong */
4522: for(j=3; j <=ncovmodel; j++) {
4523: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4524: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4525: /* ij++; */
4526: /* } */
4527: /* else */
4528: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4529: }
4530: fprintf(ficgp,")/(1");
4531:
4532: for(k1=1; k1 <=nlstate; k1++){
4533: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4534: ij=1;
4535: for(j=3; j <=ncovmodel; j++){
4536: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4537: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4538: /* ij++; */
4539: /* } */
4540: /* else */
4541: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4542: }
4543: fprintf(ficgp,")");
4544: }
4545: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4546: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4547: i=i+ncovmodel;
4548: }
4549: } /* end k */
4550: } /* end k2 */
4551: } /* end jk */
4552: } /* end ng */
4553: /* avoid: */
4554: fflush(ficgp);
4555: } /* end gnuplot */
4556:
4557:
4558: /*************** Moving average **************/
4559: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4560:
4561: int i, cpt, cptcod;
4562: int modcovmax =1;
4563: int mobilavrange, mob;
4564: double age;
4565:
4566: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4567: a covariate has 2 modalities */
4568: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4569:
4570: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4571: if(mobilav==1) mobilavrange=5; /* default */
4572: else mobilavrange=mobilav;
4573: for (age=bage; age<=fage; age++)
4574: for (i=1; i<=nlstate;i++)
4575: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4576: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4577: /* We keep the original values on the extreme ages bage, fage and for
4578: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4579: we use a 5 terms etc. until the borders are no more concerned.
4580: */
4581: for (mob=3;mob <=mobilavrange;mob=mob+2){
4582: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4583: for (i=1; i<=nlstate;i++){
4584: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4585: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4586: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4587: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4588: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4589: }
4590: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4591: }
4592: }
4593: }/* end age */
4594: }/* end mob */
4595: }else return -1;
4596: return 0;
4597: }/* End movingaverage */
4598:
4599:
4600: /************** Forecasting ******************/
4601: 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){
4602: /* proj1, year, month, day of starting projection
4603: agemin, agemax range of age
4604: dateprev1 dateprev2 range of dates during which prevalence is computed
4605: anproj2 year of en of projection (same day and month as proj1).
4606: */
4607: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4608: double agec; /* generic age */
4609: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4610: double *popeffectif,*popcount;
4611: double ***p3mat;
4612: double ***mobaverage;
4613: char fileresf[FILENAMELENGTH];
4614:
4615: agelim=AGESUP;
4616: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4617:
4618: strcpy(fileresf,"f");
4619: strcat(fileresf,fileres);
4620: if((ficresf=fopen(fileresf,"w"))==NULL) {
4621: printf("Problem with forecast resultfile: %s\n", fileresf);
4622: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4623: }
4624: printf("Computing forecasting: result on file '%s' \n", fileresf);
4625: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4626:
4627: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4628:
4629: if (mobilav!=0) {
4630: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4631: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4632: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4633: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4634: }
4635: }
4636:
4637: stepsize=(int) (stepm+YEARM-1)/YEARM;
4638: if (stepm<=12) stepsize=1;
4639: if(estepm < stepm){
4640: printf ("Problem %d lower than %d\n",estepm, stepm);
4641: }
4642: else hstepm=estepm;
4643:
4644: hstepm=hstepm/stepm;
4645: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4646: fractional in yp1 */
4647: anprojmean=yp;
4648: yp2=modf((yp1*12),&yp);
4649: mprojmean=yp;
4650: yp1=modf((yp2*30.5),&yp);
4651: jprojmean=yp;
4652: if(jprojmean==0) jprojmean=1;
4653: if(mprojmean==0) jprojmean=1;
4654:
4655: i1=cptcoveff;
4656: if (cptcovn < 1){i1=1;}
4657:
4658: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4659:
4660: fprintf(ficresf,"#****** Routine prevforecast **\n");
4661:
4662: /* if (h==(int)(YEARM*yearp)){ */
4663: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4664: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4665: k=k+1;
4666: fprintf(ficresf,"\n#******");
4667: for(j=1;j<=cptcoveff;j++) {
4668: 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]]);
4669: }
4670: fprintf(ficresf,"******\n");
4671: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4672: for(j=1; j<=nlstate+ndeath;j++){
4673: for(i=1; i<=nlstate;i++)
4674: fprintf(ficresf," p%d%d",i,j);
4675: fprintf(ficresf," p.%d",j);
4676: }
4677: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4678: fprintf(ficresf,"\n");
4679: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4680:
4681: for (agec=fage; agec>=(ageminpar-1); agec--){
4682: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4683: nhstepm = nhstepm/hstepm;
4684: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4685: oldm=oldms;savm=savms;
4686: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4687:
4688: for (h=0; h<=nhstepm; h++){
4689: if (h*hstepm/YEARM*stepm ==yearp) {
4690: fprintf(ficresf,"\n");
4691: for(j=1;j<=cptcoveff;j++)
4692: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4693: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4694: }
4695: for(j=1; j<=nlstate+ndeath;j++) {
4696: ppij=0.;
4697: for(i=1; i<=nlstate;i++) {
4698: if (mobilav==1)
4699: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4700: else {
4701: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4702: }
4703: if (h*hstepm/YEARM*stepm== yearp) {
4704: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4705: }
4706: } /* end i */
4707: if (h*hstepm/YEARM*stepm==yearp) {
4708: fprintf(ficresf," %.3f", ppij);
4709: }
4710: }/* end j */
4711: } /* end h */
4712: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4713: } /* end agec */
4714: } /* end yearp */
4715: } /* end cptcod */
4716: } /* end cptcov */
4717:
4718: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4719:
4720: fclose(ficresf);
4721: }
4722:
4723: /************** Forecasting *****not tested NB*************/
4724: 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){
4725:
4726: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4727: int *popage;
4728: double calagedatem, agelim, kk1, kk2;
4729: double *popeffectif,*popcount;
4730: double ***p3mat,***tabpop,***tabpopprev;
4731: double ***mobaverage;
4732: char filerespop[FILENAMELENGTH];
4733:
4734: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4735: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4736: agelim=AGESUP;
4737: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4738:
4739: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4740:
4741:
4742: strcpy(filerespop,"pop");
4743: strcat(filerespop,fileres);
4744: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4745: printf("Problem with forecast resultfile: %s\n", filerespop);
4746: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4747: }
4748: printf("Computing forecasting: result on file '%s' \n", filerespop);
4749: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4750:
4751: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4752:
4753: if (mobilav!=0) {
4754: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4755: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4756: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4757: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4758: }
4759: }
4760:
4761: stepsize=(int) (stepm+YEARM-1)/YEARM;
4762: if (stepm<=12) stepsize=1;
4763:
4764: agelim=AGESUP;
4765:
4766: hstepm=1;
4767: hstepm=hstepm/stepm;
4768:
4769: if (popforecast==1) {
4770: if((ficpop=fopen(popfile,"r"))==NULL) {
4771: printf("Problem with population file : %s\n",popfile);exit(0);
4772: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4773: }
4774: popage=ivector(0,AGESUP);
4775: popeffectif=vector(0,AGESUP);
4776: popcount=vector(0,AGESUP);
4777:
4778: i=1;
4779: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4780:
4781: imx=i;
4782: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4783: }
4784:
4785: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4786: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4787: k=k+1;
4788: fprintf(ficrespop,"\n#******");
4789: for(j=1;j<=cptcoveff;j++) {
4790: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4791: }
4792: fprintf(ficrespop,"******\n");
4793: fprintf(ficrespop,"# Age");
4794: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4795: if (popforecast==1) fprintf(ficrespop," [Population]");
4796:
4797: for (cpt=0; cpt<=0;cpt++) {
4798: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4799:
4800: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4801: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4802: nhstepm = nhstepm/hstepm;
4803:
4804: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4805: oldm=oldms;savm=savms;
4806: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4807:
4808: for (h=0; h<=nhstepm; h++){
4809: if (h==(int) (calagedatem+YEARM*cpt)) {
4810: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4811: }
4812: for(j=1; j<=nlstate+ndeath;j++) {
4813: kk1=0.;kk2=0;
4814: for(i=1; i<=nlstate;i++) {
4815: if (mobilav==1)
4816: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4817: else {
4818: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4819: }
4820: }
4821: if (h==(int)(calagedatem+12*cpt)){
4822: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4823: /*fprintf(ficrespop," %.3f", kk1);
4824: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4825: }
4826: }
4827: for(i=1; i<=nlstate;i++){
4828: kk1=0.;
4829: for(j=1; j<=nlstate;j++){
4830: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4831: }
4832: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4833: }
4834:
4835: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4836: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4837: }
4838: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4839: }
4840: }
4841:
4842: /******/
4843:
4844: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4845: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4846: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4847: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4848: nhstepm = nhstepm/hstepm;
4849:
4850: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4851: oldm=oldms;savm=savms;
4852: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4853: for (h=0; h<=nhstepm; h++){
4854: if (h==(int) (calagedatem+YEARM*cpt)) {
4855: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4856: }
4857: for(j=1; j<=nlstate+ndeath;j++) {
4858: kk1=0.;kk2=0;
4859: for(i=1; i<=nlstate;i++) {
4860: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4861: }
4862: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4863: }
4864: }
4865: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4866: }
4867: }
4868: }
4869: }
4870:
4871: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4872:
4873: if (popforecast==1) {
4874: free_ivector(popage,0,AGESUP);
4875: free_vector(popeffectif,0,AGESUP);
4876: free_vector(popcount,0,AGESUP);
4877: }
4878: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4879: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4880: fclose(ficrespop);
4881: } /* End of popforecast */
4882:
4883: int fileappend(FILE *fichier, char *optionfich)
4884: {
4885: if((fichier=fopen(optionfich,"a"))==NULL) {
4886: printf("Problem with file: %s\n", optionfich);
4887: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4888: return (0);
4889: }
4890: fflush(fichier);
4891: return (1);
4892: }
4893:
4894:
4895: /**************** function prwizard **********************/
4896: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4897: {
4898:
4899: /* Wizard to print covariance matrix template */
4900:
4901: char ca[32], cb[32];
4902: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4903: int numlinepar;
4904:
4905: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4906: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4907: for(i=1; i <=nlstate; i++){
4908: jj=0;
4909: for(j=1; j <=nlstate+ndeath; j++){
4910: if(j==i) continue;
4911: jj++;
4912: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4913: printf("%1d%1d",i,j);
4914: fprintf(ficparo,"%1d%1d",i,j);
4915: for(k=1; k<=ncovmodel;k++){
4916: /* printf(" %lf",param[i][j][k]); */
4917: /* fprintf(ficparo," %lf",param[i][j][k]); */
4918: printf(" 0.");
4919: fprintf(ficparo," 0.");
4920: }
4921: printf("\n");
4922: fprintf(ficparo,"\n");
4923: }
4924: }
4925: printf("# Scales (for hessian or gradient estimation)\n");
4926: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4927: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4928: for(i=1; i <=nlstate; i++){
4929: jj=0;
4930: for(j=1; j <=nlstate+ndeath; j++){
4931: if(j==i) continue;
4932: jj++;
4933: fprintf(ficparo,"%1d%1d",i,j);
4934: printf("%1d%1d",i,j);
4935: fflush(stdout);
4936: for(k=1; k<=ncovmodel;k++){
4937: /* printf(" %le",delti3[i][j][k]); */
4938: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4939: printf(" 0.");
4940: fprintf(ficparo," 0.");
4941: }
4942: numlinepar++;
4943: printf("\n");
4944: fprintf(ficparo,"\n");
4945: }
4946: }
4947: printf("# Covariance matrix\n");
4948: /* # 121 Var(a12)\n\ */
4949: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4950: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4951: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4952: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4953: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4954: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4955: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4956: fflush(stdout);
4957: fprintf(ficparo,"# Covariance matrix\n");
4958: /* # 121 Var(a12)\n\ */
4959: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4960: /* # ...\n\ */
4961: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4962:
4963: for(itimes=1;itimes<=2;itimes++){
4964: jj=0;
4965: for(i=1; i <=nlstate; i++){
4966: for(j=1; j <=nlstate+ndeath; j++){
4967: if(j==i) continue;
4968: for(k=1; k<=ncovmodel;k++){
4969: jj++;
4970: ca[0]= k+'a'-1;ca[1]='\0';
4971: if(itimes==1){
4972: printf("#%1d%1d%d",i,j,k);
4973: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4974: }else{
4975: printf("%1d%1d%d",i,j,k);
4976: fprintf(ficparo,"%1d%1d%d",i,j,k);
4977: /* printf(" %.5le",matcov[i][j]); */
4978: }
4979: ll=0;
4980: for(li=1;li <=nlstate; li++){
4981: for(lj=1;lj <=nlstate+ndeath; lj++){
4982: if(lj==li) continue;
4983: for(lk=1;lk<=ncovmodel;lk++){
4984: ll++;
4985: if(ll<=jj){
4986: cb[0]= lk +'a'-1;cb[1]='\0';
4987: if(ll<jj){
4988: if(itimes==1){
4989: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4990: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4991: }else{
4992: printf(" 0.");
4993: fprintf(ficparo," 0.");
4994: }
4995: }else{
4996: if(itimes==1){
4997: printf(" Var(%s%1d%1d)",ca,i,j);
4998: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4999: }else{
5000: printf(" 0.");
5001: fprintf(ficparo," 0.");
5002: }
5003: }
5004: }
5005: } /* end lk */
5006: } /* end lj */
5007: } /* end li */
5008: printf("\n");
5009: fprintf(ficparo,"\n");
5010: numlinepar++;
5011: } /* end k*/
5012: } /*end j */
5013: } /* end i */
5014: } /* end itimes */
5015:
5016: } /* end of prwizard */
5017: /******************* Gompertz Likelihood ******************************/
5018: double gompertz(double x[])
5019: {
5020: double A,B,L=0.0,sump=0.,num=0.;
5021: int i,n=0; /* n is the size of the sample */
5022:
5023: for (i=0;i<=imx-1 ; i++) {
5024: sump=sump+weight[i];
5025: /* sump=sump+1;*/
5026: num=num+1;
5027: }
5028:
5029:
5030: /* for (i=0; i<=imx; i++)
5031: 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]);*/
5032:
5033: for (i=1;i<=imx ; i++)
5034: {
5035: if (cens[i] == 1 && wav[i]>1)
5036: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5037:
5038: if (cens[i] == 0 && wav[i]>1)
5039: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5040: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5041:
5042: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5043: if (wav[i] > 1 ) { /* ??? */
5044: L=L+A*weight[i];
5045: /* 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]);*/
5046: }
5047: }
5048:
5049: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5050:
5051: return -2*L*num/sump;
5052: }
5053:
5054: #ifdef GSL
5055: /******************* Gompertz_f Likelihood ******************************/
5056: double gompertz_f(const gsl_vector *v, void *params)
5057: {
5058: double A,B,LL=0.0,sump=0.,num=0.;
5059: double *x= (double *) v->data;
5060: int i,n=0; /* n is the size of the sample */
5061:
5062: for (i=0;i<=imx-1 ; i++) {
5063: sump=sump+weight[i];
5064: /* sump=sump+1;*/
5065: num=num+1;
5066: }
5067:
5068:
5069: /* for (i=0; i<=imx; i++)
5070: 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]);*/
5071: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5072: for (i=1;i<=imx ; i++)
5073: {
5074: if (cens[i] == 1 && wav[i]>1)
5075: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5076:
5077: if (cens[i] == 0 && wav[i]>1)
5078: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5079: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5080:
5081: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5082: if (wav[i] > 1 ) { /* ??? */
5083: LL=LL+A*weight[i];
5084: /* 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]);*/
5085: }
5086: }
5087:
5088: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5089: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5090:
5091: return -2*LL*num/sump;
5092: }
5093: #endif
5094:
5095: /******************* Printing html file ***********/
5096: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5097: int lastpass, int stepm, int weightopt, char model[],\
5098: int imx, double p[],double **matcov,double agemortsup){
5099: int i,k;
5100:
5101: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5102: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5103: for (i=1;i<=2;i++)
5104: 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]));
5105: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5106: fprintf(fichtm,"</ul>");
5107:
5108: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5109:
5110: 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>");
5111:
5112: for (k=agegomp;k<(agemortsup-2);k++)
5113: 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]);
5114:
5115:
5116: fflush(fichtm);
5117: }
5118:
5119: /******************* Gnuplot file **************/
5120: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5121:
5122: char dirfileres[132],optfileres[132];
5123:
5124: int ng;
5125:
5126:
5127: /*#ifdef windows */
5128: fprintf(ficgp,"cd \"%s\" \n",pathc);
5129: /*#endif */
5130:
5131:
5132: strcpy(dirfileres,optionfilefiname);
5133: strcpy(optfileres,"vpl");
5134: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5135: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5136: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5137: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5138: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5139:
5140: }
5141:
5142: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5143: {
5144:
5145: /*-------- data file ----------*/
5146: FILE *fic;
5147: char dummy[]=" ";
5148: int i=0, j=0, n=0;
5149: int linei, month, year,iout;
5150: char line[MAXLINE], linetmp[MAXLINE];
5151: char stra[MAXLINE], strb[MAXLINE];
5152: char *stratrunc;
5153: int lstra;
5154:
5155:
5156: if((fic=fopen(datafile,"r"))==NULL) {
5157: printf("Problem while opening datafile: %s\n", datafile);return 1;
5158: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5159: }
5160:
5161: i=1;
5162: linei=0;
5163: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5164: linei=linei+1;
5165: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5166: if(line[j] == '\t')
5167: line[j] = ' ';
5168: }
5169: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5170: ;
5171: };
5172: line[j+1]=0; /* Trims blanks at end of line */
5173: if(line[0]=='#'){
5174: fprintf(ficlog,"Comment line\n%s\n",line);
5175: printf("Comment line\n%s\n",line);
5176: continue;
5177: }
5178: trimbb(linetmp,line); /* Trims multiple blanks in line */
5179: strcpy(line, linetmp);
5180:
5181:
5182: for (j=maxwav;j>=1;j--){
5183: cutv(stra, strb, line, ' ');
5184: if(strb[0]=='.') { /* Missing status */
5185: lval=-1;
5186: }else{
5187: errno=0;
5188: lval=strtol(strb,&endptr,10);
5189: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5190: if( strb[0]=='\0' || (*endptr != '\0')){
5191: 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);
5192: 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);
5193: return 1;
5194: }
5195: }
5196: s[j][i]=lval;
5197:
5198: strcpy(line,stra);
5199: cutv(stra, strb,line,' ');
5200: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5201: }
5202: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5203: month=99;
5204: year=9999;
5205: }else{
5206: 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);
5207: 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);
5208: return 1;
5209: }
5210: anint[j][i]= (double) year;
5211: mint[j][i]= (double)month;
5212: strcpy(line,stra);
5213: } /* ENd Waves */
5214:
5215: cutv(stra, strb,line,' ');
5216: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5217: }
5218: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5219: month=99;
5220: year=9999;
5221: }else{
5222: 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);
5223: 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);
5224: return 1;
5225: }
5226: andc[i]=(double) year;
5227: moisdc[i]=(double) month;
5228: strcpy(line,stra);
5229:
5230: cutv(stra, strb,line,' ');
5231: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5232: }
5233: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5234: month=99;
5235: year=9999;
5236: }else{
5237: 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);
5238: 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);
5239: return 1;
5240: }
5241: if (year==9999) {
5242: 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);
5243: 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);
5244: return 1;
5245:
5246: }
5247: annais[i]=(double)(year);
5248: moisnais[i]=(double)(month);
5249: strcpy(line,stra);
5250:
5251: cutv(stra, strb,line,' ');
5252: errno=0;
5253: dval=strtod(strb,&endptr);
5254: if( strb[0]=='\0' || (*endptr != '\0')){
5255: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5256: 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);
5257: fflush(ficlog);
5258: return 1;
5259: }
5260: weight[i]=dval;
5261: strcpy(line,stra);
5262:
5263: for (j=ncovcol;j>=1;j--){
5264: cutv(stra, strb,line,' ');
5265: if(strb[0]=='.') { /* Missing status */
5266: lval=-1;
5267: }else{
5268: errno=0;
5269: lval=strtol(strb,&endptr,10);
5270: if( strb[0]=='\0' || (*endptr != '\0')){
5271: 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);
5272: 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);
5273: return 1;
5274: }
5275: }
5276: if(lval <-1 || lval >1){
5277: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5278: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5279: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5280: For example, for multinomial values like 1, 2 and 3,\n \
5281: build V1=0 V2=0 for the reference value (1),\n \
5282: V1=1 V2=0 for (2) \n \
5283: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5284: output of IMaCh is often meaningless.\n \
5285: Exiting.\n",lval,linei, i,line,j);
5286: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5287: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5288: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5289: For example, for multinomial values like 1, 2 and 3,\n \
5290: build V1=0 V2=0 for the reference value (1),\n \
5291: V1=1 V2=0 for (2) \n \
5292: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5293: output of IMaCh is often meaningless.\n \
5294: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5295: return 1;
5296: }
5297: covar[j][i]=(double)(lval);
5298: strcpy(line,stra);
5299: }
5300: lstra=strlen(stra);
5301:
5302: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5303: stratrunc = &(stra[lstra-9]);
5304: num[i]=atol(stratrunc);
5305: }
5306: else
5307: num[i]=atol(stra);
5308: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5309: 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;}*/
5310:
5311: i=i+1;
5312: } /* End loop reading data */
5313:
5314: *imax=i-1; /* Number of individuals */
5315: fclose(fic);
5316:
5317: return (0);
5318: /* endread: */
5319: printf("Exiting readdata: ");
5320: fclose(fic);
5321: return (1);
5322:
5323:
5324:
5325: }
5326: void removespace(char *str) {
5327: char *p1 = str, *p2 = str;
5328: do
5329: while (*p2 == ' ')
5330: p2++;
5331: while (*p1++ == *p2++);
5332: }
5333:
5334: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5335: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5336: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5337: * - cptcovn or number of covariates k of the models excluding age*products =6
5338: * - cptcovage number of covariates with age*products =2
5339: * - cptcovs number of simple covariates
5340: * - 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
5341: * which is a new column after the 9 (ncovcol) variables.
5342: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5343: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5344: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5345: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5346: */
5347: {
5348: int i, j, k, ks;
5349: int j1, k1, k2;
5350: char modelsav[80];
5351: char stra[80], strb[80], strc[80], strd[80],stre[80];
5352:
5353: /*removespace(model);*/
5354: if (strlen(model) >1){ /* If there is at least 1 covariate */
5355: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5356: j=nbocc(model,'+'); /**< j=Number of '+' */
5357: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5358: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5359: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5360: /* including age products which are counted in cptcovage.
5361: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5362: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5363: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5364: strcpy(modelsav,model);
5365: if (strstr(model,"AGE") !=0){
5366: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5367: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5368: return 1;
5369: }
5370: if (strstr(model,"v") !=0){
5371: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5372: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5373: return 1;
5374: }
5375:
5376: /* Design
5377: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5378: * < ncovcol=8 >
5379: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5380: * k= 1 2 3 4 5 6 7 8
5381: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5382: * covar[k,i], value of kth covariate if not including age for individual i:
5383: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5384: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5385: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5386: * Tage[++cptcovage]=k
5387: * if products, new covar are created after ncovcol with k1
5388: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5389: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5390: * 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
5391: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5392: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5393: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5394: * < ncovcol=8 >
5395: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5396: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5397: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5398: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5399: * p Tprod[1]@2={ 6, 5}
5400: *p Tvard[1][1]@4= {7, 8, 5, 6}
5401: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5402: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5403: *How to reorganize?
5404: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5405: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5406: * {2, 1, 4, 8, 5, 6, 3, 7}
5407: * Struct []
5408: */
5409:
5410: /* This loop fills the array Tvar from the string 'model'.*/
5411: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5412: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5413: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5414: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5415: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5416: /* k=1 Tvar[1]=2 (from V2) */
5417: /* k=5 Tvar[5] */
5418: /* for (k=1; k<=cptcovn;k++) { */
5419: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5420: /* } */
5421: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5422: /*
5423: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5424: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5425: Tvar[k]=0;
5426: cptcovage=0;
5427: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5428: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5429: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5430: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5431: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5432: /*scanf("%d",i);*/
5433: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5434: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5435: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5436: /* covar is not filled and then is empty */
5437: cptcovprod--;
5438: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5439: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5440: cptcovage++; /* Sums the number of covariates which include age as a product */
5441: Tage[cptcovage]=k; /* Tage[1] = 4 */
5442: /*printf("stre=%s ", stre);*/
5443: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5444: cptcovprod--;
5445: cutl(stre,strb,strc,'V');
5446: Tvar[k]=atoi(stre);
5447: cptcovage++;
5448: Tage[cptcovage]=k;
5449: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5450: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5451: cptcovn++;
5452: cptcovprodnoage++;k1++;
5453: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5454: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5455: because this model-covariate is a construction we invent a new column
5456: ncovcol + k1
5457: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5458: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5459: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5460: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5461: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5462: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5463: k2=k2+2;
5464: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5465: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5466: for (i=1; i<=lastobs;i++){
5467: /* Computes the new covariate which is a product of
5468: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5469: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5470: }
5471: } /* End age is not in the model */
5472: } /* End if model includes a product */
5473: else { /* no more sum */
5474: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5475: /* scanf("%d",i);*/
5476: cutl(strd,strc,strb,'V');
5477: ks++; /**< Number of simple covariates */
5478: cptcovn++;
5479: Tvar[k]=atoi(strd);
5480: }
5481: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5482: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5483: scanf("%d",i);*/
5484: } /* end of loop + */
5485: } /* end model */
5486:
5487: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5488: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5489:
5490: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5491: printf("cptcovprod=%d ", cptcovprod);
5492: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5493:
5494: scanf("%d ",i);*/
5495:
5496:
5497: return (0); /* with covar[new additional covariate if product] and Tage if age */
5498: /*endread:*/
5499: printf("Exiting decodemodel: ");
5500: return (1);
5501: }
5502:
5503: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5504: {
5505: int i, m;
5506:
5507: for (i=1; i<=imx; i++) {
5508: for(m=2; (m<= maxwav); m++) {
5509: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5510: anint[m][i]=9999;
5511: s[m][i]=-1;
5512: }
5513: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5514: *nberr = *nberr + 1;
5515: 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);
5516: 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);
5517: s[m][i]=-1;
5518: }
5519: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5520: (*nberr)++;
5521: 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]);
5522: 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]);
5523: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5524: }
5525: }
5526: }
5527:
5528: for (i=1; i<=imx; i++) {
5529: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5530: for(m=firstpass; (m<= lastpass); m++){
5531: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5532: if (s[m][i] >= nlstate+1) {
5533: if(agedc[i]>0){
5534: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5535: agev[m][i]=agedc[i];
5536: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5537: }else {
5538: if ((int)andc[i]!=9999){
5539: nbwarn++;
5540: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5541: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5542: agev[m][i]=-1;
5543: }
5544: }
5545: } /* agedc > 0 */
5546: }
5547: else if(s[m][i] !=9){ /* Standard case, age in fractional
5548: years but with the precision of a month */
5549: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5550: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5551: agev[m][i]=1;
5552: else if(agev[m][i] < *agemin){
5553: *agemin=agev[m][i];
5554: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5555: }
5556: else if(agev[m][i] >*agemax){
5557: *agemax=agev[m][i];
5558: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5559: }
5560: /*agev[m][i]=anint[m][i]-annais[i];*/
5561: /* agev[m][i] = age[i]+2*m;*/
5562: }
5563: else { /* =9 */
5564: agev[m][i]=1;
5565: s[m][i]=-1;
5566: }
5567: }
5568: else /*= 0 Unknown */
5569: agev[m][i]=1;
5570: }
5571:
5572: }
5573: for (i=1; i<=imx; i++) {
5574: for(m=firstpass; (m<=lastpass); m++){
5575: if (s[m][i] > (nlstate+ndeath)) {
5576: (*nberr)++;
5577: 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);
5578: 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);
5579: return 1;
5580: }
5581: }
5582: }
5583:
5584: /*for (i=1; i<=imx; i++){
5585: for (m=firstpass; (m<lastpass); m++){
5586: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5587: }
5588:
5589: }*/
5590:
5591:
5592: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5593: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5594:
5595: return (0);
5596: /* endread:*/
5597: printf("Exiting calandcheckages: ");
5598: return (1);
5599: }
5600:
5601: #if defined(_MSC_VER)
5602: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5603: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5604: //#include "stdafx.h"
5605: //#include <stdio.h>
5606: //#include <tchar.h>
5607: //#include <windows.h>
5608: //#include <iostream>
5609: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5610:
5611: LPFN_ISWOW64PROCESS fnIsWow64Process;
5612:
5613: BOOL IsWow64()
5614: {
5615: BOOL bIsWow64 = FALSE;
5616:
5617: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5618: // (HANDLE, PBOOL);
5619:
5620: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5621:
5622: HMODULE module = GetModuleHandle(_T("kernel32"));
5623: const char funcName[] = "IsWow64Process";
5624: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5625: GetProcAddress(module, funcName);
5626:
5627: if (NULL != fnIsWow64Process)
5628: {
5629: if (!fnIsWow64Process(GetCurrentProcess(),
5630: &bIsWow64))
5631: //throw std::exception("Unknown error");
5632: printf("Unknown error\n");
5633: }
5634: return bIsWow64 != FALSE;
5635: }
5636: #endif
5637:
5638: void syscompilerinfo()
5639: {
5640: /* #include "syscompilerinfo.h"*/
5641:
5642: #if defined __INTEL_COMPILER
5643: #if defined(__GNUC__)
5644: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5645: #endif
5646: #elif defined(__GNUC__)
5647: #ifndef __APPLE__
5648: #include <gnu/libc-version.h> /* Only on gnu */
5649: #endif
5650: struct utsname sysInfo;
5651: int cross = CROSS;
5652: if (cross){
5653: printf("Cross-");
5654: fprintf(ficlog, "Cross-");
5655: }
5656: #endif
5657:
5658: #include <stdint.h>
5659:
5660: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5661: #if defined(__clang__)
5662: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5663: #endif
5664: #if defined(__ICC) || defined(__INTEL_COMPILER)
5665: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5666: #endif
5667: #if defined(__GNUC__) || defined(__GNUG__)
5668: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5669: #endif
5670: #if defined(__HP_cc) || defined(__HP_aCC)
5671: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5672: #endif
5673: #if defined(__IBMC__) || defined(__IBMCPP__)
5674: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5675: #endif
5676: #if defined(_MSC_VER)
5677: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5678: #endif
5679: #if defined(__PGI)
5680: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5681: #endif
5682: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5683: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5684: #endif
5685: printf(" for ");fprintf(ficlog," for ");
5686:
5687: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5688: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5689: // Windows (x64 and x86)
5690: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
5691: #elif __unix__ // all unices, not all compilers
5692: // Unix
5693: printf("Unix ");fprintf(ficlog,"Unix ");
5694: #elif __linux__
5695: // linux
5696: printf("linux ");fprintf(ficlog,"linux ");
5697: #elif __APPLE__
5698: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5699: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
5700: #endif
5701:
5702: /* __MINGW32__ */
5703: /* __CYGWIN__ */
5704: /* __MINGW64__ */
5705: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5706: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5707: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5708: /* _WIN64 // Defined for applications for Win64. */
5709: /* _M_X64 // Defined for compilations that target x64 processors. */
5710: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
5711:
5712: #if UINTPTR_MAX == 0xffffffff
5713: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
5714: #elif UINTPTR_MAX == 0xffffffffffffffff
5715: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
5716: #else
5717: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
5718: #endif
5719:
5720: #if defined(__GNUC__)
5721: # if defined(__GNUC_PATCHLEVEL__)
5722: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5723: + __GNUC_MINOR__ * 100 \
5724: + __GNUC_PATCHLEVEL__)
5725: # else
5726: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5727: + __GNUC_MINOR__ * 100)
5728: # endif
5729: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5730: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
5731:
5732: if (uname(&sysInfo) != -1) {
5733: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5734: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5735: }
5736: else
5737: perror("uname() error");
5738: //#ifndef __INTEL_COMPILER
5739: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
5740: printf("GNU libc version: %s\n", gnu_get_libc_version());
5741: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
5742: #endif
5743: #endif
5744:
5745: // void main()
5746: // {
5747: #if defined(_MSC_VER)
5748: if (IsWow64()){
5749: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5750: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5751: }
5752: else{
5753: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5754: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5755: }
5756: // printf("\nPress Enter to continue...");
5757: // getchar();
5758: // }
5759:
5760: #endif
5761:
5762:
5763: }
5764:
5765: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5766: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5767: int i, j, k, i1 ;
5768: double ftolpl = 1.e-10;
5769: double age, agebase, agelim;
5770:
5771: strcpy(filerespl,"pl");
5772: strcat(filerespl,fileres);
5773: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5774: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5775: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5776: }
5777: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5778: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5779: pstamp(ficrespl);
5780: fprintf(ficrespl,"# Period (stable) prevalence \n");
5781: fprintf(ficrespl,"#Age ");
5782: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5783: fprintf(ficrespl,"\n");
5784:
5785: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5786:
5787: agebase=ageminpar;
5788: agelim=agemaxpar;
5789:
5790: i1=pow(2,cptcoveff);
5791: if (cptcovn < 1){i1=1;}
5792:
5793: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5794: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5795: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5796: k=k+1;
5797: /* to clean */
5798: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5799: fprintf(ficrespl,"\n#******");
5800: printf("\n#******");
5801: fprintf(ficlog,"\n#******");
5802: for(j=1;j<=cptcoveff;j++) {
5803: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5804: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5805: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5806: }
5807: fprintf(ficrespl,"******\n");
5808: printf("******\n");
5809: fprintf(ficlog,"******\n");
5810:
5811: fprintf(ficrespl,"#Age ");
5812: for(j=1;j<=cptcoveff;j++) {
5813: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5814: }
5815: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5816: fprintf(ficrespl,"\n");
5817:
5818: for (age=agebase; age<=agelim; age++){
5819: /* for (age=agebase; age<=agebase; age++){ */
5820: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5821: fprintf(ficrespl,"%.0f ",age );
5822: for(j=1;j<=cptcoveff;j++)
5823: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5824: for(i=1; i<=nlstate;i++)
5825: fprintf(ficrespl," %.5f", prlim[i][i]);
5826: fprintf(ficrespl,"\n");
5827: } /* Age */
5828: /* was end of cptcod */
5829: } /* cptcov */
5830: }
5831:
5832: int hPijx(double *p, int bage, int fage){
5833: /*------------- h Pij x at various ages ------------*/
5834:
5835: int stepsize;
5836: int agelim;
5837: int hstepm;
5838: int nhstepm;
5839: int h, i, i1, j, k;
5840:
5841: double agedeb;
5842: double ***p3mat;
5843:
5844: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5845: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5846: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5847: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5848: }
5849: printf("Computing pij: result on file '%s' \n", filerespij);
5850: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5851:
5852: stepsize=(int) (stepm+YEARM-1)/YEARM;
5853: /*if (stepm<=24) stepsize=2;*/
5854:
5855: agelim=AGESUP;
5856: hstepm=stepsize*YEARM; /* Every year of age */
5857: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5858:
5859: /* hstepm=1; aff par mois*/
5860: pstamp(ficrespij);
5861: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5862: i1= pow(2,cptcoveff);
5863: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
5864: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
5865: /* k=k+1; */
5866: for (k=1; k <= (int) pow(2,cptcoveff); k++){
5867: fprintf(ficrespij,"\n#****** ");
5868: for(j=1;j<=cptcoveff;j++)
5869: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5870: fprintf(ficrespij,"******\n");
5871:
5872: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5873: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5874: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5875:
5876: /* nhstepm=nhstepm*YEARM; aff par mois*/
5877:
5878: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5879: oldm=oldms;savm=savms;
5880: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5881: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5882: for(i=1; i<=nlstate;i++)
5883: for(j=1; j<=nlstate+ndeath;j++)
5884: fprintf(ficrespij," %1d-%1d",i,j);
5885: fprintf(ficrespij,"\n");
5886: for (h=0; h<=nhstepm; h++){
5887: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5888: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5889: for(i=1; i<=nlstate;i++)
5890: for(j=1; j<=nlstate+ndeath;j++)
5891: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5892: fprintf(ficrespij,"\n");
5893: }
5894: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5895: fprintf(ficrespij,"\n");
5896: }
5897: /*}*/
5898: }
5899: }
5900:
5901:
5902: /***********************************************/
5903: /**************** Main Program *****************/
5904: /***********************************************/
5905:
5906: int main(int argc, char *argv[])
5907: {
5908: #ifdef GSL
5909: const gsl_multimin_fminimizer_type *T;
5910: size_t iteri = 0, it;
5911: int rval = GSL_CONTINUE;
5912: int status = GSL_SUCCESS;
5913: double ssval;
5914: #endif
5915: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5916: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5917:
5918: int jj, ll, li, lj, lk;
5919: int numlinepar=0; /* Current linenumber of parameter file */
5920: int itimes;
5921: int NDIM=2;
5922: int vpopbased=0;
5923:
5924: char ca[32], cb[32];
5925: /* FILE *fichtm; *//* Html File */
5926: /* FILE *ficgp;*/ /*Gnuplot File */
5927: struct stat info;
5928: double agedeb;
5929: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5930:
5931: double fret;
5932: double dum; /* Dummy variable */
5933: double ***p3mat;
5934: double ***mobaverage;
5935:
5936: char line[MAXLINE];
5937: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5938: char pathr[MAXLINE], pathimach[MAXLINE];
5939: char *tok, *val; /* pathtot */
5940: int firstobs=1, lastobs=10;
5941: int c, h , cpt;
5942: int jl;
5943: int i1, j1, jk, stepsize;
5944: int *tab;
5945: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5946: int mobilav=0,popforecast=0;
5947: int hstepm, nhstepm;
5948: int agemortsup;
5949: float sumlpop=0.;
5950: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5951: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5952:
5953: double bage=0, fage=110, age, agelim, agebase;
5954: double ftolpl=FTOL;
5955: double **prlim;
5956: double ***param; /* Matrix of parameters */
5957: double *p;
5958: double **matcov; /* Matrix of covariance */
5959: double ***delti3; /* Scale */
5960: double *delti; /* Scale */
5961: double ***eij, ***vareij;
5962: double **varpl; /* Variances of prevalence limits by age */
5963: double *epj, vepp;
5964:
5965: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5966: double **ximort;
5967: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5968: int *dcwave;
5969:
5970: char z[1]="c";
5971:
5972: /*char *strt;*/
5973: char strtend[80];
5974:
5975:
5976: /* setlocale (LC_ALL, ""); */
5977: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5978: /* textdomain (PACKAGE); */
5979: /* setlocale (LC_CTYPE, ""); */
5980: /* setlocale (LC_MESSAGES, ""); */
5981:
5982: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5983: rstart_time = time(NULL);
5984: /* (void) gettimeofday(&start_time,&tzp);*/
5985: start_time = *localtime(&rstart_time);
5986: curr_time=start_time;
5987: /*tml = *localtime(&start_time.tm_sec);*/
5988: /* strcpy(strstart,asctime(&tml)); */
5989: strcpy(strstart,asctime(&start_time));
5990:
5991: /* printf("Localtime (at start)=%s",strstart); */
5992: /* tp.tm_sec = tp.tm_sec +86400; */
5993: /* tm = *localtime(&start_time.tm_sec); */
5994: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5995: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5996: /* tmg.tm_hour=tmg.tm_hour + 1; */
5997: /* tp.tm_sec = mktime(&tmg); */
5998: /* strt=asctime(&tmg); */
5999: /* printf("Time(after) =%s",strstart); */
6000: /* (void) time (&time_value);
6001: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6002: * tm = *localtime(&time_value);
6003: * strstart=asctime(&tm);
6004: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6005: */
6006:
6007: nberr=0; /* Number of errors and warnings */
6008: nbwarn=0;
6009: getcwd(pathcd, size);
6010:
6011: printf("\n%s\n%s",version,fullversion);
6012: if(argc <=1){
6013: printf("\nEnter the parameter file name: ");
6014: fgets(pathr,FILENAMELENGTH,stdin);
6015: i=strlen(pathr);
6016: if(pathr[i-1]=='\n')
6017: pathr[i-1]='\0';
6018: i=strlen(pathr);
6019: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6020: pathr[i-1]='\0';
6021: for (tok = pathr; tok != NULL; ){
6022: printf("Pathr |%s|\n",pathr);
6023: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6024: printf("val= |%s| pathr=%s\n",val,pathr);
6025: strcpy (pathtot, val);
6026: if(pathr[0] == '\0') break; /* Dirty */
6027: }
6028: }
6029: else{
6030: strcpy(pathtot,argv[1]);
6031: }
6032: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6033: /*cygwin_split_path(pathtot,path,optionfile);
6034: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6035: /* cutv(path,optionfile,pathtot,'\\');*/
6036:
6037: /* Split argv[0], imach program to get pathimach */
6038: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6039: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6040: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6041: /* strcpy(pathimach,argv[0]); */
6042: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6043: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6044: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6045: chdir(path); /* Can be a relative path */
6046: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6047: printf("Current directory %s!\n",pathcd);
6048: strcpy(command,"mkdir ");
6049: strcat(command,optionfilefiname);
6050: if((outcmd=system(command)) != 0){
6051: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6052: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6053: /* fclose(ficlog); */
6054: /* exit(1); */
6055: }
6056: /* if((imk=mkdir(optionfilefiname))<0){ */
6057: /* perror("mkdir"); */
6058: /* } */
6059:
6060: /*-------- arguments in the command line --------*/
6061:
6062: /* Log file */
6063: strcat(filelog, optionfilefiname);
6064: strcat(filelog,".log"); /* */
6065: if((ficlog=fopen(filelog,"w"))==NULL) {
6066: printf("Problem with logfile %s\n",filelog);
6067: goto end;
6068: }
6069: fprintf(ficlog,"Log filename:%s\n",filelog);
6070: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6071: fprintf(ficlog,"\nEnter the parameter file name: \n");
6072: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6073: path=%s \n\
6074: optionfile=%s\n\
6075: optionfilext=%s\n\
6076: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6077:
6078: syscompilerinfo();
6079:
6080: printf("Local time (at start):%s",strstart);
6081: fprintf(ficlog,"Local time (at start): %s",strstart);
6082: fflush(ficlog);
6083: /* (void) gettimeofday(&curr_time,&tzp); */
6084: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6085:
6086: /* */
6087: strcpy(fileres,"r");
6088: strcat(fileres, optionfilefiname);
6089: strcat(fileres,".txt"); /* Other files have txt extension */
6090:
6091: /*---------arguments file --------*/
6092:
6093: if((ficpar=fopen(optionfile,"r"))==NULL) {
6094: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6095: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6096: fflush(ficlog);
6097: /* goto end; */
6098: exit(70);
6099: }
6100:
6101:
6102:
6103: strcpy(filereso,"o");
6104: strcat(filereso,fileres);
6105: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6106: printf("Problem with Output resultfile: %s\n", filereso);
6107: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6108: fflush(ficlog);
6109: goto end;
6110: }
6111:
6112: /* Reads comments: lines beginning with '#' */
6113: numlinepar=0;
6114: while((c=getc(ficpar))=='#' && c!= EOF){
6115: ungetc(c,ficpar);
6116: fgets(line, MAXLINE, ficpar);
6117: numlinepar++;
6118: fputs(line,stdout);
6119: fputs(line,ficparo);
6120: fputs(line,ficlog);
6121: }
6122: ungetc(c,ficpar);
6123:
6124: fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
6125: numlinepar++;
6126: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
6127: fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6128: fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6129: fflush(ficlog);
6130: while((c=getc(ficpar))=='#' && c!= EOF){
6131: ungetc(c,ficpar);
6132: fgets(line, MAXLINE, ficpar);
6133: numlinepar++;
6134: fputs(line, stdout);
6135: //puts(line);
6136: fputs(line,ficparo);
6137: fputs(line,ficlog);
6138: }
6139: ungetc(c,ficpar);
6140:
6141:
6142: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6143: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6144: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6145: v1+v2*age+v2*v3 makes cptcovn = 3
6146: */
6147: if (strlen(model)>1)
6148: 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*/
6149: else
6150: ncovmodel=2;
6151: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
6152: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6153: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6154: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6155: 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);
6156: 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);
6157: fflush(stdout);
6158: fclose (ficlog);
6159: goto end;
6160: }
6161: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6162: delti=delti3[1][1];
6163: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6164: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6165: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6166: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6167: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6168: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6169: fclose (ficparo);
6170: fclose (ficlog);
6171: goto end;
6172: exit(0);
6173: }
6174: else if(mle==-3) {
6175: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6176: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6177: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6178: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6179: matcov=matrix(1,npar,1,npar);
6180: }
6181: else{
6182: /* Read guessed parameters */
6183: /* Reads comments: lines beginning with '#' */
6184: while((c=getc(ficpar))=='#' && c!= EOF){
6185: ungetc(c,ficpar);
6186: fgets(line, MAXLINE, ficpar);
6187: numlinepar++;
6188: fputs(line,stdout);
6189: fputs(line,ficparo);
6190: fputs(line,ficlog);
6191: }
6192: ungetc(c,ficpar);
6193:
6194: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6195: for(i=1; i <=nlstate; i++){
6196: j=0;
6197: for(jj=1; jj <=nlstate+ndeath; jj++){
6198: if(jj==i) continue;
6199: j++;
6200: fscanf(ficpar,"%1d%1d",&i1,&j1);
6201: if ((i1 != i) && (j1 != j)){
6202: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6203: It might be a problem of design; if ncovcol and the model are correct\n \
6204: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6205: exit(1);
6206: }
6207: fprintf(ficparo,"%1d%1d",i1,j1);
6208: if(mle==1)
6209: printf("%1d%1d",i,j);
6210: fprintf(ficlog,"%1d%1d",i,j);
6211: for(k=1; k<=ncovmodel;k++){
6212: fscanf(ficpar," %lf",¶m[i][j][k]);
6213: if(mle==1){
6214: printf(" %lf",param[i][j][k]);
6215: fprintf(ficlog," %lf",param[i][j][k]);
6216: }
6217: else
6218: fprintf(ficlog," %lf",param[i][j][k]);
6219: fprintf(ficparo," %lf",param[i][j][k]);
6220: }
6221: fscanf(ficpar,"\n");
6222: numlinepar++;
6223: if(mle==1)
6224: printf("\n");
6225: fprintf(ficlog,"\n");
6226: fprintf(ficparo,"\n");
6227: }
6228: }
6229: fflush(ficlog);
6230:
6231: /* Reads scales values */
6232: p=param[1][1];
6233:
6234: /* Reads comments: lines beginning with '#' */
6235: while((c=getc(ficpar))=='#' && c!= EOF){
6236: ungetc(c,ficpar);
6237: fgets(line, MAXLINE, ficpar);
6238: numlinepar++;
6239: fputs(line,stdout);
6240: fputs(line,ficparo);
6241: fputs(line,ficlog);
6242: }
6243: ungetc(c,ficpar);
6244:
6245: for(i=1; i <=nlstate; i++){
6246: for(j=1; j <=nlstate+ndeath-1; j++){
6247: fscanf(ficpar,"%1d%1d",&i1,&j1);
6248: if ( (i1-i) * (j1-j) != 0){
6249: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6250: exit(1);
6251: }
6252: printf("%1d%1d",i,j);
6253: fprintf(ficparo,"%1d%1d",i1,j1);
6254: fprintf(ficlog,"%1d%1d",i1,j1);
6255: for(k=1; k<=ncovmodel;k++){
6256: fscanf(ficpar,"%le",&delti3[i][j][k]);
6257: printf(" %le",delti3[i][j][k]);
6258: fprintf(ficparo," %le",delti3[i][j][k]);
6259: fprintf(ficlog," %le",delti3[i][j][k]);
6260: }
6261: fscanf(ficpar,"\n");
6262: numlinepar++;
6263: printf("\n");
6264: fprintf(ficparo,"\n");
6265: fprintf(ficlog,"\n");
6266: }
6267: }
6268: fflush(ficlog);
6269:
6270: /* Reads covariance matrix */
6271: delti=delti3[1][1];
6272:
6273:
6274: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6275:
6276: /* Reads comments: lines beginning with '#' */
6277: while((c=getc(ficpar))=='#' && c!= EOF){
6278: ungetc(c,ficpar);
6279: fgets(line, MAXLINE, ficpar);
6280: numlinepar++;
6281: fputs(line,stdout);
6282: fputs(line,ficparo);
6283: fputs(line,ficlog);
6284: }
6285: ungetc(c,ficpar);
6286:
6287: matcov=matrix(1,npar,1,npar);
6288: for(i=1; i <=npar; i++)
6289: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6290:
6291: for(i=1; i <=npar; i++){
6292: fscanf(ficpar,"%s",str);
6293: if(mle==1)
6294: printf("%s",str);
6295: fprintf(ficlog,"%s",str);
6296: fprintf(ficparo,"%s",str);
6297: for(j=1; j <=i; j++){
6298: fscanf(ficpar," %le",&matcov[i][j]);
6299: if(mle==1){
6300: printf(" %.5le",matcov[i][j]);
6301: }
6302: fprintf(ficlog," %.5le",matcov[i][j]);
6303: fprintf(ficparo," %.5le",matcov[i][j]);
6304: }
6305: fscanf(ficpar,"\n");
6306: numlinepar++;
6307: if(mle==1)
6308: printf("\n");
6309: fprintf(ficlog,"\n");
6310: fprintf(ficparo,"\n");
6311: }
6312: for(i=1; i <=npar; i++)
6313: for(j=i+1;j<=npar;j++)
6314: matcov[i][j]=matcov[j][i];
6315:
6316: if(mle==1)
6317: printf("\n");
6318: fprintf(ficlog,"\n");
6319:
6320: fflush(ficlog);
6321:
6322: /*-------- Rewriting parameter file ----------*/
6323: strcpy(rfileres,"r"); /* "Rparameterfile */
6324: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6325: strcat(rfileres,"."); /* */
6326: strcat(rfileres,optionfilext); /* Other files have txt extension */
6327: if((ficres =fopen(rfileres,"w"))==NULL) {
6328: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6329: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6330: }
6331: fprintf(ficres,"#%s\n",version);
6332: } /* End of mle != -3 */
6333:
6334:
6335: n= lastobs;
6336: num=lvector(1,n);
6337: moisnais=vector(1,n);
6338: annais=vector(1,n);
6339: moisdc=vector(1,n);
6340: andc=vector(1,n);
6341: agedc=vector(1,n);
6342: cod=ivector(1,n);
6343: weight=vector(1,n);
6344: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6345: mint=matrix(1,maxwav,1,n);
6346: anint=matrix(1,maxwav,1,n);
6347: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6348: tab=ivector(1,NCOVMAX);
6349: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6350:
6351: /* Reads data from file datafile */
6352: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6353: goto end;
6354:
6355: /* Calculation of the number of parameters from char model */
6356: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6357: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6358: k=3 V4 Tvar[k=3]= 4 (from V4)
6359: k=2 V1 Tvar[k=2]= 1 (from V1)
6360: k=1 Tvar[1]=2 (from V2)
6361: */
6362: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6363: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6364: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6365: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6366: */
6367: /* For model-covariate k tells which data-covariate to use but
6368: because this model-covariate is a construction we invent a new column
6369: ncovcol + k1
6370: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6371: Tvar[3=V1*V4]=4+1 etc */
6372: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6373: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6374: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6375: */
6376: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6377: 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
6378: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6379: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6380: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6381: 4 covariates (3 plus signs)
6382: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6383: */
6384:
6385: if(decodemodel(model, lastobs) == 1)
6386: goto end;
6387:
6388: if((double)(lastobs-imx)/(double)imx > 1.10){
6389: nbwarn++;
6390: 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);
6391: 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);
6392: }
6393: /* if(mle==1){*/
6394: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6395: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6396: }
6397:
6398: /*-calculation of age at interview from date of interview and age at death -*/
6399: agev=matrix(1,maxwav,1,imx);
6400:
6401: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6402: goto end;
6403:
6404:
6405: agegomp=(int)agemin;
6406: free_vector(moisnais,1,n);
6407: free_vector(annais,1,n);
6408: /* free_matrix(mint,1,maxwav,1,n);
6409: free_matrix(anint,1,maxwav,1,n);*/
6410: free_vector(moisdc,1,n);
6411: free_vector(andc,1,n);
6412: /* */
6413:
6414: wav=ivector(1,imx);
6415: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6416: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6417: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6418:
6419: /* Concatenates waves */
6420: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6421: /* */
6422:
6423: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6424:
6425: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6426: ncodemax[1]=1;
6427: Ndum =ivector(-1,NCOVMAX);
6428: if (ncovmodel > 2)
6429: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6430:
6431: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6432: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6433: h=0;
6434:
6435:
6436: /*if (cptcovn > 0) */
6437:
6438:
6439: m=pow(2,cptcoveff);
6440:
6441: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6442: 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 */
6443: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6444: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6445: h++;
6446: if (h>m)
6447: h=1;
6448: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6449: * h 1 2 3 4
6450: *______________________________
6451: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6452: * 2 2 1 1 1
6453: * 3 i=2 1 2 1 1
6454: * 4 2 2 1 1
6455: * 5 i=3 1 i=2 1 2 1
6456: * 6 2 1 2 1
6457: * 7 i=4 1 2 2 1
6458: * 8 2 2 2 1
6459: * 9 i=5 1 i=3 1 i=2 1 1
6460: * 10 2 1 1 1
6461: * 11 i=6 1 2 1 1
6462: * 12 2 2 1 1
6463: * 13 i=7 1 i=4 1 2 1
6464: * 14 2 1 2 1
6465: * 15 i=8 1 2 2 1
6466: * 16 2 2 2 1
6467: */
6468: codtab[h][k]=j;
6469: /*codtab[h][Tvar[k]]=j;*/
6470: 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]]);
6471: }
6472: }
6473: }
6474: }
6475: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6476: codtab[1][2]=1;codtab[2][2]=2; */
6477: /* for(i=1; i <=m ;i++){
6478: for(k=1; k <=cptcovn; k++){
6479: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6480: }
6481: printf("\n");
6482: }
6483: scanf("%d",i);*/
6484:
6485: free_ivector(Ndum,-1,NCOVMAX);
6486:
6487:
6488:
6489: /*------------ gnuplot -------------*/
6490: strcpy(optionfilegnuplot,optionfilefiname);
6491: if(mle==-3)
6492: strcat(optionfilegnuplot,"-mort");
6493: strcat(optionfilegnuplot,".gp");
6494:
6495: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6496: printf("Problem with file %s",optionfilegnuplot);
6497: }
6498: else{
6499: fprintf(ficgp,"\n# %s\n", version);
6500: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6501: //fprintf(ficgp,"set missing 'NaNq'\n");
6502: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6503: }
6504: /* fclose(ficgp);*/
6505: /*--------- index.htm --------*/
6506:
6507: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6508: if(mle==-3)
6509: strcat(optionfilehtm,"-mort");
6510: strcat(optionfilehtm,".htm");
6511: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6512: printf("Problem with %s \n",optionfilehtm);
6513: exit(0);
6514: }
6515:
6516: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6517: strcat(optionfilehtmcov,"-cov.htm");
6518: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6519: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6520: }
6521: else{
6522: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6523: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6524: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6525: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6526: }
6527:
6528: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6529: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6530: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6531: \n\
6532: <hr size=\"2\" color=\"#EC5E5E\">\
6533: <ul><li><h4>Parameter files</h4>\n\
6534: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6535: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6536: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6537: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6538: - Date and time at start: %s</ul>\n",\
6539: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6540: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6541: fileres,fileres,\
6542: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6543: fflush(fichtm);
6544:
6545: strcpy(pathr,path);
6546: strcat(pathr,optionfilefiname);
6547: chdir(optionfilefiname); /* Move to directory named optionfile */
6548:
6549: /* Calculates basic frequencies. Computes observed prevalence at single age
6550: and prints on file fileres'p'. */
6551: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6552:
6553: fprintf(fichtm,"\n");
6554: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6555: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6556: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6557: imx,agemin,agemax,jmin,jmax,jmean);
6558: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6559: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6560: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6561: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6562: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6563:
6564:
6565: /* For Powell, parameters are in a vector p[] starting at p[1]
6566: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6567: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6568:
6569: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6570:
6571: if (mle==-3){
6572: ximort=matrix(1,NDIM,1,NDIM);
6573: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6574: cens=ivector(1,n);
6575: ageexmed=vector(1,n);
6576: agecens=vector(1,n);
6577: dcwave=ivector(1,n);
6578:
6579: for (i=1; i<=imx; i++){
6580: dcwave[i]=-1;
6581: for (m=firstpass; m<=lastpass; m++)
6582: if (s[m][i]>nlstate) {
6583: dcwave[i]=m;
6584: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6585: break;
6586: }
6587: }
6588:
6589: for (i=1; i<=imx; i++) {
6590: if (wav[i]>0){
6591: ageexmed[i]=agev[mw[1][i]][i];
6592: j=wav[i];
6593: agecens[i]=1.;
6594:
6595: if (ageexmed[i]> 1 && wav[i] > 0){
6596: agecens[i]=agev[mw[j][i]][i];
6597: cens[i]= 1;
6598: }else if (ageexmed[i]< 1)
6599: cens[i]= -1;
6600: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6601: cens[i]=0 ;
6602: }
6603: else cens[i]=-1;
6604: }
6605:
6606: for (i=1;i<=NDIM;i++) {
6607: for (j=1;j<=NDIM;j++)
6608: ximort[i][j]=(i == j ? 1.0 : 0.0);
6609: }
6610:
6611: /*p[1]=0.0268; p[NDIM]=0.083;*/
6612: /*printf("%lf %lf", p[1], p[2]);*/
6613:
6614:
6615: #ifdef GSL
6616: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6617: #else
6618: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6619: #endif
6620: strcpy(filerespow,"pow-mort");
6621: strcat(filerespow,fileres);
6622: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6623: printf("Problem with resultfile: %s\n", filerespow);
6624: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6625: }
6626: #ifdef GSL
6627: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6628: #else
6629: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6630: #endif
6631: /* for (i=1;i<=nlstate;i++)
6632: for(j=1;j<=nlstate+ndeath;j++)
6633: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6634: */
6635: fprintf(ficrespow,"\n");
6636: #ifdef GSL
6637: /* gsl starts here */
6638: T = gsl_multimin_fminimizer_nmsimplex;
6639: gsl_multimin_fminimizer *sfm = NULL;
6640: gsl_vector *ss, *x;
6641: gsl_multimin_function minex_func;
6642:
6643: /* Initial vertex size vector */
6644: ss = gsl_vector_alloc (NDIM);
6645:
6646: if (ss == NULL){
6647: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6648: }
6649: /* Set all step sizes to 1 */
6650: gsl_vector_set_all (ss, 0.001);
6651:
6652: /* Starting point */
6653:
6654: x = gsl_vector_alloc (NDIM);
6655:
6656: if (x == NULL){
6657: gsl_vector_free(ss);
6658: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6659: }
6660:
6661: /* Initialize method and iterate */
6662: /* p[1]=0.0268; p[NDIM]=0.083; */
6663: /* gsl_vector_set(x, 0, 0.0268); */
6664: /* gsl_vector_set(x, 1, 0.083); */
6665: gsl_vector_set(x, 0, p[1]);
6666: gsl_vector_set(x, 1, p[2]);
6667:
6668: minex_func.f = &gompertz_f;
6669: minex_func.n = NDIM;
6670: minex_func.params = (void *)&p; /* ??? */
6671:
6672: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6673: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6674:
6675: printf("Iterations beginning .....\n\n");
6676: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6677:
6678: iteri=0;
6679: while (rval == GSL_CONTINUE){
6680: iteri++;
6681: status = gsl_multimin_fminimizer_iterate(sfm);
6682:
6683: if (status) printf("error: %s\n", gsl_strerror (status));
6684: fflush(0);
6685:
6686: if (status)
6687: break;
6688:
6689: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6690: ssval = gsl_multimin_fminimizer_size (sfm);
6691:
6692: if (rval == GSL_SUCCESS)
6693: printf ("converged to a local maximum at\n");
6694:
6695: printf("%5d ", iteri);
6696: for (it = 0; it < NDIM; it++){
6697: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6698: }
6699: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6700: }
6701:
6702: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6703:
6704: gsl_vector_free(x); /* initial values */
6705: gsl_vector_free(ss); /* inital step size */
6706: for (it=0; it<NDIM; it++){
6707: p[it+1]=gsl_vector_get(sfm->x,it);
6708: fprintf(ficrespow," %.12lf", p[it]);
6709: }
6710: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6711: #endif
6712: #ifdef POWELL
6713: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6714: #endif
6715: fclose(ficrespow);
6716:
6717: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6718:
6719: for(i=1; i <=NDIM; i++)
6720: for(j=i+1;j<=NDIM;j++)
6721: matcov[i][j]=matcov[j][i];
6722:
6723: printf("\nCovariance matrix\n ");
6724: for(i=1; i <=NDIM; i++) {
6725: for(j=1;j<=NDIM;j++){
6726: printf("%f ",matcov[i][j]);
6727: }
6728: printf("\n ");
6729: }
6730:
6731: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6732: for (i=1;i<=NDIM;i++)
6733: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6734:
6735: lsurv=vector(1,AGESUP);
6736: lpop=vector(1,AGESUP);
6737: tpop=vector(1,AGESUP);
6738: lsurv[agegomp]=100000;
6739:
6740: for (k=agegomp;k<=AGESUP;k++) {
6741: agemortsup=k;
6742: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6743: }
6744:
6745: for (k=agegomp;k<agemortsup;k++)
6746: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6747:
6748: for (k=agegomp;k<agemortsup;k++){
6749: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6750: sumlpop=sumlpop+lpop[k];
6751: }
6752:
6753: tpop[agegomp]=sumlpop;
6754: for (k=agegomp;k<(agemortsup-3);k++){
6755: /* tpop[k+1]=2;*/
6756: tpop[k+1]=tpop[k]-lpop[k];
6757: }
6758:
6759:
6760: printf("\nAge lx qx dx Lx Tx e(x)\n");
6761: for (k=agegomp;k<(agemortsup-2);k++)
6762: 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]);
6763:
6764:
6765: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6766: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6767:
6768: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6769: stepm, weightopt,\
6770: model,imx,p,matcov,agemortsup);
6771:
6772: free_vector(lsurv,1,AGESUP);
6773: free_vector(lpop,1,AGESUP);
6774: free_vector(tpop,1,AGESUP);
6775: #ifdef GSL
6776: free_ivector(cens,1,n);
6777: free_vector(agecens,1,n);
6778: free_ivector(dcwave,1,n);
6779: free_matrix(ximort,1,NDIM,1,NDIM);
6780: #endif
6781: } /* Endof if mle==-3 */
6782:
6783: else{ /* For mle >=1 */
6784: globpr=0;/* debug */
6785: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6786: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6787: for (k=1; k<=npar;k++)
6788: printf(" %d %8.5f",k,p[k]);
6789: printf("\n");
6790: globpr=1; /* to print the contributions */
6791: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6792: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6793: for (k=1; k<=npar;k++)
6794: printf(" %d %8.5f",k,p[k]);
6795: printf("\n");
6796: if(mle>=1){ /* Could be 1 or 2 */
6797: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6798: }
6799:
6800: /*--------- results files --------------*/
6801: fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
6802:
6803:
6804: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6805: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6806: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6807: for(i=1,jk=1; i <=nlstate; i++){
6808: for(k=1; k <=(nlstate+ndeath); k++){
6809: if (k != i) {
6810: printf("%d%d ",i,k);
6811: fprintf(ficlog,"%d%d ",i,k);
6812: fprintf(ficres,"%1d%1d ",i,k);
6813: for(j=1; j <=ncovmodel; j++){
6814: printf("%lf ",p[jk]);
6815: fprintf(ficlog,"%lf ",p[jk]);
6816: fprintf(ficres,"%lf ",p[jk]);
6817: jk++;
6818: }
6819: printf("\n");
6820: fprintf(ficlog,"\n");
6821: fprintf(ficres,"\n");
6822: }
6823: }
6824: }
6825: if(mle!=0){
6826: /* Computing hessian and covariance matrix */
6827: ftolhess=ftol; /* Usually correct */
6828: hesscov(matcov, p, npar, delti, ftolhess, func);
6829: }
6830: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6831: printf("# Scales (for hessian or gradient estimation)\n");
6832: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6833: for(i=1,jk=1; i <=nlstate; i++){
6834: for(j=1; j <=nlstate+ndeath; j++){
6835: if (j!=i) {
6836: fprintf(ficres,"%1d%1d",i,j);
6837: printf("%1d%1d",i,j);
6838: fprintf(ficlog,"%1d%1d",i,j);
6839: for(k=1; k<=ncovmodel;k++){
6840: printf(" %.5e",delti[jk]);
6841: fprintf(ficlog," %.5e",delti[jk]);
6842: fprintf(ficres," %.5e",delti[jk]);
6843: jk++;
6844: }
6845: printf("\n");
6846: fprintf(ficlog,"\n");
6847: fprintf(ficres,"\n");
6848: }
6849: }
6850: }
6851:
6852: 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");
6853: if(mle>=1)
6854: 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");
6855: 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");
6856: /* # 121 Var(a12)\n\ */
6857: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6858: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6859: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6860: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6861: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6862: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6863: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6864:
6865:
6866: /* Just to have a covariance matrix which will be more understandable
6867: even is we still don't want to manage dictionary of variables
6868: */
6869: for(itimes=1;itimes<=2;itimes++){
6870: jj=0;
6871: for(i=1; i <=nlstate; i++){
6872: for(j=1; j <=nlstate+ndeath; j++){
6873: if(j==i) continue;
6874: for(k=1; k<=ncovmodel;k++){
6875: jj++;
6876: ca[0]= k+'a'-1;ca[1]='\0';
6877: if(itimes==1){
6878: if(mle>=1)
6879: printf("#%1d%1d%d",i,j,k);
6880: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6881: fprintf(ficres,"#%1d%1d%d",i,j,k);
6882: }else{
6883: if(mle>=1)
6884: printf("%1d%1d%d",i,j,k);
6885: fprintf(ficlog,"%1d%1d%d",i,j,k);
6886: fprintf(ficres,"%1d%1d%d",i,j,k);
6887: }
6888: ll=0;
6889: for(li=1;li <=nlstate; li++){
6890: for(lj=1;lj <=nlstate+ndeath; lj++){
6891: if(lj==li) continue;
6892: for(lk=1;lk<=ncovmodel;lk++){
6893: ll++;
6894: if(ll<=jj){
6895: cb[0]= lk +'a'-1;cb[1]='\0';
6896: if(ll<jj){
6897: if(itimes==1){
6898: if(mle>=1)
6899: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6900: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6901: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6902: }else{
6903: if(mle>=1)
6904: printf(" %.5e",matcov[jj][ll]);
6905: fprintf(ficlog," %.5e",matcov[jj][ll]);
6906: fprintf(ficres," %.5e",matcov[jj][ll]);
6907: }
6908: }else{
6909: if(itimes==1){
6910: if(mle>=1)
6911: printf(" Var(%s%1d%1d)",ca,i,j);
6912: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6913: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6914: }else{
6915: if(mle>=1)
6916: printf(" %.5e",matcov[jj][ll]);
6917: fprintf(ficlog," %.5e",matcov[jj][ll]);
6918: fprintf(ficres," %.5e",matcov[jj][ll]);
6919: }
6920: }
6921: }
6922: } /* end lk */
6923: } /* end lj */
6924: } /* end li */
6925: if(mle>=1)
6926: printf("\n");
6927: fprintf(ficlog,"\n");
6928: fprintf(ficres,"\n");
6929: numlinepar++;
6930: } /* end k*/
6931: } /*end j */
6932: } /* end i */
6933: } /* end itimes */
6934:
6935: fflush(ficlog);
6936: fflush(ficres);
6937:
6938: while((c=getc(ficpar))=='#' && c!= EOF){
6939: ungetc(c,ficpar);
6940: fgets(line, MAXLINE, ficpar);
6941: fputs(line,stdout);
6942: fputs(line,ficparo);
6943: }
6944: ungetc(c,ficpar);
6945:
6946: estepm=0;
6947: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6948: if (estepm==0 || estepm < stepm) estepm=stepm;
6949: if (fage <= 2) {
6950: bage = ageminpar;
6951: fage = agemaxpar;
6952: }
6953:
6954: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6955: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6956: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6957:
6958: while((c=getc(ficpar))=='#' && c!= EOF){
6959: ungetc(c,ficpar);
6960: fgets(line, MAXLINE, ficpar);
6961: fputs(line,stdout);
6962: fputs(line,ficparo);
6963: }
6964: ungetc(c,ficpar);
6965:
6966: 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);
6967: 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);
6968: 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);
6969: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6970: 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);
6971:
6972: while((c=getc(ficpar))=='#' && c!= EOF){
6973: ungetc(c,ficpar);
6974: fgets(line, MAXLINE, ficpar);
6975: fputs(line,stdout);
6976: fputs(line,ficparo);
6977: }
6978: ungetc(c,ficpar);
6979:
6980:
6981: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6982: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6983:
6984: fscanf(ficpar,"pop_based=%d\n",&popbased);
6985: fprintf(ficparo,"pop_based=%d\n",popbased);
6986: fprintf(ficres,"pop_based=%d\n",popbased);
6987:
6988: while((c=getc(ficpar))=='#' && c!= EOF){
6989: ungetc(c,ficpar);
6990: fgets(line, MAXLINE, ficpar);
6991: fputs(line,stdout);
6992: fputs(line,ficparo);
6993: }
6994: ungetc(c,ficpar);
6995:
6996: 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);
6997: 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);
6998: 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);
6999: 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);
7000: 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);
7001: /* day and month of proj2 are not used but only year anproj2.*/
7002:
7003:
7004:
7005: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7006: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
7007:
7008: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7009: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7010:
7011: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7012: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7013: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7014:
7015: /*------------ free_vector -------------*/
7016: /* chdir(path); */
7017:
7018: free_ivector(wav,1,imx);
7019: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7020: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7021: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7022: free_lvector(num,1,n);
7023: free_vector(agedc,1,n);
7024: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7025: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7026: fclose(ficparo);
7027: fclose(ficres);
7028:
7029:
7030: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
7031: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7032: prlim=matrix(1,nlstate,1,nlstate);
7033: prevalence_limit(p, prlim, ageminpar, agemaxpar);
7034: fclose(ficrespl);
7035:
7036: #ifdef FREEEXIT2
7037: #include "freeexit2.h"
7038: #endif
7039:
7040: /*------------- h Pij x at various ages ------------*/
7041: /*#include "hpijx.h"*/
7042: hPijx(p, bage, fage);
7043: fclose(ficrespij);
7044:
7045: /*-------------- Variance of one-step probabilities---*/
7046: k=1;
7047: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7048:
7049:
7050: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7051: for(i=1;i<=AGESUP;i++)
7052: for(j=1;j<=NCOVMAX;j++)
7053: for(k=1;k<=NCOVMAX;k++)
7054: probs[i][j][k]=0.;
7055:
7056: /*---------- Forecasting ------------------*/
7057: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7058: if(prevfcast==1){
7059: /* if(stepm ==1){*/
7060: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7061: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7062: /* } */
7063: /* else{ */
7064: /* erreur=108; */
7065: /* 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); */
7066: /* 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); */
7067: /* } */
7068: }
7069:
7070:
7071: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7072:
7073: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7074: /* 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",\
7075: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7076: */
7077:
7078: if (mobilav!=0) {
7079: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7080: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7081: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7082: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7083: }
7084: }
7085:
7086:
7087: /*---------- Health expectancies, no variances ------------*/
7088:
7089: strcpy(filerese,"e");
7090: strcat(filerese,fileres);
7091: if((ficreseij=fopen(filerese,"w"))==NULL) {
7092: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7093: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7094: }
7095: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7096: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
7097: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7098: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7099:
7100: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7101: fprintf(ficreseij,"\n#****** ");
7102: for(j=1;j<=cptcoveff;j++) {
7103: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7104: }
7105: fprintf(ficreseij,"******\n");
7106:
7107: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7108: oldm=oldms;savm=savms;
7109: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7110:
7111: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7112: /*}*/
7113: }
7114: fclose(ficreseij);
7115:
7116:
7117: /*---------- Health expectancies and variances ------------*/
7118:
7119:
7120: strcpy(filerest,"t");
7121: strcat(filerest,fileres);
7122: if((ficrest=fopen(filerest,"w"))==NULL) {
7123: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7124: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7125: }
7126: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7127: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7128:
7129:
7130: strcpy(fileresstde,"stde");
7131: strcat(fileresstde,fileres);
7132: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7133: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7134: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7135: }
7136: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7137: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7138:
7139: strcpy(filerescve,"cve");
7140: strcat(filerescve,fileres);
7141: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7142: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7143: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7144: }
7145: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7146: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7147:
7148: strcpy(fileresv,"v");
7149: strcat(fileresv,fileres);
7150: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7151: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7152: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7153: }
7154: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7155: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7156:
7157: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7158: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7159:
7160: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7161: fprintf(ficrest,"\n#****** ");
7162: for(j=1;j<=cptcoveff;j++)
7163: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7164: fprintf(ficrest,"******\n");
7165:
7166: fprintf(ficresstdeij,"\n#****** ");
7167: fprintf(ficrescveij,"\n#****** ");
7168: for(j=1;j<=cptcoveff;j++) {
7169: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7170: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7171: }
7172: fprintf(ficresstdeij,"******\n");
7173: fprintf(ficrescveij,"******\n");
7174:
7175: fprintf(ficresvij,"\n#****** ");
7176: for(j=1;j<=cptcoveff;j++)
7177: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7178: fprintf(ficresvij,"******\n");
7179:
7180: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7181: oldm=oldms;savm=savms;
7182: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7183: /*
7184: */
7185: /* goto endfree; */
7186:
7187: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7188: pstamp(ficrest);
7189:
7190:
7191: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7192: oldm=oldms;savm=savms; /* Segmentation fault */
7193: cptcod= 0; /* To be deleted */
7194: 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 */
7195: 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 ");
7196: if(vpopbased==1)
7197: 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);
7198: else
7199: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7200: fprintf(ficrest,"# Age e.. (std) ");
7201: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7202: fprintf(ficrest,"\n");
7203:
7204: epj=vector(1,nlstate+1);
7205: for(age=bage; age <=fage ;age++){
7206: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7207: if (vpopbased==1) {
7208: if(mobilav ==0){
7209: for(i=1; i<=nlstate;i++)
7210: prlim[i][i]=probs[(int)age][i][k];
7211: }else{ /* mobilav */
7212: for(i=1; i<=nlstate;i++)
7213: prlim[i][i]=mobaverage[(int)age][i][k];
7214: }
7215: }
7216:
7217: fprintf(ficrest," %4.0f",age);
7218: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7219: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7220: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7221: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7222: }
7223: epj[nlstate+1] +=epj[j];
7224: }
7225:
7226: for(i=1, vepp=0.;i <=nlstate;i++)
7227: for(j=1;j <=nlstate;j++)
7228: vepp += vareij[i][j][(int)age];
7229: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7230: for(j=1;j <=nlstate;j++){
7231: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7232: }
7233: fprintf(ficrest,"\n");
7234: }
7235: }
7236: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7237: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7238: free_vector(epj,1,nlstate+1);
7239: /*}*/
7240: }
7241: free_vector(weight,1,n);
7242: free_imatrix(Tvard,1,NCOVMAX,1,2);
7243: free_imatrix(s,1,maxwav+1,1,n);
7244: free_matrix(anint,1,maxwav,1,n);
7245: free_matrix(mint,1,maxwav,1,n);
7246: free_ivector(cod,1,n);
7247: free_ivector(tab,1,NCOVMAX);
7248: fclose(ficresstdeij);
7249: fclose(ficrescveij);
7250: fclose(ficresvij);
7251: fclose(ficrest);
7252: fclose(ficpar);
7253:
7254: /*------- Variance of period (stable) prevalence------*/
7255:
7256: strcpy(fileresvpl,"vpl");
7257: strcat(fileresvpl,fileres);
7258: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7259: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7260: exit(0);
7261: }
7262: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7263:
7264: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7265: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7266:
7267: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7268: fprintf(ficresvpl,"\n#****** ");
7269: for(j=1;j<=cptcoveff;j++)
7270: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7271: fprintf(ficresvpl,"******\n");
7272:
7273: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7274: oldm=oldms;savm=savms;
7275: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7276: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7277: /*}*/
7278: }
7279:
7280: fclose(ficresvpl);
7281:
7282: /*---------- End : free ----------------*/
7283: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7284: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7285: } /* mle==-3 arrives here for freeing */
7286: /* endfree:*/
7287: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7288: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7289: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7290: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7291: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7292: free_matrix(covar,0,NCOVMAX,1,n);
7293: free_matrix(matcov,1,npar,1,npar);
7294: /*free_vector(delti,1,npar);*/
7295: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7296: free_matrix(agev,1,maxwav,1,imx);
7297: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7298:
7299: free_ivector(ncodemax,1,NCOVMAX);
7300: free_ivector(Tvar,1,NCOVMAX);
7301: free_ivector(Tprod,1,NCOVMAX);
7302: free_ivector(Tvaraff,1,NCOVMAX);
7303: free_ivector(Tage,1,NCOVMAX);
7304:
7305: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7306: free_imatrix(codtab,1,100,1,10);
7307: fflush(fichtm);
7308: fflush(ficgp);
7309:
7310:
7311: if((nberr >0) || (nbwarn>0)){
7312: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7313: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7314: }else{
7315: printf("End of Imach\n");
7316: fprintf(ficlog,"End of Imach\n");
7317: }
7318: printf("See log file on %s\n",filelog);
7319: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7320: /*(void) gettimeofday(&end_time,&tzp);*/
7321: rend_time = time(NULL);
7322: end_time = *localtime(&rend_time);
7323: /* tml = *localtime(&end_time.tm_sec); */
7324: strcpy(strtend,asctime(&end_time));
7325: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7326: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7327: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7328:
7329: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7330: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7331: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7332: /* printf("Total time was %d uSec.\n", total_usecs);*/
7333: /* if(fileappend(fichtm,optionfilehtm)){ */
7334: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7335: fclose(fichtm);
7336: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7337: fclose(fichtmcov);
7338: fclose(ficgp);
7339: fclose(ficlog);
7340: /*------ End -----------*/
7341:
7342:
7343: printf("Before Current directory %s!\n",pathcd);
7344: if(chdir(pathcd) != 0)
7345: printf("Can't move to directory %s!\n",path);
7346: if(getcwd(pathcd,MAXLINE) > 0)
7347: printf("Current directory %s!\n",pathcd);
7348: /*strcat(plotcmd,CHARSEPARATOR);*/
7349: sprintf(plotcmd,"gnuplot");
7350: #ifdef _WIN32
7351: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7352: #endif
7353: if(!stat(plotcmd,&info)){
7354: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7355: if(!stat(getenv("GNUPLOTBIN"),&info)){
7356: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7357: }else
7358: strcpy(pplotcmd,plotcmd);
7359: #ifdef __unix
7360: strcpy(plotcmd,GNUPLOTPROGRAM);
7361: if(!stat(plotcmd,&info)){
7362: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7363: }else
7364: strcpy(pplotcmd,plotcmd);
7365: #endif
7366: }else
7367: strcpy(pplotcmd,plotcmd);
7368:
7369: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7370: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7371:
7372: if((outcmd=system(plotcmd)) != 0){
7373: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7374: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7375: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7376: if((outcmd=system(plotcmd)) != 0)
7377: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7378: }
7379: printf(" Successful, please wait...");
7380: while (z[0] != 'q') {
7381: /* chdir(path); */
7382: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7383: scanf("%s",z);
7384: /* if (z[0] == 'c') system("./imach"); */
7385: if (z[0] == 'e') {
7386: #ifdef __APPLE__
7387: sprintf(pplotcmd, "open %s", optionfilehtm);
7388: #elif __linux
7389: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7390: #else
7391: sprintf(pplotcmd, "%s", optionfilehtm);
7392: #endif
7393: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7394: system(pplotcmd);
7395: }
7396: else if (z[0] == 'g') system(plotcmd);
7397: else if (z[0] == 'q') exit(0);
7398: }
7399: end:
7400: while (z[0] != 'q') {
7401: printf("\nType q for exiting: ");
7402: scanf("%s",z);
7403: }
7404: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>