Annotation of imach/src/imach.c, revision 1.181
1.181 ! brouard 1: /* $Id: imach.c,v 1.180 2015/02/11 17:33:45 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.181 ! brouard 4: Revision 1.180 2015/02/11 17:33:45 brouard
! 5: Summary: Finishing move from main to function (hpijx and prevalence_limit)
! 6:
1.180 brouard 7: Revision 1.179 2015/01/04 09:57:06 brouard
8: Summary: back to OS/X
9:
1.179 brouard 10: Revision 1.178 2015/01/04 09:35:48 brouard
11: *** empty log message ***
12:
1.178 brouard 13: Revision 1.177 2015/01/03 18:40:56 brouard
14: Summary: Still testing ilc32 on OSX
15:
1.177 brouard 16: Revision 1.176 2015/01/03 16:45:04 brouard
17: *** empty log message ***
18:
1.176 brouard 19: Revision 1.175 2015/01/03 16:33:42 brouard
20: *** empty log message ***
21:
1.175 brouard 22: Revision 1.174 2015/01/03 16:15:49 brouard
23: Summary: Still in cross-compilation
24:
1.174 brouard 25: Revision 1.173 2015/01/03 12:06:26 brouard
26: Summary: trying to detect cross-compilation
27:
1.173 brouard 28: Revision 1.172 2014/12/27 12:07:47 brouard
29: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
30:
1.172 brouard 31: Revision 1.171 2014/12/23 13:26:59 brouard
32: Summary: Back from Visual C
33:
34: Still problem with utsname.h on Windows
35:
1.171 brouard 36: Revision 1.170 2014/12/23 11:17:12 brouard
37: Summary: Cleaning some \%% back to %%
38:
39: The escape was mandatory for a specific compiler (which one?), but too many warnings.
40:
1.170 brouard 41: Revision 1.169 2014/12/22 23:08:31 brouard
42: Summary: 0.98p
43:
44: Outputs some informations on compiler used, OS etc. Testing on different platforms.
45:
1.169 brouard 46: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 47: Summary: update
1.169 brouard 48:
1.168 brouard 49: Revision 1.167 2014/12/22 13:50:56 brouard
50: Summary: Testing uname and compiler version and if compiled 32 or 64
51:
52: Testing on Linux 64
53:
1.167 brouard 54: Revision 1.166 2014/12/22 11:40:47 brouard
55: *** empty log message ***
56:
1.166 brouard 57: Revision 1.165 2014/12/16 11:20:36 brouard
58: Summary: After compiling on Visual C
59:
60: * imach.c (Module): Merging 1.61 to 1.162
61:
1.165 brouard 62: Revision 1.164 2014/12/16 10:52:11 brouard
63: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
64:
65: * imach.c (Module): Merging 1.61 to 1.162
66:
1.164 brouard 67: Revision 1.163 2014/12/16 10:30:11 brouard
68: * imach.c (Module): Merging 1.61 to 1.162
69:
1.163 brouard 70: Revision 1.162 2014/09/25 11:43:39 brouard
71: Summary: temporary backup 0.99!
72:
1.162 brouard 73: Revision 1.1 2014/09/16 11:06:58 brouard
74: Summary: With some code (wrong) for nlopt
75:
76: Author:
77:
78: Revision 1.161 2014/09/15 20:41:41 brouard
79: Summary: Problem with macro SQR on Intel compiler
80:
1.161 brouard 81: Revision 1.160 2014/09/02 09:24:05 brouard
82: *** empty log message ***
83:
1.160 brouard 84: Revision 1.159 2014/09/01 10:34:10 brouard
85: Summary: WIN32
86: Author: Brouard
87:
1.159 brouard 88: Revision 1.158 2014/08/27 17:11:51 brouard
89: *** empty log message ***
90:
1.158 brouard 91: Revision 1.157 2014/08/27 16:26:55 brouard
92: Summary: Preparing windows Visual studio version
93: Author: Brouard
94:
95: In order to compile on Visual studio, time.h is now correct and time_t
96: and tm struct should be used. difftime should be used but sometimes I
97: just make the differences in raw time format (time(&now).
98: Trying to suppress #ifdef LINUX
99: Add xdg-open for __linux in order to open default browser.
100:
1.157 brouard 101: Revision 1.156 2014/08/25 20:10:10 brouard
102: *** empty log message ***
103:
1.156 brouard 104: Revision 1.155 2014/08/25 18:32:34 brouard
105: Summary: New compile, minor changes
106: Author: Brouard
107:
1.155 brouard 108: Revision 1.154 2014/06/20 17:32:08 brouard
109: Summary: Outputs now all graphs of convergence to period prevalence
110:
1.154 brouard 111: Revision 1.153 2014/06/20 16:45:46 brouard
112: Summary: If 3 live state, convergence to period prevalence on same graph
113: Author: Brouard
114:
1.153 brouard 115: Revision 1.152 2014/06/18 17:54:09 brouard
116: Summary: open browser, use gnuplot on same dir than imach if not found in the path
117:
1.152 brouard 118: Revision 1.151 2014/06/18 16:43:30 brouard
119: *** empty log message ***
120:
1.151 brouard 121: Revision 1.150 2014/06/18 16:42:35 brouard
122: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
123: Author: brouard
124:
1.150 brouard 125: Revision 1.149 2014/06/18 15:51:14 brouard
126: Summary: Some fixes in parameter files errors
127: Author: Nicolas Brouard
128:
1.149 brouard 129: Revision 1.148 2014/06/17 17:38:48 brouard
130: Summary: Nothing new
131: Author: Brouard
132:
133: Just a new packaging for OS/X version 0.98nS
134:
1.148 brouard 135: Revision 1.147 2014/06/16 10:33:11 brouard
136: *** empty log message ***
137:
1.147 brouard 138: Revision 1.146 2014/06/16 10:20:28 brouard
139: Summary: Merge
140: Author: Brouard
141:
142: Merge, before building revised version.
143:
1.146 brouard 144: Revision 1.145 2014/06/10 21:23:15 brouard
145: Summary: Debugging with valgrind
146: Author: Nicolas Brouard
147:
148: Lot of changes in order to output the results with some covariates
149: After the Edimburgh REVES conference 2014, it seems mandatory to
150: improve the code.
151: No more memory valgrind error but a lot has to be done in order to
152: continue the work of splitting the code into subroutines.
153: Also, decodemodel has been improved. Tricode is still not
154: optimal. nbcode should be improved. Documentation has been added in
155: the source code.
156:
1.144 brouard 157: Revision 1.143 2014/01/26 09:45:38 brouard
158: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
159:
160: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
161: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
162:
1.143 brouard 163: Revision 1.142 2014/01/26 03:57:36 brouard
164: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
165:
166: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
167:
1.142 brouard 168: Revision 1.141 2014/01/26 02:42:01 brouard
169: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
170:
1.141 brouard 171: Revision 1.140 2011/09/02 10:37:54 brouard
172: Summary: times.h is ok with mingw32 now.
173:
1.140 brouard 174: Revision 1.139 2010/06/14 07:50:17 brouard
175: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
176: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
177:
1.139 brouard 178: Revision 1.138 2010/04/30 18:19:40 brouard
179: *** empty log message ***
180:
1.138 brouard 181: Revision 1.137 2010/04/29 18:11:38 brouard
182: (Module): Checking covariates for more complex models
183: than V1+V2. A lot of change to be done. Unstable.
184:
1.137 brouard 185: Revision 1.136 2010/04/26 20:30:53 brouard
186: (Module): merging some libgsl code. Fixing computation
187: of likelione (using inter/intrapolation if mle = 0) in order to
188: get same likelihood as if mle=1.
189: Some cleaning of code and comments added.
190:
1.136 brouard 191: Revision 1.135 2009/10/29 15:33:14 brouard
192: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
193:
1.135 brouard 194: Revision 1.134 2009/10/29 13:18:53 brouard
195: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
196:
1.134 brouard 197: Revision 1.133 2009/07/06 10:21:25 brouard
198: just nforces
199:
1.133 brouard 200: Revision 1.132 2009/07/06 08:22:05 brouard
201: Many tings
202:
1.132 brouard 203: Revision 1.131 2009/06/20 16:22:47 brouard
204: Some dimensions resccaled
205:
1.131 brouard 206: Revision 1.130 2009/05/26 06:44:34 brouard
207: (Module): Max Covariate is now set to 20 instead of 8. A
208: lot of cleaning with variables initialized to 0. Trying to make
209: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
210:
1.130 brouard 211: Revision 1.129 2007/08/31 13:49:27 lievre
212: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
213:
1.129 lievre 214: Revision 1.128 2006/06/30 13:02:05 brouard
215: (Module): Clarifications on computing e.j
216:
1.128 brouard 217: Revision 1.127 2006/04/28 18:11:50 brouard
218: (Module): Yes the sum of survivors was wrong since
219: imach-114 because nhstepm was no more computed in the age
220: loop. Now we define nhstepma in the age loop.
221: (Module): In order to speed up (in case of numerous covariates) we
222: compute health expectancies (without variances) in a first step
223: and then all the health expectancies with variances or standard
224: deviation (needs data from the Hessian matrices) which slows the
225: computation.
226: In the future we should be able to stop the program is only health
227: expectancies and graph are needed without standard deviations.
228:
1.127 brouard 229: Revision 1.126 2006/04/28 17:23:28 brouard
230: (Module): Yes the sum of survivors was wrong since
231: imach-114 because nhstepm was no more computed in the age
232: loop. Now we define nhstepma in the age loop.
233: Version 0.98h
234:
1.126 brouard 235: Revision 1.125 2006/04/04 15:20:31 lievre
236: Errors in calculation of health expectancies. Age was not initialized.
237: Forecasting file added.
238:
239: Revision 1.124 2006/03/22 17:13:53 lievre
240: Parameters are printed with %lf instead of %f (more numbers after the comma).
241: The log-likelihood is printed in the log file
242:
243: Revision 1.123 2006/03/20 10:52:43 brouard
244: * imach.c (Module): <title> changed, corresponds to .htm file
245: name. <head> headers where missing.
246:
247: * imach.c (Module): Weights can have a decimal point as for
248: English (a comma might work with a correct LC_NUMERIC environment,
249: otherwise the weight is truncated).
250: Modification of warning when the covariates values are not 0 or
251: 1.
252: Version 0.98g
253:
254: Revision 1.122 2006/03/20 09:45:41 brouard
255: (Module): Weights can have a decimal point as for
256: English (a comma might work with a correct LC_NUMERIC environment,
257: otherwise the weight is truncated).
258: Modification of warning when the covariates values are not 0 or
259: 1.
260: Version 0.98g
261:
262: Revision 1.121 2006/03/16 17:45:01 lievre
263: * imach.c (Module): Comments concerning covariates added
264:
265: * imach.c (Module): refinements in the computation of lli if
266: status=-2 in order to have more reliable computation if stepm is
267: not 1 month. Version 0.98f
268:
269: Revision 1.120 2006/03/16 15:10:38 lievre
270: (Module): refinements in the computation of lli if
271: status=-2 in order to have more reliable computation if stepm is
272: not 1 month. Version 0.98f
273:
274: Revision 1.119 2006/03/15 17:42:26 brouard
275: (Module): Bug if status = -2, the loglikelihood was
276: computed as likelihood omitting the logarithm. Version O.98e
277:
278: Revision 1.118 2006/03/14 18:20:07 brouard
279: (Module): varevsij Comments added explaining the second
280: table of variances if popbased=1 .
281: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
282: (Module): Function pstamp added
283: (Module): Version 0.98d
284:
285: Revision 1.117 2006/03/14 17:16:22 brouard
286: (Module): varevsij Comments added explaining the second
287: table of variances if popbased=1 .
288: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
289: (Module): Function pstamp added
290: (Module): Version 0.98d
291:
292: Revision 1.116 2006/03/06 10:29:27 brouard
293: (Module): Variance-covariance wrong links and
294: varian-covariance of ej. is needed (Saito).
295:
296: Revision 1.115 2006/02/27 12:17:45 brouard
297: (Module): One freematrix added in mlikeli! 0.98c
298:
299: Revision 1.114 2006/02/26 12:57:58 brouard
300: (Module): Some improvements in processing parameter
301: filename with strsep.
302:
303: Revision 1.113 2006/02/24 14:20:24 brouard
304: (Module): Memory leaks checks with valgrind and:
305: datafile was not closed, some imatrix were not freed and on matrix
306: allocation too.
307:
308: Revision 1.112 2006/01/30 09:55:26 brouard
309: (Module): Back to gnuplot.exe instead of wgnuplot.exe
310:
311: Revision 1.111 2006/01/25 20:38:18 brouard
312: (Module): Lots of cleaning and bugs added (Gompertz)
313: (Module): Comments can be added in data file. Missing date values
314: can be a simple dot '.'.
315:
316: Revision 1.110 2006/01/25 00:51:50 brouard
317: (Module): Lots of cleaning and bugs added (Gompertz)
318:
319: Revision 1.109 2006/01/24 19:37:15 brouard
320: (Module): Comments (lines starting with a #) are allowed in data.
321:
322: Revision 1.108 2006/01/19 18:05:42 lievre
323: Gnuplot problem appeared...
324: To be fixed
325:
326: Revision 1.107 2006/01/19 16:20:37 brouard
327: Test existence of gnuplot in imach path
328:
329: Revision 1.106 2006/01/19 13:24:36 brouard
330: Some cleaning and links added in html output
331:
332: Revision 1.105 2006/01/05 20:23:19 lievre
333: *** empty log message ***
334:
335: Revision 1.104 2005/09/30 16:11:43 lievre
336: (Module): sump fixed, loop imx fixed, and simplifications.
337: (Module): If the status is missing at the last wave but we know
338: that the person is alive, then we can code his/her status as -2
339: (instead of missing=-1 in earlier versions) and his/her
340: contributions to the likelihood is 1 - Prob of dying from last
341: health status (= 1-p13= p11+p12 in the easiest case of somebody in
342: the healthy state at last known wave). Version is 0.98
343:
344: Revision 1.103 2005/09/30 15:54:49 lievre
345: (Module): sump fixed, loop imx fixed, and simplifications.
346:
347: Revision 1.102 2004/09/15 17:31:30 brouard
348: Add the possibility to read data file including tab characters.
349:
350: Revision 1.101 2004/09/15 10:38:38 brouard
351: Fix on curr_time
352:
353: Revision 1.100 2004/07/12 18:29:06 brouard
354: Add version for Mac OS X. Just define UNIX in Makefile
355:
356: Revision 1.99 2004/06/05 08:57:40 brouard
357: *** empty log message ***
358:
359: Revision 1.98 2004/05/16 15:05:56 brouard
360: New version 0.97 . First attempt to estimate force of mortality
361: directly from the data i.e. without the need of knowing the health
362: state at each age, but using a Gompertz model: log u =a + b*age .
363: This is the basic analysis of mortality and should be done before any
364: other analysis, in order to test if the mortality estimated from the
365: cross-longitudinal survey is different from the mortality estimated
366: from other sources like vital statistic data.
367:
368: The same imach parameter file can be used but the option for mle should be -3.
369:
1.133 brouard 370: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 371: former routines in order to include the new code within the former code.
372:
373: The output is very simple: only an estimate of the intercept and of
374: the slope with 95% confident intervals.
375:
376: Current limitations:
377: A) Even if you enter covariates, i.e. with the
378: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
379: B) There is no computation of Life Expectancy nor Life Table.
380:
381: Revision 1.97 2004/02/20 13:25:42 lievre
382: Version 0.96d. Population forecasting command line is (temporarily)
383: suppressed.
384:
385: Revision 1.96 2003/07/15 15:38:55 brouard
386: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
387: rewritten within the same printf. Workaround: many printfs.
388:
389: Revision 1.95 2003/07/08 07:54:34 brouard
390: * imach.c (Repository):
391: (Repository): Using imachwizard code to output a more meaningful covariance
392: matrix (cov(a12,c31) instead of numbers.
393:
394: Revision 1.94 2003/06/27 13:00:02 brouard
395: Just cleaning
396:
397: Revision 1.93 2003/06/25 16:33:55 brouard
398: (Module): On windows (cygwin) function asctime_r doesn't
399: exist so I changed back to asctime which exists.
400: (Module): Version 0.96b
401:
402: Revision 1.92 2003/06/25 16:30:45 brouard
403: (Module): On windows (cygwin) function asctime_r doesn't
404: exist so I changed back to asctime which exists.
405:
406: Revision 1.91 2003/06/25 15:30:29 brouard
407: * imach.c (Repository): Duplicated warning errors corrected.
408: (Repository): Elapsed time after each iteration is now output. It
409: helps to forecast when convergence will be reached. Elapsed time
410: is stamped in powell. We created a new html file for the graphs
411: concerning matrix of covariance. It has extension -cov.htm.
412:
413: Revision 1.90 2003/06/24 12:34:15 brouard
414: (Module): Some bugs corrected for windows. Also, when
415: mle=-1 a template is output in file "or"mypar.txt with the design
416: of the covariance matrix to be input.
417:
418: Revision 1.89 2003/06/24 12:30:52 brouard
419: (Module): Some bugs corrected for windows. Also, when
420: mle=-1 a template is output in file "or"mypar.txt with the design
421: of the covariance matrix to be input.
422:
423: Revision 1.88 2003/06/23 17:54:56 brouard
424: * 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.
425:
426: Revision 1.87 2003/06/18 12:26:01 brouard
427: Version 0.96
428:
429: Revision 1.86 2003/06/17 20:04:08 brouard
430: (Module): Change position of html and gnuplot routines and added
431: routine fileappend.
432:
433: Revision 1.85 2003/06/17 13:12:43 brouard
434: * imach.c (Repository): Check when date of death was earlier that
435: current date of interview. It may happen when the death was just
436: prior to the death. In this case, dh was negative and likelihood
437: was wrong (infinity). We still send an "Error" but patch by
438: assuming that the date of death was just one stepm after the
439: interview.
440: (Repository): Because some people have very long ID (first column)
441: we changed int to long in num[] and we added a new lvector for
442: memory allocation. But we also truncated to 8 characters (left
443: truncation)
444: (Repository): No more line truncation errors.
445:
446: Revision 1.84 2003/06/13 21:44:43 brouard
447: * imach.c (Repository): Replace "freqsummary" at a correct
448: place. It differs from routine "prevalence" which may be called
449: many times. Probs is memory consuming and must be used with
450: parcimony.
451: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
452:
453: Revision 1.83 2003/06/10 13:39:11 lievre
454: *** empty log message ***
455:
456: Revision 1.82 2003/06/05 15:57:20 brouard
457: Add log in imach.c and fullversion number is now printed.
458:
459: */
460: /*
461: Interpolated Markov Chain
462:
463: Short summary of the programme:
464:
465: This program computes Healthy Life Expectancies from
466: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
467: first survey ("cross") where individuals from different ages are
468: interviewed on their health status or degree of disability (in the
469: case of a health survey which is our main interest) -2- at least a
470: second wave of interviews ("longitudinal") which measure each change
471: (if any) in individual health status. Health expectancies are
472: computed from the time spent in each health state according to a
473: model. More health states you consider, more time is necessary to reach the
474: Maximum Likelihood of the parameters involved in the model. The
475: simplest model is the multinomial logistic model where pij is the
476: probability to be observed in state j at the second wave
477: conditional to be observed in state i at the first wave. Therefore
478: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
479: 'age' is age and 'sex' is a covariate. If you want to have a more
480: complex model than "constant and age", you should modify the program
481: where the markup *Covariates have to be included here again* invites
482: you to do it. More covariates you add, slower the
483: convergence.
484:
485: The advantage of this computer programme, compared to a simple
486: multinomial logistic model, is clear when the delay between waves is not
487: identical for each individual. Also, if a individual missed an
488: intermediate interview, the information is lost, but taken into
489: account using an interpolation or extrapolation.
490:
491: hPijx is the probability to be observed in state i at age x+h
492: conditional to the observed state i at age x. The delay 'h' can be
493: split into an exact number (nh*stepm) of unobserved intermediate
494: states. This elementary transition (by month, quarter,
495: semester or year) is modelled as a multinomial logistic. The hPx
496: matrix is simply the matrix product of nh*stepm elementary matrices
497: and the contribution of each individual to the likelihood is simply
498: hPijx.
499:
500: Also this programme outputs the covariance matrix of the parameters but also
501: of the life expectancies. It also computes the period (stable) prevalence.
502:
1.133 brouard 503: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
504: Institut national d'études démographiques, Paris.
1.126 brouard 505: This software have been partly granted by Euro-REVES, a concerted action
506: from the European Union.
507: It is copyrighted identically to a GNU software product, ie programme and
508: software can be distributed freely for non commercial use. Latest version
509: can be accessed at http://euroreves.ined.fr/imach .
510:
511: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
512: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
513:
514: **********************************************************************/
515: /*
516: main
517: read parameterfile
518: read datafile
519: concatwav
520: freqsummary
521: if (mle >= 1)
522: mlikeli
523: print results files
524: if mle==1
525: computes hessian
526: read end of parameter file: agemin, agemax, bage, fage, estepm
527: begin-prev-date,...
528: open gnuplot file
529: open html file
1.145 brouard 530: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
531: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
532: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
533: freexexit2 possible for memory heap.
534:
535: h Pij x | pij_nom ficrestpij
536: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
537: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
538: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
539:
540: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
541: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
542: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
543: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
544: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
545:
1.126 brouard 546: forecasting if prevfcast==1 prevforecast call prevalence()
547: health expectancies
548: Variance-covariance of DFLE
549: prevalence()
550: movingaverage()
551: varevsij()
552: if popbased==1 varevsij(,popbased)
553: total life expectancies
554: Variance of period (stable) prevalence
555: end
556: */
557:
1.165 brouard 558: #define POWELL /* Instead of NLOPT */
1.181 ! brouard 559: #define POWELLDIRECT /* Directest to decide new direction instead of Powell test */
1.126 brouard 560:
561: #include <math.h>
562: #include <stdio.h>
563: #include <stdlib.h>
564: #include <string.h>
1.159 brouard 565:
566: #ifdef _WIN32
567: #include <io.h>
1.172 brouard 568: #include <windows.h>
569: #include <tchar.h>
1.159 brouard 570: #else
1.126 brouard 571: #include <unistd.h>
1.159 brouard 572: #endif
1.126 brouard 573:
574: #include <limits.h>
575: #include <sys/types.h>
1.171 brouard 576:
577: #if defined(__GNUC__)
578: #include <sys/utsname.h> /* Doesn't work on Windows */
579: #endif
580:
1.126 brouard 581: #include <sys/stat.h>
582: #include <errno.h>
1.159 brouard 583: /* extern int errno; */
1.126 brouard 584:
1.157 brouard 585: /* #ifdef LINUX */
586: /* #include <time.h> */
587: /* #include "timeval.h" */
588: /* #else */
589: /* #include <sys/time.h> */
590: /* #endif */
591:
1.126 brouard 592: #include <time.h>
593:
1.136 brouard 594: #ifdef GSL
595: #include <gsl/gsl_errno.h>
596: #include <gsl/gsl_multimin.h>
597: #endif
598:
1.167 brouard 599:
1.162 brouard 600: #ifdef NLOPT
601: #include <nlopt.h>
602: typedef struct {
603: double (* function)(double [] );
604: } myfunc_data ;
605: #endif
606:
1.126 brouard 607: /* #include <libintl.h> */
608: /* #define _(String) gettext (String) */
609:
1.141 brouard 610: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 611:
612: #define GNUPLOTPROGRAM "gnuplot"
613: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
614: #define FILENAMELENGTH 132
615:
616: #define GLOCK_ERROR_NOPATH -1 /* empty path */
617: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
618:
1.144 brouard 619: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
620: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 621:
622: #define NINTERVMAX 8
1.144 brouard 623: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
624: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
625: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 626: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 627: #define MAXN 20000
1.144 brouard 628: #define YEARM 12. /**< Number of months per year */
1.126 brouard 629: #define AGESUP 130
630: #define AGEBASE 40
1.164 brouard 631: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 632: #ifdef _WIN32
633: #define DIRSEPARATOR '\\'
634: #define CHARSEPARATOR "\\"
635: #define ODIRSEPARATOR '/'
636: #else
1.126 brouard 637: #define DIRSEPARATOR '/'
638: #define CHARSEPARATOR "/"
639: #define ODIRSEPARATOR '\\'
640: #endif
641:
1.181 ! brouard 642: /* $Id: imach.c,v 1.180 2015/02/11 17:33:45 brouard Exp $ */
1.126 brouard 643: /* $State: Exp $ */
644:
1.180 brouard 645: char version[]="Imach version 0.98p, Février 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.181 ! brouard 646: char fullversion[]="$Revision: 1.180 $ $Date: 2015/02/11 17:33:45 $";
1.126 brouard 647: char strstart[80];
648: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 649: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 650: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 651: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
652: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
653: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
654: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
655: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
656: int cptcovprodnoage=0; /**< Number of covariate products without age */
657: int cptcoveff=0; /* Total number of covariates to vary for printing results */
658: int cptcov=0; /* Working variable */
1.126 brouard 659: int npar=NPARMAX;
660: int nlstate=2; /* Number of live states */
661: int ndeath=1; /* Number of dead states */
1.130 brouard 662: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 663: int popbased=0;
664:
665: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 666: int maxwav=0; /* Maxim number of waves */
667: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
668: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
669: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 670: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 671: int mle=1, weightopt=0;
1.126 brouard 672: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
673: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
674: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
675: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 676: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 677: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 678: double **matprod2(); /* test */
1.126 brouard 679: double **oldm, **newm, **savm; /* Working pointers to matrices */
680: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 681: /*FILE *fic ; */ /* Used in readdata only */
682: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 683: FILE *ficlog, *ficrespow;
1.130 brouard 684: int globpr=0; /* Global variable for printing or not */
1.126 brouard 685: double fretone; /* Only one call to likelihood */
1.130 brouard 686: long ipmx=0; /* Number of contributions */
1.126 brouard 687: double sw; /* Sum of weights */
688: char filerespow[FILENAMELENGTH];
689: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
690: FILE *ficresilk;
691: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
692: FILE *ficresprobmorprev;
693: FILE *fichtm, *fichtmcov; /* Html File */
694: FILE *ficreseij;
695: char filerese[FILENAMELENGTH];
696: FILE *ficresstdeij;
697: char fileresstde[FILENAMELENGTH];
698: FILE *ficrescveij;
699: char filerescve[FILENAMELENGTH];
700: FILE *ficresvij;
701: char fileresv[FILENAMELENGTH];
702: FILE *ficresvpl;
703: char fileresvpl[FILENAMELENGTH];
704: char title[MAXLINE];
705: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
706: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
707: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
708: char command[FILENAMELENGTH];
709: int outcmd=0;
710:
711: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
712:
713: char filelog[FILENAMELENGTH]; /* Log file */
714: char filerest[FILENAMELENGTH];
715: char fileregp[FILENAMELENGTH];
716: char popfile[FILENAMELENGTH];
717:
718: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
719:
1.157 brouard 720: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
721: /* struct timezone tzp; */
722: /* extern int gettimeofday(); */
723: struct tm tml, *gmtime(), *localtime();
724:
725: extern time_t time();
726:
727: struct tm start_time, end_time, curr_time, last_time, forecast_time;
728: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
729: struct tm tm;
730:
1.126 brouard 731: char strcurr[80], strfor[80];
732:
733: char *endptr;
734: long lval;
735: double dval;
736:
737: #define NR_END 1
738: #define FREE_ARG char*
739: #define FTOL 1.0e-10
740:
741: #define NRANSI
742: #define ITMAX 200
743:
744: #define TOL 2.0e-4
745:
746: #define CGOLD 0.3819660
747: #define ZEPS 1.0e-10
748: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
749:
750: #define GOLD 1.618034
751: #define GLIMIT 100.0
752: #define TINY 1.0e-20
753:
754: static double maxarg1,maxarg2;
755: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
756: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
757:
758: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
759: #define rint(a) floor(a+0.5)
1.166 brouard 760: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
761: /* #define mytinydouble 1.0e-16 */
762: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
763: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
764: /* static double dsqrarg; */
765: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 766: static double sqrarg;
767: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
768: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
769: int agegomp= AGEGOMP;
770:
771: int imx;
772: int stepm=1;
773: /* Stepm, step in month: minimum step interpolation*/
774:
775: int estepm;
776: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
777:
778: int m,nb;
779: long *num;
780: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
781: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
782: double **pmmij, ***probs;
783: double *ageexmed,*agecens;
784: double dateintmean=0;
785:
786: double *weight;
787: int **s; /* Status */
1.141 brouard 788: double *agedc;
1.145 brouard 789: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 790: * covar=matrix(0,NCOVMAX,1,n);
791: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
792: double idx;
793: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 794: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 795: int **codtab; /**< codtab=imatrix(1,100,1,10); */
796: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 797: double *lsurv, *lpop, *tpop;
798:
1.143 brouard 799: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
800: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 801:
802: /**************** split *************************/
803: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
804: {
805: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
806: the name of the file (name), its extension only (ext) and its first part of the name (finame)
807: */
808: char *ss; /* pointer */
809: int l1, l2; /* length counters */
810:
811: l1 = strlen(path ); /* length of path */
812: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
813: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
814: if ( ss == NULL ) { /* no directory, so determine current directory */
815: strcpy( name, path ); /* we got the fullname name because no directory */
816: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
817: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
818: /* get current working directory */
819: /* extern char* getcwd ( char *buf , int len);*/
820: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
821: return( GLOCK_ERROR_GETCWD );
822: }
823: /* got dirc from getcwd*/
824: printf(" DIRC = %s \n",dirc);
825: } else { /* strip direcotry from path */
826: ss++; /* after this, the filename */
827: l2 = strlen( ss ); /* length of filename */
828: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
829: strcpy( name, ss ); /* save file name */
830: strncpy( dirc, path, l1 - l2 ); /* now the directory */
831: dirc[l1-l2] = 0; /* add zero */
832: printf(" DIRC2 = %s \n",dirc);
833: }
834: /* We add a separator at the end of dirc if not exists */
835: l1 = strlen( dirc ); /* length of directory */
836: if( dirc[l1-1] != DIRSEPARATOR ){
837: dirc[l1] = DIRSEPARATOR;
838: dirc[l1+1] = 0;
839: printf(" DIRC3 = %s \n",dirc);
840: }
841: ss = strrchr( name, '.' ); /* find last / */
842: if (ss >0){
843: ss++;
844: strcpy(ext,ss); /* save extension */
845: l1= strlen( name);
846: l2= strlen(ss)+1;
847: strncpy( finame, name, l1-l2);
848: finame[l1-l2]= 0;
849: }
850:
851: return( 0 ); /* we're done */
852: }
853:
854:
855: /******************************************/
856:
857: void replace_back_to_slash(char *s, char*t)
858: {
859: int i;
860: int lg=0;
861: i=0;
862: lg=strlen(t);
863: for(i=0; i<= lg; i++) {
864: (s[i] = t[i]);
865: if (t[i]== '\\') s[i]='/';
866: }
867: }
868:
1.132 brouard 869: char *trimbb(char *out, char *in)
1.137 brouard 870: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 871: char *s;
872: s=out;
873: while (*in != '\0'){
1.137 brouard 874: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 875: in++;
876: }
877: *out++ = *in++;
878: }
879: *out='\0';
880: return s;
881: }
882:
1.145 brouard 883: char *cutl(char *blocc, char *alocc, char *in, char occ)
884: {
885: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
886: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
887: gives blocc="abcdef2ghi" and alocc="j".
888: If occ is not found blocc is null and alocc is equal to in. Returns blocc
889: */
1.160 brouard 890: char *s, *t;
1.145 brouard 891: t=in;s=in;
892: while ((*in != occ) && (*in != '\0')){
893: *alocc++ = *in++;
894: }
895: if( *in == occ){
896: *(alocc)='\0';
897: s=++in;
898: }
899:
900: if (s == t) {/* occ not found */
901: *(alocc-(in-s))='\0';
902: in=s;
903: }
904: while ( *in != '\0'){
905: *blocc++ = *in++;
906: }
907:
908: *blocc='\0';
909: return t;
910: }
1.137 brouard 911: char *cutv(char *blocc, char *alocc, char *in, char occ)
912: {
913: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
914: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
915: gives blocc="abcdef2ghi" and alocc="j".
916: If occ is not found blocc is null and alocc is equal to in. Returns alocc
917: */
918: char *s, *t;
919: t=in;s=in;
920: while (*in != '\0'){
921: while( *in == occ){
922: *blocc++ = *in++;
923: s=in;
924: }
925: *blocc++ = *in++;
926: }
927: if (s == t) /* occ not found */
928: *(blocc-(in-s))='\0';
929: else
930: *(blocc-(in-s)-1)='\0';
931: in=s;
932: while ( *in != '\0'){
933: *alocc++ = *in++;
934: }
935:
936: *alocc='\0';
937: return s;
938: }
939:
1.126 brouard 940: int nbocc(char *s, char occ)
941: {
942: int i,j=0;
943: int lg=20;
944: i=0;
945: lg=strlen(s);
946: for(i=0; i<= lg; i++) {
947: if (s[i] == occ ) j++;
948: }
949: return j;
950: }
951:
1.137 brouard 952: /* void cutv(char *u,char *v, char*t, char occ) */
953: /* { */
954: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
955: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
956: /* gives u="abcdef2ghi" and v="j" *\/ */
957: /* int i,lg,j,p=0; */
958: /* i=0; */
959: /* lg=strlen(t); */
960: /* for(j=0; j<=lg-1; j++) { */
961: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
962: /* } */
1.126 brouard 963:
1.137 brouard 964: /* for(j=0; j<p; j++) { */
965: /* (u[j] = t[j]); */
966: /* } */
967: /* u[p]='\0'; */
1.126 brouard 968:
1.137 brouard 969: /* for(j=0; j<= lg; j++) { */
970: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
971: /* } */
972: /* } */
1.126 brouard 973:
1.160 brouard 974: #ifdef _WIN32
975: char * strsep(char **pp, const char *delim)
976: {
977: char *p, *q;
978:
979: if ((p = *pp) == NULL)
980: return 0;
981: if ((q = strpbrk (p, delim)) != NULL)
982: {
983: *pp = q + 1;
984: *q = '\0';
985: }
986: else
987: *pp = 0;
988: return p;
989: }
990: #endif
991:
1.126 brouard 992: /********************** nrerror ********************/
993:
994: void nrerror(char error_text[])
995: {
996: fprintf(stderr,"ERREUR ...\n");
997: fprintf(stderr,"%s\n",error_text);
998: exit(EXIT_FAILURE);
999: }
1000: /*********************** vector *******************/
1001: double *vector(int nl, int nh)
1002: {
1003: double *v;
1004: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1005: if (!v) nrerror("allocation failure in vector");
1006: return v-nl+NR_END;
1007: }
1008:
1009: /************************ free vector ******************/
1010: void free_vector(double*v, int nl, int nh)
1011: {
1012: free((FREE_ARG)(v+nl-NR_END));
1013: }
1014:
1015: /************************ivector *******************************/
1016: int *ivector(long nl,long nh)
1017: {
1018: int *v;
1019: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1020: if (!v) nrerror("allocation failure in ivector");
1021: return v-nl+NR_END;
1022: }
1023:
1024: /******************free ivector **************************/
1025: void free_ivector(int *v, long nl, long nh)
1026: {
1027: free((FREE_ARG)(v+nl-NR_END));
1028: }
1029:
1030: /************************lvector *******************************/
1031: long *lvector(long nl,long nh)
1032: {
1033: long *v;
1034: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1035: if (!v) nrerror("allocation failure in ivector");
1036: return v-nl+NR_END;
1037: }
1038:
1039: /******************free lvector **************************/
1040: void free_lvector(long *v, long nl, long nh)
1041: {
1042: free((FREE_ARG)(v+nl-NR_END));
1043: }
1044:
1045: /******************* imatrix *******************************/
1046: int **imatrix(long nrl, long nrh, long ncl, long nch)
1047: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1048: {
1049: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1050: int **m;
1051:
1052: /* allocate pointers to rows */
1053: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1054: if (!m) nrerror("allocation failure 1 in matrix()");
1055: m += NR_END;
1056: m -= nrl;
1057:
1058:
1059: /* allocate rows and set pointers to them */
1060: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1061: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1062: m[nrl] += NR_END;
1063: m[nrl] -= ncl;
1064:
1065: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1066:
1067: /* return pointer to array of pointers to rows */
1068: return m;
1069: }
1070:
1071: /****************** free_imatrix *************************/
1072: void free_imatrix(m,nrl,nrh,ncl,nch)
1073: int **m;
1074: long nch,ncl,nrh,nrl;
1075: /* free an int matrix allocated by imatrix() */
1076: {
1077: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1078: free((FREE_ARG) (m+nrl-NR_END));
1079: }
1080:
1081: /******************* matrix *******************************/
1082: double **matrix(long nrl, long nrh, long ncl, long nch)
1083: {
1084: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1085: double **m;
1086:
1087: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1088: if (!m) nrerror("allocation failure 1 in matrix()");
1089: m += NR_END;
1090: m -= nrl;
1091:
1092: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1093: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1094: m[nrl] += NR_END;
1095: m[nrl] -= ncl;
1096:
1097: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1098: return m;
1.145 brouard 1099: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1100: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1101: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1102: */
1103: }
1104:
1105: /*************************free matrix ************************/
1106: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1107: {
1108: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1109: free((FREE_ARG)(m+nrl-NR_END));
1110: }
1111:
1112: /******************* ma3x *******************************/
1113: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1114: {
1115: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1116: double ***m;
1117:
1118: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1119: if (!m) nrerror("allocation failure 1 in matrix()");
1120: m += NR_END;
1121: m -= nrl;
1122:
1123: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1124: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1125: m[nrl] += NR_END;
1126: m[nrl] -= ncl;
1127:
1128: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1129:
1130: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1131: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1132: m[nrl][ncl] += NR_END;
1133: m[nrl][ncl] -= nll;
1134: for (j=ncl+1; j<=nch; j++)
1135: m[nrl][j]=m[nrl][j-1]+nlay;
1136:
1137: for (i=nrl+1; i<=nrh; i++) {
1138: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1139: for (j=ncl+1; j<=nch; j++)
1140: m[i][j]=m[i][j-1]+nlay;
1141: }
1142: return m;
1143: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1144: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1145: */
1146: }
1147:
1148: /*************************free ma3x ************************/
1149: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1150: {
1151: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1152: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1153: free((FREE_ARG)(m+nrl-NR_END));
1154: }
1155:
1156: /*************** function subdirf ***********/
1157: char *subdirf(char fileres[])
1158: {
1159: /* Caution optionfilefiname is hidden */
1160: strcpy(tmpout,optionfilefiname);
1161: strcat(tmpout,"/"); /* Add to the right */
1162: strcat(tmpout,fileres);
1163: return tmpout;
1164: }
1165:
1166: /*************** function subdirf2 ***********/
1167: char *subdirf2(char fileres[], char *preop)
1168: {
1169:
1170: /* Caution optionfilefiname is hidden */
1171: strcpy(tmpout,optionfilefiname);
1172: strcat(tmpout,"/");
1173: strcat(tmpout,preop);
1174: strcat(tmpout,fileres);
1175: return tmpout;
1176: }
1177:
1178: /*************** function subdirf3 ***********/
1179: char *subdirf3(char fileres[], char *preop, char *preop2)
1180: {
1181:
1182: /* Caution optionfilefiname is hidden */
1183: strcpy(tmpout,optionfilefiname);
1184: strcat(tmpout,"/");
1185: strcat(tmpout,preop);
1186: strcat(tmpout,preop2);
1187: strcat(tmpout,fileres);
1188: return tmpout;
1189: }
1190:
1.162 brouard 1191: char *asc_diff_time(long time_sec, char ascdiff[])
1192: {
1193: long sec_left, days, hours, minutes;
1194: days = (time_sec) / (60*60*24);
1195: sec_left = (time_sec) % (60*60*24);
1196: hours = (sec_left) / (60*60) ;
1197: sec_left = (sec_left) %(60*60);
1198: minutes = (sec_left) /60;
1199: sec_left = (sec_left) % (60);
1200: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1201: return ascdiff;
1202: }
1203:
1.126 brouard 1204: /***************** f1dim *************************/
1205: extern int ncom;
1206: extern double *pcom,*xicom;
1207: extern double (*nrfunc)(double []);
1208:
1209: double f1dim(double x)
1210: {
1211: int j;
1212: double f;
1213: double *xt;
1214:
1215: xt=vector(1,ncom);
1216: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1217: f=(*nrfunc)(xt);
1218: free_vector(xt,1,ncom);
1219: return f;
1220: }
1221:
1222: /*****************brent *************************/
1223: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1224: {
1225: int iter;
1226: double a,b,d,etemp;
1.159 brouard 1227: double fu=0,fv,fw,fx;
1.164 brouard 1228: double ftemp=0.;
1.126 brouard 1229: double p,q,r,tol1,tol2,u,v,w,x,xm;
1230: double e=0.0;
1231:
1232: a=(ax < cx ? ax : cx);
1233: b=(ax > cx ? ax : cx);
1234: x=w=v=bx;
1235: fw=fv=fx=(*f)(x);
1236: for (iter=1;iter<=ITMAX;iter++) {
1237: xm=0.5*(a+b);
1238: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1239: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1240: printf(".");fflush(stdout);
1241: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1242: #ifdef DEBUGBRENT
1.126 brouard 1243: 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);
1244: 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);
1245: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1246: #endif
1247: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1248: *xmin=x;
1249: return fx;
1250: }
1251: ftemp=fu;
1252: if (fabs(e) > tol1) {
1253: r=(x-w)*(fx-fv);
1254: q=(x-v)*(fx-fw);
1255: p=(x-v)*q-(x-w)*r;
1256: q=2.0*(q-r);
1257: if (q > 0.0) p = -p;
1258: q=fabs(q);
1259: etemp=e;
1260: e=d;
1261: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1262: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1263: else {
1264: d=p/q;
1265: u=x+d;
1266: if (u-a < tol2 || b-u < tol2)
1267: d=SIGN(tol1,xm-x);
1268: }
1269: } else {
1270: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1271: }
1272: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1273: fu=(*f)(u);
1274: if (fu <= fx) {
1275: if (u >= x) a=x; else b=x;
1276: SHFT(v,w,x,u)
1277: SHFT(fv,fw,fx,fu)
1278: } else {
1279: if (u < x) a=u; else b=u;
1280: if (fu <= fw || w == x) {
1281: v=w;
1282: w=u;
1283: fv=fw;
1284: fw=fu;
1285: } else if (fu <= fv || v == x || v == w) {
1286: v=u;
1287: fv=fu;
1288: }
1289: }
1290: }
1291: nrerror("Too many iterations in brent");
1292: *xmin=x;
1293: return fx;
1294: }
1295:
1296: /****************** mnbrak ***********************/
1297:
1298: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1299: double (*func)(double))
1300: {
1301: double ulim,u,r,q, dum;
1302: double fu;
1303:
1304: *fa=(*func)(*ax);
1305: *fb=(*func)(*bx);
1306: if (*fb > *fa) {
1307: SHFT(dum,*ax,*bx,dum)
1308: SHFT(dum,*fb,*fa,dum)
1309: }
1310: *cx=(*bx)+GOLD*(*bx-*ax);
1311: *fc=(*func)(*cx);
1.162 brouard 1312: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1313: r=(*bx-*ax)*(*fb-*fc);
1314: q=(*bx-*cx)*(*fb-*fa);
1315: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1316: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1317: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1318: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1319: fu=(*func)(u);
1.163 brouard 1320: #ifdef DEBUG
1321: /* f(x)=A(x-u)**2+f(u) */
1322: double A, fparabu;
1323: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1324: fparabu= *fa - A*(*ax-u)*(*ax-u);
1325: 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);
1326: 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);
1327: #endif
1.162 brouard 1328: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1329: fu=(*func)(u);
1330: if (fu < *fc) {
1331: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1332: SHFT(*fb,*fc,fu,(*func)(u))
1333: }
1.162 brouard 1334: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1335: u=ulim;
1336: fu=(*func)(u);
1337: } else {
1338: u=(*cx)+GOLD*(*cx-*bx);
1339: fu=(*func)(u);
1340: }
1341: SHFT(*ax,*bx,*cx,u)
1342: SHFT(*fa,*fb,*fc,fu)
1343: }
1344: }
1345:
1346: /*************** linmin ************************/
1.162 brouard 1347: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1348: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1349: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1350: the value of func at the returned location p . This is actually all accomplished by calling the
1351: routines mnbrak and brent .*/
1.126 brouard 1352: int ncom;
1353: double *pcom,*xicom;
1354: double (*nrfunc)(double []);
1355:
1356: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1357: {
1358: double brent(double ax, double bx, double cx,
1359: double (*f)(double), double tol, double *xmin);
1360: double f1dim(double x);
1361: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1362: double *fc, double (*func)(double));
1363: int j;
1364: double xx,xmin,bx,ax;
1365: double fx,fb,fa;
1366:
1367: ncom=n;
1368: pcom=vector(1,n);
1369: xicom=vector(1,n);
1370: nrfunc=func;
1371: for (j=1;j<=n;j++) {
1372: pcom[j]=p[j];
1373: xicom[j]=xi[j];
1374: }
1375: ax=0.0;
1376: xx=1.0;
1.162 brouard 1377: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1378: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1.126 brouard 1379: #ifdef DEBUG
1380: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1381: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1382: #endif
1383: for (j=1;j<=n;j++) {
1384: xi[j] *= xmin;
1385: p[j] += xi[j];
1386: }
1387: free_vector(xicom,1,n);
1388: free_vector(pcom,1,n);
1389: }
1390:
1391:
1392: /*************** powell ************************/
1.162 brouard 1393: /*
1394: Minimization of a function func of n variables. Input consists of an initial starting point
1395: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1396: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1397: such that failure to decrease by more than this amount on one iteration signals doneness. On
1398: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1399: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1400: */
1.126 brouard 1401: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1402: double (*func)(double []))
1403: {
1404: void linmin(double p[], double xi[], int n, double *fret,
1405: double (*func)(double []));
1406: int i,ibig,j;
1407: double del,t,*pt,*ptt,*xit;
1.181 ! brouard 1408: double directest;
1.126 brouard 1409: double fp,fptt;
1410: double *xits;
1411: int niterf, itmp;
1412:
1413: pt=vector(1,n);
1414: ptt=vector(1,n);
1415: xit=vector(1,n);
1416: xits=vector(1,n);
1417: *fret=(*func)(p);
1418: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1419: rcurr_time = time(NULL);
1.126 brouard 1420: for (*iter=1;;++(*iter)) {
1421: fp=(*fret);
1422: ibig=0;
1423: del=0.0;
1.157 brouard 1424: rlast_time=rcurr_time;
1425: /* (void) gettimeofday(&curr_time,&tzp); */
1426: rcurr_time = time(NULL);
1427: curr_time = *localtime(&rcurr_time);
1428: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1429: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1430: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1431: for (i=1;i<=n;i++) {
1432: printf(" %d %.12f",i, p[i]);
1433: fprintf(ficlog," %d %.12lf",i, p[i]);
1434: fprintf(ficrespow," %.12lf", p[i]);
1435: }
1436: printf("\n");
1437: fprintf(ficlog,"\n");
1438: fprintf(ficrespow,"\n");fflush(ficrespow);
1439: if(*iter <=3){
1.157 brouard 1440: tml = *localtime(&rcurr_time);
1441: strcpy(strcurr,asctime(&tml));
1442: rforecast_time=rcurr_time;
1.126 brouard 1443: itmp = strlen(strcurr);
1444: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1445: strcurr[itmp-1]='\0';
1.162 brouard 1446: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1447: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1448: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1449: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1450: forecast_time = *localtime(&rforecast_time);
1451: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1452: itmp = strlen(strfor);
1453: if(strfor[itmp-1]=='\n')
1454: strfor[itmp-1]='\0';
1.157 brouard 1455: 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);
1456: 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);
1.126 brouard 1457: }
1458: }
1459: for (i=1;i<=n;i++) {
1460: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1461: fptt=(*fret);
1462: #ifdef DEBUG
1.164 brouard 1463: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1464: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1465: #endif
1466: printf("%d",i);fflush(stdout);
1467: fprintf(ficlog,"%d",i);fflush(ficlog);
1468: linmin(p,xit,n,fret,func);
1.181 ! brouard 1469: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
! 1470: because that direction will be replaced unless the gain del is small
! 1471: in comparison with the 'probable' gain, mu^2, with the last average direction.
! 1472: Unless the n directions are conjugate some gain in the determinant may be obtained
! 1473: with the new direction.
! 1474: */
1.126 brouard 1475: del=fabs(fptt-(*fret));
1476: ibig=i;
1477: }
1478: #ifdef DEBUG
1479: printf("%d %.12e",i,(*fret));
1480: fprintf(ficlog,"%d %.12e",i,(*fret));
1481: for (j=1;j<=n;j++) {
1482: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1483: printf(" x(%d)=%.12e",j,xit[j]);
1484: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1485: }
1486: for(j=1;j<=n;j++) {
1.162 brouard 1487: printf(" p(%d)=%.12e",j,p[j]);
1488: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1489: }
1490: printf("\n");
1491: fprintf(ficlog,"\n");
1492: #endif
1.162 brouard 1493: } /* end i */
1.126 brouard 1494: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1495: #ifdef DEBUG
1496: int k[2],l;
1497: k[0]=1;
1498: k[1]=-1;
1499: printf("Max: %.12e",(*func)(p));
1500: fprintf(ficlog,"Max: %.12e",(*func)(p));
1501: for (j=1;j<=n;j++) {
1502: printf(" %.12e",p[j]);
1503: fprintf(ficlog," %.12e",p[j]);
1504: }
1505: printf("\n");
1506: fprintf(ficlog,"\n");
1507: for(l=0;l<=1;l++) {
1508: for (j=1;j<=n;j++) {
1509: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1510: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1511: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1512: }
1513: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1514: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1515: }
1516: #endif
1517:
1518:
1519: free_vector(xit,1,n);
1520: free_vector(xits,1,n);
1521: free_vector(ptt,1,n);
1522: free_vector(pt,1,n);
1523: return;
1524: }
1525: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 ! brouard 1526: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1527: ptt[j]=2.0*p[j]-pt[j];
1528: xit[j]=p[j]-pt[j];
1529: pt[j]=p[j];
1530: }
1.181 ! brouard 1531: fptt=(*func)(ptt); /* f_3 */
1.161 brouard 1532: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1533: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1534: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1535: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1536: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1537: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 ! brouard 1538: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1539: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1540:
1.161 brouard 1541: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1542: t= t- del*SQR(fp-fptt);
1.181 ! brouard 1543: directest = SQR(fp-2.0*(*fret)+fptt) - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1544: #ifdef DEBUG
1.181 ! brouard 1545: 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);
! 1546: 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);
1.161 brouard 1547: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1548: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1549: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1550: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1551: 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);
1552: 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);
1553: #endif
1.181 ! brouard 1554: #ifdef POWELLDIRECT
! 1555: if (directest < 0.0) { /* Then we use it for new direction */
! 1556: #else
! 1557: if (t < 0.0) { /* Then we use it for new direction */
! 1558: #endif
! 1559: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1.126 brouard 1560: for (j=1;j<=n;j++) {
1.181 ! brouard 1561: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
! 1562: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1563: }
1.181 ! brouard 1564: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
! 1565: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1566:
1.126 brouard 1567: #ifdef DEBUG
1.164 brouard 1568: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1569: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1570: for(j=1;j<=n;j++){
1571: printf(" %.12e",xit[j]);
1572: fprintf(ficlog," %.12e",xit[j]);
1573: }
1574: printf("\n");
1575: fprintf(ficlog,"\n");
1576: #endif
1.162 brouard 1577: } /* end of t negative */
1578: } /* end if (fptt < fp) */
1.126 brouard 1579: }
1580: }
1581:
1582: /**** Prevalence limit (stable or period prevalence) ****************/
1583:
1584: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1585: {
1586: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1587: matrix by transitions matrix until convergence is reached */
1.169 brouard 1588:
1.126 brouard 1589: int i, ii,j,k;
1590: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1591: /* double **matprod2(); */ /* test */
1.131 brouard 1592: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1593: double **newm;
1594: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1595:
1.126 brouard 1596: for (ii=1;ii<=nlstate+ndeath;ii++)
1597: for (j=1;j<=nlstate+ndeath;j++){
1598: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1599: }
1.169 brouard 1600:
1601: cov[1]=1.;
1602:
1603: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1604: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1605: newm=savm;
1606: /* Covariates have to be included here again */
1.138 brouard 1607: cov[2]=agefin;
1608:
1609: for (k=1; k<=cptcovn;k++) {
1610: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1611: /*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]]);*/
1.138 brouard 1612: }
1.145 brouard 1613: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1614: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1615: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1.138 brouard 1616:
1617: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1618: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1619: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1620: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1621: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1622: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1623:
1.126 brouard 1624: savm=oldm;
1625: oldm=newm;
1626: maxmax=0.;
1627: for(j=1;j<=nlstate;j++){
1628: min=1.;
1629: max=0.;
1630: for(i=1; i<=nlstate; i++) {
1631: sumnew=0;
1632: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1633: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1634: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1.126 brouard 1635: max=FMAX(max,prlim[i][j]);
1636: min=FMIN(min,prlim[i][j]);
1637: }
1638: maxmin=max-min;
1639: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1640: } /* j loop */
1.126 brouard 1641: if(maxmax < ftolpl){
1642: return prlim;
1643: }
1.169 brouard 1644: } /* age loop */
1645: return prlim; /* should not reach here */
1.126 brouard 1646: }
1647:
1648: /*************** transition probabilities ***************/
1649:
1650: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1651: {
1.138 brouard 1652: /* According to parameters values stored in x and the covariate's values stored in cov,
1653: computes the probability to be observed in state j being in state i by appying the
1654: model to the ncovmodel covariates (including constant and age).
1655: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1656: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1657: ncth covariate in the global vector x is given by the formula:
1658: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1659: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1660: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1661: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1662: Outputs ps[i][j] the probability to be observed in j being in j according to
1663: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1664: */
1665: double s1, lnpijopii;
1.126 brouard 1666: /*double t34;*/
1.164 brouard 1667: int i,j, nc, ii, jj;
1.126 brouard 1668:
1669: for(i=1; i<= nlstate; i++){
1670: for(j=1; j<i;j++){
1.138 brouard 1671: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1672: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1673: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1674: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1675: }
1.138 brouard 1676: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1677: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1678: }
1679: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1680: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1681: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1682: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1683: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1684: }
1.138 brouard 1685: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1686: }
1687: }
1688:
1689: for(i=1; i<= nlstate; i++){
1690: s1=0;
1.131 brouard 1691: for(j=1; j<i; j++){
1.138 brouard 1692: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1693: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1694: }
1695: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1696: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1697: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1698: }
1.138 brouard 1699: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1700: ps[i][i]=1./(s1+1.);
1.138 brouard 1701: /* Computing other pijs */
1.126 brouard 1702: for(j=1; j<i; j++)
1703: ps[i][j]= exp(ps[i][j])*ps[i][i];
1704: for(j=i+1; j<=nlstate+ndeath; j++)
1705: ps[i][j]= exp(ps[i][j])*ps[i][i];
1706: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1707: } /* end i */
1708:
1709: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1710: for(jj=1; jj<= nlstate+ndeath; jj++){
1711: ps[ii][jj]=0;
1712: ps[ii][ii]=1;
1713: }
1714: }
1715:
1.145 brouard 1716:
1717: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1718: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1719: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1720: /* } */
1721: /* printf("\n "); */
1722: /* } */
1723: /* printf("\n ");printf("%lf ",cov[2]);*/
1724: /*
1.126 brouard 1725: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1726: goto end;*/
1727: return ps;
1728: }
1729:
1730: /**************** Product of 2 matrices ******************/
1731:
1.145 brouard 1732: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1733: {
1734: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1735: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1736: /* in, b, out are matrice of pointers which should have been initialized
1737: before: only the contents of out is modified. The function returns
1738: a pointer to pointers identical to out */
1.145 brouard 1739: int i, j, k;
1.126 brouard 1740: for(i=nrl; i<= nrh; i++)
1.145 brouard 1741: for(k=ncolol; k<=ncoloh; k++){
1742: out[i][k]=0.;
1743: for(j=ncl; j<=nch; j++)
1744: out[i][k] +=in[i][j]*b[j][k];
1745: }
1.126 brouard 1746: return out;
1747: }
1748:
1749:
1750: /************* Higher Matrix Product ***************/
1751:
1752: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1753: {
1754: /* Computes the transition matrix starting at age 'age' over
1755: 'nhstepm*hstepm*stepm' months (i.e. until
1756: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1757: nhstepm*hstepm matrices.
1758: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1759: (typically every 2 years instead of every month which is too big
1760: for the memory).
1761: Model is determined by parameters x and covariates have to be
1762: included manually here.
1763:
1764: */
1765:
1766: int i, j, d, h, k;
1.131 brouard 1767: double **out, cov[NCOVMAX+1];
1.126 brouard 1768: double **newm;
1769:
1770: /* Hstepm could be zero and should return the unit matrix */
1771: for (i=1;i<=nlstate+ndeath;i++)
1772: for (j=1;j<=nlstate+ndeath;j++){
1773: oldm[i][j]=(i==j ? 1.0 : 0.0);
1774: po[i][j][0]=(i==j ? 1.0 : 0.0);
1775: }
1776: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1777: for(h=1; h <=nhstepm; h++){
1778: for(d=1; d <=hstepm; d++){
1779: newm=savm;
1780: /* Covariates have to be included here again */
1781: cov[1]=1.;
1782: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1783: for (k=1; k<=cptcovn;k++)
1784: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1785: for (k=1; k<=cptcovage;k++)
1786: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1787: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1788: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1789:
1790:
1791: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1792: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1793: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1794: pmij(pmmij,cov,ncovmodel,x,nlstate));
1795: savm=oldm;
1796: oldm=newm;
1797: }
1798: for(i=1; i<=nlstate+ndeath; i++)
1799: for(j=1;j<=nlstate+ndeath;j++) {
1800: po[i][j][h]=newm[i][j];
1.128 brouard 1801: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1802: }
1.128 brouard 1803: /*printf("h=%d ",h);*/
1.126 brouard 1804: } /* end h */
1.128 brouard 1805: /* printf("\n H=%d \n",h); */
1.126 brouard 1806: return po;
1807: }
1808:
1.162 brouard 1809: #ifdef NLOPT
1810: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1811: double fret;
1812: double *xt;
1813: int j;
1814: myfunc_data *d2 = (myfunc_data *) pd;
1815: /* xt = (p1-1); */
1816: xt=vector(1,n);
1817: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1818:
1819: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1820: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1821: printf("Function = %.12lf ",fret);
1822: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1823: printf("\n");
1824: free_vector(xt,1,n);
1825: return fret;
1826: }
1827: #endif
1.126 brouard 1828:
1829: /*************** log-likelihood *************/
1830: double func( double *x)
1831: {
1832: int i, ii, j, k, mi, d, kk;
1.131 brouard 1833: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1834: double **out;
1835: double sw; /* Sum of weights */
1836: double lli; /* Individual log likelihood */
1837: int s1, s2;
1838: double bbh, survp;
1839: long ipmx;
1840: /*extern weight */
1841: /* We are differentiating ll according to initial status */
1842: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1843: /*for(i=1;i<imx;i++)
1844: printf(" %d\n",s[4][i]);
1845: */
1.162 brouard 1846:
1847: ++countcallfunc;
1848:
1.126 brouard 1849: cov[1]=1.;
1850:
1851: for(k=1; k<=nlstate; k++) ll[k]=0.;
1852:
1853: if(mle==1){
1854: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1855: /* Computes the values of the ncovmodel covariates of the model
1856: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1857: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1858: to be observed in j being in i according to the model.
1859: */
1.145 brouard 1860: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1861: cov[2+k]=covar[Tvar[k]][i];
1862: }
1.137 brouard 1863: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1864: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1865: has been calculated etc */
1.126 brouard 1866: for(mi=1; mi<= wav[i]-1; mi++){
1867: for (ii=1;ii<=nlstate+ndeath;ii++)
1868: for (j=1;j<=nlstate+ndeath;j++){
1869: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1870: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1871: }
1872: for(d=0; d<dh[mi][i]; d++){
1873: newm=savm;
1874: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1875: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1876: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1877: }
1878: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1879: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1880: savm=oldm;
1881: oldm=newm;
1882: } /* end mult */
1883:
1884: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1885: /* But now since version 0.9 we anticipate for bias at large stepm.
1886: * If stepm is larger than one month (smallest stepm) and if the exact delay
1887: * (in months) between two waves is not a multiple of stepm, we rounded to
1888: * the nearest (and in case of equal distance, to the lowest) interval but now
1889: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1890: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1891: * probability in order to take into account the bias as a fraction of the way
1892: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1893: * -stepm/2 to stepm/2 .
1894: * For stepm=1 the results are the same as for previous versions of Imach.
1895: * For stepm > 1 the results are less biased than in previous versions.
1896: */
1897: s1=s[mw[mi][i]][i];
1898: s2=s[mw[mi+1][i]][i];
1899: bbh=(double)bh[mi][i]/(double)stepm;
1900: /* bias bh is positive if real duration
1901: * is higher than the multiple of stepm and negative otherwise.
1902: */
1903: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1904: if( s2 > nlstate){
1905: /* i.e. if s2 is a death state and if the date of death is known
1906: then the contribution to the likelihood is the probability to
1907: die between last step unit time and current step unit time,
1908: which is also equal to probability to die before dh
1909: minus probability to die before dh-stepm .
1910: In version up to 0.92 likelihood was computed
1911: as if date of death was unknown. Death was treated as any other
1912: health state: the date of the interview describes the actual state
1913: and not the date of a change in health state. The former idea was
1914: to consider that at each interview the state was recorded
1915: (healthy, disable or death) and IMaCh was corrected; but when we
1916: introduced the exact date of death then we should have modified
1917: the contribution of an exact death to the likelihood. This new
1918: contribution is smaller and very dependent of the step unit
1919: stepm. It is no more the probability to die between last interview
1920: and month of death but the probability to survive from last
1921: interview up to one month before death multiplied by the
1922: probability to die within a month. Thanks to Chris
1923: Jackson for correcting this bug. Former versions increased
1924: mortality artificially. The bad side is that we add another loop
1925: which slows down the processing. The difference can be up to 10%
1926: lower mortality.
1927: */
1928: lli=log(out[s1][s2] - savm[s1][s2]);
1929:
1930:
1931: } else if (s2==-2) {
1932: for (j=1,survp=0. ; j<=nlstate; j++)
1933: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1934: /*survp += out[s1][j]; */
1935: lli= log(survp);
1936: }
1937:
1938: else if (s2==-4) {
1939: for (j=3,survp=0. ; j<=nlstate; j++)
1940: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1941: lli= log(survp);
1942: }
1943:
1944: else if (s2==-5) {
1945: for (j=1,survp=0. ; j<=2; j++)
1946: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1947: lli= log(survp);
1948: }
1949:
1950: else{
1951: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1952: /* 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 */
1953: }
1954: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1955: /*if(lli ==000.0)*/
1956: /*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); */
1957: ipmx +=1;
1958: sw += weight[i];
1959: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1960: } /* end of wave */
1961: } /* end of individual */
1962: } else if(mle==2){
1963: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1964: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1965: for(mi=1; mi<= wav[i]-1; mi++){
1966: for (ii=1;ii<=nlstate+ndeath;ii++)
1967: for (j=1;j<=nlstate+ndeath;j++){
1968: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1969: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1970: }
1971: for(d=0; d<=dh[mi][i]; d++){
1972: newm=savm;
1973: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1974: for (kk=1; kk<=cptcovage;kk++) {
1975: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1976: }
1977: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1978: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1979: savm=oldm;
1980: oldm=newm;
1981: } /* end mult */
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: 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 */
1987: ipmx +=1;
1988: sw += weight[i];
1989: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1990: } /* end of wave */
1991: } /* end of individual */
1992: } else if(mle==3){ /* exponential inter-extrapolation */
1993: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1994: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1995: for(mi=1; mi<= wav[i]-1; mi++){
1996: for (ii=1;ii<=nlstate+ndeath;ii++)
1997: for (j=1;j<=nlstate+ndeath;j++){
1998: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1999: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2000: }
2001: for(d=0; d<dh[mi][i]; d++){
2002: newm=savm;
2003: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2004: for (kk=1; kk<=cptcovage;kk++) {
2005: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2006: }
2007: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2008: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2009: savm=oldm;
2010: oldm=newm;
2011: } /* end mult */
2012:
2013: s1=s[mw[mi][i]][i];
2014: s2=s[mw[mi+1][i]][i];
2015: bbh=(double)bh[mi][i]/(double)stepm;
2016: 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 */
2017: ipmx +=1;
2018: sw += weight[i];
2019: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2020: } /* end of wave */
2021: } /* end of individual */
2022: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2023: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2024: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2025: for(mi=1; mi<= wav[i]-1; mi++){
2026: for (ii=1;ii<=nlstate+ndeath;ii++)
2027: for (j=1;j<=nlstate+ndeath;j++){
2028: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2029: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2030: }
2031: for(d=0; d<dh[mi][i]; d++){
2032: newm=savm;
2033: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2034: for (kk=1; kk<=cptcovage;kk++) {
2035: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2036: }
2037:
2038: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2039: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2040: savm=oldm;
2041: oldm=newm;
2042: } /* end mult */
2043:
2044: s1=s[mw[mi][i]][i];
2045: s2=s[mw[mi+1][i]][i];
2046: if( s2 > nlstate){
2047: lli=log(out[s1][s2] - savm[s1][s2]);
2048: }else{
2049: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2050: }
2051: ipmx +=1;
2052: sw += weight[i];
2053: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2054: /* 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]); */
2055: } /* end of wave */
2056: } /* end of individual */
2057: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2058: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2059: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2060: for(mi=1; mi<= wav[i]-1; mi++){
2061: for (ii=1;ii<=nlstate+ndeath;ii++)
2062: for (j=1;j<=nlstate+ndeath;j++){
2063: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2064: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2065: }
2066: for(d=0; d<dh[mi][i]; d++){
2067: newm=savm;
2068: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2069: for (kk=1; kk<=cptcovage;kk++) {
2070: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2071: }
2072:
2073: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2074: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2075: savm=oldm;
2076: oldm=newm;
2077: } /* end mult */
2078:
2079: s1=s[mw[mi][i]][i];
2080: s2=s[mw[mi+1][i]][i];
2081: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2082: ipmx +=1;
2083: sw += weight[i];
2084: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2085: /*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]);*/
2086: } /* end of wave */
2087: } /* end of individual */
2088: } /* End of if */
2089: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2090: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2091: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2092: return -l;
2093: }
2094:
2095: /*************** log-likelihood *************/
2096: double funcone( double *x)
2097: {
2098: /* Same as likeli but slower because of a lot of printf and if */
2099: int i, ii, j, k, mi, d, kk;
1.131 brouard 2100: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2101: double **out;
2102: double lli; /* Individual log likelihood */
2103: double llt;
2104: int s1, s2;
2105: double bbh, survp;
2106: /*extern weight */
2107: /* We are differentiating ll according to initial status */
2108: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2109: /*for(i=1;i<imx;i++)
2110: printf(" %d\n",s[4][i]);
2111: */
2112: cov[1]=1.;
2113:
2114: for(k=1; k<=nlstate; k++) ll[k]=0.;
2115:
2116: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2117: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2118: for(mi=1; mi<= wav[i]-1; mi++){
2119: for (ii=1;ii<=nlstate+ndeath;ii++)
2120: for (j=1;j<=nlstate+ndeath;j++){
2121: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2122: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2123: }
2124: for(d=0; d<dh[mi][i]; d++){
2125: newm=savm;
2126: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2127: for (kk=1; kk<=cptcovage;kk++) {
2128: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2129: }
1.145 brouard 2130: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2131: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2132: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2133: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2134: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2135: savm=oldm;
2136: oldm=newm;
2137: } /* end mult */
2138:
2139: s1=s[mw[mi][i]][i];
2140: s2=s[mw[mi+1][i]][i];
2141: bbh=(double)bh[mi][i]/(double)stepm;
2142: /* bias is positive if real duration
2143: * is higher than the multiple of stepm and negative otherwise.
2144: */
2145: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2146: lli=log(out[s1][s2] - savm[s1][s2]);
2147: } else if (s2==-2) {
2148: for (j=1,survp=0. ; j<=nlstate; j++)
2149: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2150: lli= log(survp);
2151: }else if (mle==1){
2152: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2153: } else if(mle==2){
2154: 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 */
2155: } else if(mle==3){ /* exponential inter-extrapolation */
2156: 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 */
2157: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2158: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2159: } else{ /* mle=0 back to 1 */
2160: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2161: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2162: } /* End of if */
2163: ipmx +=1;
2164: sw += weight[i];
2165: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2166: /*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]); */
1.126 brouard 2167: if(globpr){
1.141 brouard 2168: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2169: %11.6f %11.6f %11.6f ", \
2170: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2171: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2172: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2173: llt +=ll[k]*gipmx/gsw;
2174: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2175: }
2176: fprintf(ficresilk," %10.6f\n", -llt);
2177: }
2178: } /* end of wave */
2179: } /* end of individual */
2180: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2181: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2182: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2183: if(globpr==0){ /* First time we count the contributions and weights */
2184: gipmx=ipmx;
2185: gsw=sw;
2186: }
2187: return -l;
2188: }
2189:
2190:
2191: /*************** function likelione ***********/
2192: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2193: {
2194: /* This routine should help understanding what is done with
2195: the selection of individuals/waves and
2196: to check the exact contribution to the likelihood.
2197: Plotting could be done.
2198: */
2199: int k;
2200:
2201: if(*globpri !=0){ /* Just counts and sums, no printings */
2202: strcpy(fileresilk,"ilk");
2203: strcat(fileresilk,fileres);
2204: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2205: printf("Problem with resultfile: %s\n", fileresilk);
2206: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2207: }
2208: 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");
2209: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2210: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2211: for(k=1; k<=nlstate; k++)
2212: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2213: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2214: }
2215:
2216: *fretone=(*funcone)(p);
2217: if(*globpri !=0){
2218: fclose(ficresilk);
2219: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2220: fflush(fichtm);
2221: }
2222: return;
2223: }
2224:
2225:
2226: /*********** Maximum Likelihood Estimation ***************/
2227:
2228: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2229: {
1.165 brouard 2230: int i,j, iter=0;
1.126 brouard 2231: double **xi;
2232: double fret;
2233: double fretone; /* Only one call to likelihood */
2234: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2235:
2236: #ifdef NLOPT
2237: int creturn;
2238: nlopt_opt opt;
2239: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2240: double *lb;
2241: double minf; /* the minimum objective value, upon return */
2242: double * p1; /* Shifted parameters from 0 instead of 1 */
2243: myfunc_data dinst, *d = &dinst;
2244: #endif
2245:
2246:
1.126 brouard 2247: xi=matrix(1,npar,1,npar);
2248: for (i=1;i<=npar;i++)
2249: for (j=1;j<=npar;j++)
2250: xi[i][j]=(i==j ? 1.0 : 0.0);
2251: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2252: strcpy(filerespow,"pow");
2253: strcat(filerespow,fileres);
2254: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2255: printf("Problem with resultfile: %s\n", filerespow);
2256: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2257: }
2258: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2259: for (i=1;i<=nlstate;i++)
2260: for(j=1;j<=nlstate+ndeath;j++)
2261: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2262: fprintf(ficrespow,"\n");
1.162 brouard 2263: #ifdef POWELL
1.126 brouard 2264: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2265: #endif
1.126 brouard 2266:
1.162 brouard 2267: #ifdef NLOPT
2268: #ifdef NEWUOA
2269: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2270: #else
2271: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2272: #endif
2273: lb=vector(0,npar-1);
2274: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2275: nlopt_set_lower_bounds(opt, lb);
2276: nlopt_set_initial_step1(opt, 0.1);
2277:
2278: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2279: d->function = func;
2280: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2281: nlopt_set_min_objective(opt, myfunc, d);
2282: nlopt_set_xtol_rel(opt, ftol);
2283: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2284: printf("nlopt failed! %d\n",creturn);
2285: }
2286: else {
2287: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2288: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2289: iter=1; /* not equal */
2290: }
2291: nlopt_destroy(opt);
2292: #endif
1.126 brouard 2293: free_matrix(xi,1,npar,1,npar);
2294: fclose(ficrespow);
1.180 brouard 2295: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2296: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2297: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2298:
2299: }
2300:
2301: /**** Computes Hessian and covariance matrix ***/
2302: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2303: {
2304: double **a,**y,*x,pd;
2305: double **hess;
1.164 brouard 2306: int i, j;
1.126 brouard 2307: int *indx;
2308:
2309: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2310: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2311: void lubksb(double **a, int npar, int *indx, double b[]) ;
2312: void ludcmp(double **a, int npar, int *indx, double *d) ;
2313: double gompertz(double p[]);
2314: hess=matrix(1,npar,1,npar);
2315:
2316: printf("\nCalculation of the hessian matrix. Wait...\n");
2317: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2318: for (i=1;i<=npar;i++){
2319: printf("%d",i);fflush(stdout);
2320: fprintf(ficlog,"%d",i);fflush(ficlog);
2321:
2322: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2323:
2324: /* printf(" %f ",p[i]);
2325: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2326: }
2327:
2328: for (i=1;i<=npar;i++) {
2329: for (j=1;j<=npar;j++) {
2330: if (j>i) {
2331: printf(".%d%d",i,j);fflush(stdout);
2332: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2333: hess[i][j]=hessij(p,delti,i,j,func,npar);
2334:
2335: hess[j][i]=hess[i][j];
2336: /*printf(" %lf ",hess[i][j]);*/
2337: }
2338: }
2339: }
2340: printf("\n");
2341: fprintf(ficlog,"\n");
2342:
2343: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2344: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2345:
2346: a=matrix(1,npar,1,npar);
2347: y=matrix(1,npar,1,npar);
2348: x=vector(1,npar);
2349: indx=ivector(1,npar);
2350: for (i=1;i<=npar;i++)
2351: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2352: ludcmp(a,npar,indx,&pd);
2353:
2354: for (j=1;j<=npar;j++) {
2355: for (i=1;i<=npar;i++) x[i]=0;
2356: x[j]=1;
2357: lubksb(a,npar,indx,x);
2358: for (i=1;i<=npar;i++){
2359: matcov[i][j]=x[i];
2360: }
2361: }
2362:
2363: printf("\n#Hessian matrix#\n");
2364: fprintf(ficlog,"\n#Hessian matrix#\n");
2365: for (i=1;i<=npar;i++) {
2366: for (j=1;j<=npar;j++) {
2367: printf("%.3e ",hess[i][j]);
2368: fprintf(ficlog,"%.3e ",hess[i][j]);
2369: }
2370: printf("\n");
2371: fprintf(ficlog,"\n");
2372: }
2373:
2374: /* Recompute Inverse */
2375: for (i=1;i<=npar;i++)
2376: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2377: ludcmp(a,npar,indx,&pd);
2378:
2379: /* printf("\n#Hessian matrix recomputed#\n");
2380:
2381: for (j=1;j<=npar;j++) {
2382: for (i=1;i<=npar;i++) x[i]=0;
2383: x[j]=1;
2384: lubksb(a,npar,indx,x);
2385: for (i=1;i<=npar;i++){
2386: y[i][j]=x[i];
2387: printf("%.3e ",y[i][j]);
2388: fprintf(ficlog,"%.3e ",y[i][j]);
2389: }
2390: printf("\n");
2391: fprintf(ficlog,"\n");
2392: }
2393: */
2394:
2395: free_matrix(a,1,npar,1,npar);
2396: free_matrix(y,1,npar,1,npar);
2397: free_vector(x,1,npar);
2398: free_ivector(indx,1,npar);
2399: free_matrix(hess,1,npar,1,npar);
2400:
2401:
2402: }
2403:
2404: /*************** hessian matrix ****************/
2405: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2406: {
2407: int i;
2408: int l=1, lmax=20;
2409: double k1,k2;
1.132 brouard 2410: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2411: double res;
2412: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2413: double fx;
2414: int k=0,kmax=10;
2415: double l1;
2416:
2417: fx=func(x);
2418: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2419: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2420: l1=pow(10,l);
2421: delts=delt;
2422: for(k=1 ; k <kmax; k=k+1){
2423: delt = delta*(l1*k);
2424: p2[theta]=x[theta] +delt;
1.145 brouard 2425: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2426: p2[theta]=x[theta]-delt;
2427: k2=func(p2)-fx;
2428: /*res= (k1-2.0*fx+k2)/delt/delt; */
2429: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2430:
1.132 brouard 2431: #ifdef DEBUGHESS
1.126 brouard 2432: 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);
2433: 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);
2434: #endif
2435: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2436: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2437: k=kmax;
2438: }
2439: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2440: k=kmax; l=lmax*10;
1.126 brouard 2441: }
2442: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2443: delts=delt;
2444: }
2445: }
2446: }
2447: delti[theta]=delts;
2448: return res;
2449:
2450: }
2451:
2452: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2453: {
2454: int i;
1.164 brouard 2455: int l=1, lmax=20;
1.126 brouard 2456: double k1,k2,k3,k4,res,fx;
1.132 brouard 2457: double p2[MAXPARM+1];
1.126 brouard 2458: int k;
2459:
2460: fx=func(x);
2461: for (k=1; k<=2; k++) {
2462: for (i=1;i<=npar;i++) p2[i]=x[i];
2463: p2[thetai]=x[thetai]+delti[thetai]/k;
2464: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2465: k1=func(p2)-fx;
2466:
2467: p2[thetai]=x[thetai]+delti[thetai]/k;
2468: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2469: k2=func(p2)-fx;
2470:
2471: p2[thetai]=x[thetai]-delti[thetai]/k;
2472: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2473: k3=func(p2)-fx;
2474:
2475: p2[thetai]=x[thetai]-delti[thetai]/k;
2476: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2477: k4=func(p2)-fx;
2478: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2479: #ifdef DEBUG
2480: 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);
2481: 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);
2482: #endif
2483: }
2484: return res;
2485: }
2486:
2487: /************** Inverse of matrix **************/
2488: void ludcmp(double **a, int n, int *indx, double *d)
2489: {
2490: int i,imax,j,k;
2491: double big,dum,sum,temp;
2492: double *vv;
2493:
2494: vv=vector(1,n);
2495: *d=1.0;
2496: for (i=1;i<=n;i++) {
2497: big=0.0;
2498: for (j=1;j<=n;j++)
2499: if ((temp=fabs(a[i][j])) > big) big=temp;
2500: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2501: vv[i]=1.0/big;
2502: }
2503: for (j=1;j<=n;j++) {
2504: for (i=1;i<j;i++) {
2505: sum=a[i][j];
2506: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2507: a[i][j]=sum;
2508: }
2509: big=0.0;
2510: for (i=j;i<=n;i++) {
2511: sum=a[i][j];
2512: for (k=1;k<j;k++)
2513: sum -= a[i][k]*a[k][j];
2514: a[i][j]=sum;
2515: if ( (dum=vv[i]*fabs(sum)) >= big) {
2516: big=dum;
2517: imax=i;
2518: }
2519: }
2520: if (j != imax) {
2521: for (k=1;k<=n;k++) {
2522: dum=a[imax][k];
2523: a[imax][k]=a[j][k];
2524: a[j][k]=dum;
2525: }
2526: *d = -(*d);
2527: vv[imax]=vv[j];
2528: }
2529: indx[j]=imax;
2530: if (a[j][j] == 0.0) a[j][j]=TINY;
2531: if (j != n) {
2532: dum=1.0/(a[j][j]);
2533: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2534: }
2535: }
2536: free_vector(vv,1,n); /* Doesn't work */
2537: ;
2538: }
2539:
2540: void lubksb(double **a, int n, int *indx, double b[])
2541: {
2542: int i,ii=0,ip,j;
2543: double sum;
2544:
2545: for (i=1;i<=n;i++) {
2546: ip=indx[i];
2547: sum=b[ip];
2548: b[ip]=b[i];
2549: if (ii)
2550: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2551: else if (sum) ii=i;
2552: b[i]=sum;
2553: }
2554: for (i=n;i>=1;i--) {
2555: sum=b[i];
2556: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2557: b[i]=sum/a[i][i];
2558: }
2559: }
2560:
2561: void pstamp(FILE *fichier)
2562: {
2563: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2564: }
2565:
2566: /************ Frequencies ********************/
2567: 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[])
2568: { /* Some frequencies */
2569:
1.164 brouard 2570: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2571: int first;
2572: double ***freq; /* Frequencies */
2573: double *pp, **prop;
2574: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2575: char fileresp[FILENAMELENGTH];
2576:
2577: pp=vector(1,nlstate);
2578: prop=matrix(1,nlstate,iagemin,iagemax+3);
2579: strcpy(fileresp,"p");
2580: strcat(fileresp,fileres);
2581: if((ficresp=fopen(fileresp,"w"))==NULL) {
2582: printf("Problem with prevalence resultfile: %s\n", fileresp);
2583: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2584: exit(0);
2585: }
2586: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2587: j1=0;
2588:
2589: j=cptcoveff;
2590: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2591:
2592: first=1;
2593:
1.169 brouard 2594: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2595: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2596: /* j1++; */
1.145 brouard 2597: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2598: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2599: scanf("%d", i);*/
2600: for (i=-5; i<=nlstate+ndeath; i++)
2601: for (jk=-5; jk<=nlstate+ndeath; jk++)
2602: for(m=iagemin; m <= iagemax+3; m++)
2603: freq[i][jk][m]=0;
1.143 brouard 2604:
2605: for (i=1; i<=nlstate; i++)
2606: for(m=iagemin; m <= iagemax+3; m++)
2607: prop[i][m]=0;
1.126 brouard 2608:
2609: dateintsum=0;
2610: k2cpt=0;
2611: for (i=1; i<=imx; i++) {
2612: bool=1;
1.144 brouard 2613: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2614: for (z1=1; z1<=cptcoveff; z1++)
2615: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2616: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2617: bool=0;
1.145 brouard 2618: /* 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",
2619: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2620: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2621: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2622: }
1.126 brouard 2623: }
1.144 brouard 2624:
1.126 brouard 2625: if (bool==1){
2626: for(m=firstpass; m<=lastpass; m++){
2627: k2=anint[m][i]+(mint[m][i]/12.);
2628: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2629: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2630: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2631: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2632: if (m<lastpass) {
2633: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2634: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2635: }
2636:
2637: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2638: dateintsum=dateintsum+k2;
2639: k2cpt++;
2640: }
2641: /*}*/
2642: }
2643: }
1.145 brouard 2644: } /* end i */
1.126 brouard 2645:
2646: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2647: pstamp(ficresp);
2648: if (cptcovn>0) {
2649: fprintf(ficresp, "\n#********** Variable ");
2650: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2651: fprintf(ficresp, "**********\n#");
1.143 brouard 2652: fprintf(ficlog, "\n#********** Variable ");
2653: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2654: fprintf(ficlog, "**********\n#");
1.126 brouard 2655: }
2656: for(i=1; i<=nlstate;i++)
2657: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2658: fprintf(ficresp, "\n");
2659:
2660: for(i=iagemin; i <= iagemax+3; i++){
2661: if(i==iagemax+3){
2662: fprintf(ficlog,"Total");
2663: }else{
2664: if(first==1){
2665: first=0;
2666: printf("See log file for details...\n");
2667: }
2668: fprintf(ficlog,"Age %d", i);
2669: }
2670: for(jk=1; jk <=nlstate ; jk++){
2671: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2672: pp[jk] += freq[jk][m][i];
2673: }
2674: for(jk=1; jk <=nlstate ; jk++){
2675: for(m=-1, pos=0; m <=0 ; m++)
2676: pos += freq[jk][m][i];
2677: if(pp[jk]>=1.e-10){
2678: if(first==1){
1.132 brouard 2679: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2680: }
2681: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2682: }else{
2683: if(first==1)
2684: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2685: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2686: }
2687: }
2688:
2689: for(jk=1; jk <=nlstate ; jk++){
2690: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2691: pp[jk] += freq[jk][m][i];
2692: }
2693: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2694: pos += pp[jk];
2695: posprop += prop[jk][i];
2696: }
2697: for(jk=1; jk <=nlstate ; jk++){
2698: if(pos>=1.e-5){
2699: if(first==1)
2700: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2701: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2702: }else{
2703: if(first==1)
2704: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2705: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2706: }
2707: if( i <= iagemax){
2708: if(pos>=1.e-5){
2709: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2710: /*probs[i][jk][j1]= pp[jk]/pos;*/
2711: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2712: }
2713: else
2714: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2715: }
2716: }
2717:
2718: for(jk=-1; jk <=nlstate+ndeath; jk++)
2719: for(m=-1; m <=nlstate+ndeath; m++)
2720: if(freq[jk][m][i] !=0 ) {
2721: if(first==1)
2722: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2723: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2724: }
2725: if(i <= iagemax)
2726: fprintf(ficresp,"\n");
2727: if(first==1)
2728: printf("Others in log...\n");
2729: fprintf(ficlog,"\n");
2730: }
1.145 brouard 2731: /*}*/
1.126 brouard 2732: }
2733: dateintmean=dateintsum/k2cpt;
2734:
2735: fclose(ficresp);
2736: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2737: free_vector(pp,1,nlstate);
2738: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2739: /* End of Freq */
2740: }
2741:
2742: /************ Prevalence ********************/
2743: 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)
2744: {
2745: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2746: in each health status at the date of interview (if between dateprev1 and dateprev2).
2747: We still use firstpass and lastpass as another selection.
2748: */
2749:
1.164 brouard 2750: int i, m, jk, j1, bool, z1,j;
2751:
2752: double **prop;
2753: double posprop;
1.126 brouard 2754: double y2; /* in fractional years */
2755: int iagemin, iagemax;
1.145 brouard 2756: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2757:
2758: iagemin= (int) agemin;
2759: iagemax= (int) agemax;
2760: /*pp=vector(1,nlstate);*/
2761: prop=matrix(1,nlstate,iagemin,iagemax+3);
2762: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2763: j1=0;
2764:
1.145 brouard 2765: /*j=cptcoveff;*/
1.126 brouard 2766: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2767:
1.145 brouard 2768: first=1;
2769: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2770: /*for(i1=1; i1<=ncodemax[k1];i1++){
2771: j1++;*/
1.126 brouard 2772:
2773: for (i=1; i<=nlstate; i++)
2774: for(m=iagemin; m <= iagemax+3; m++)
2775: prop[i][m]=0.0;
2776:
2777: for (i=1; i<=imx; i++) { /* Each individual */
2778: bool=1;
2779: if (cptcovn>0) {
2780: for (z1=1; z1<=cptcoveff; z1++)
2781: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2782: bool=0;
2783: }
2784: if (bool==1) {
2785: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2786: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2787: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2788: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2789: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2790: 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);
2791: if (s[m][i]>0 && s[m][i]<=nlstate) {
2792: /*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]]);*/
2793: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2794: prop[s[m][i]][iagemax+3] += weight[i];
2795: }
2796: }
2797: } /* end selection of waves */
2798: }
2799: }
2800: for(i=iagemin; i <= iagemax+3; i++){
2801: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2802: posprop += prop[jk][i];
2803: }
1.145 brouard 2804:
1.126 brouard 2805: for(jk=1; jk <=nlstate ; jk++){
2806: if( i <= iagemax){
2807: if(posprop>=1.e-5){
2808: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2809: } else{
2810: if(first==1){
2811: first=0;
2812: 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]);
2813: }
2814: }
1.126 brouard 2815: }
2816: }/* end jk */
2817: }/* end i */
1.145 brouard 2818: /*} *//* end i1 */
2819: } /* end j1 */
1.126 brouard 2820:
2821: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2822: /*free_vector(pp,1,nlstate);*/
2823: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2824: } /* End of prevalence */
2825:
2826: /************* Waves Concatenation ***************/
2827:
2828: 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)
2829: {
2830: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2831: Death is a valid wave (if date is known).
2832: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2833: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2834: and mw[mi+1][i]. dh depends on stepm.
2835: */
2836:
2837: int i, mi, m;
2838: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2839: double sum=0., jmean=0.;*/
2840: int first;
2841: int j, k=0,jk, ju, jl;
2842: double sum=0.;
2843: first=0;
1.164 brouard 2844: jmin=100000;
1.126 brouard 2845: jmax=-1;
2846: jmean=0.;
2847: for(i=1; i<=imx; i++){
2848: mi=0;
2849: m=firstpass;
2850: while(s[m][i] <= nlstate){
2851: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2852: mw[++mi][i]=m;
2853: if(m >=lastpass)
2854: break;
2855: else
2856: m++;
2857: }/* end while */
2858: if (s[m][i] > nlstate){
2859: mi++; /* Death is another wave */
2860: /* if(mi==0) never been interviewed correctly before death */
2861: /* Only death is a correct wave */
2862: mw[mi][i]=m;
2863: }
2864:
2865: wav[i]=mi;
2866: if(mi==0){
2867: nbwarn++;
2868: if(first==0){
2869: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2870: first=1;
2871: }
2872: if(first==1){
2873: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2874: }
2875: } /* end mi==0 */
2876: } /* End individuals */
2877:
2878: for(i=1; i<=imx; i++){
2879: for(mi=1; mi<wav[i];mi++){
2880: if (stepm <=0)
2881: dh[mi][i]=1;
2882: else{
2883: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2884: if (agedc[i] < 2*AGESUP) {
2885: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2886: if(j==0) j=1; /* Survives at least one month after exam */
2887: else if(j<0){
2888: nberr++;
2889: 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]);
2890: j=1; /* Temporary Dangerous patch */
2891: 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);
2892: 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]);
2893: 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);
2894: }
2895: k=k+1;
2896: if (j >= jmax){
2897: jmax=j;
2898: ijmax=i;
2899: }
2900: if (j <= jmin){
2901: jmin=j;
2902: ijmin=i;
2903: }
2904: sum=sum+j;
2905: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2906: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2907: }
2908: }
2909: else{
2910: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2911: /* 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]); */
2912:
2913: k=k+1;
2914: if (j >= jmax) {
2915: jmax=j;
2916: ijmax=i;
2917: }
2918: else if (j <= jmin){
2919: jmin=j;
2920: ijmin=i;
2921: }
2922: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2923: /*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]);*/
2924: if(j<0){
2925: nberr++;
2926: 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]);
2927: 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]);
2928: }
2929: sum=sum+j;
2930: }
2931: jk= j/stepm;
2932: jl= j -jk*stepm;
2933: ju= j -(jk+1)*stepm;
2934: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2935: if(jl==0){
2936: dh[mi][i]=jk;
2937: bh[mi][i]=0;
2938: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2939: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2940: dh[mi][i]=jk+1;
2941: bh[mi][i]=ju;
2942: }
2943: }else{
2944: if(jl <= -ju){
2945: dh[mi][i]=jk;
2946: bh[mi][i]=jl; /* bias is positive if real duration
2947: * is higher than the multiple of stepm and negative otherwise.
2948: */
2949: }
2950: else{
2951: dh[mi][i]=jk+1;
2952: bh[mi][i]=ju;
2953: }
2954: if(dh[mi][i]==0){
2955: dh[mi][i]=1; /* At least one step */
2956: bh[mi][i]=ju; /* At least one step */
2957: /* 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);*/
2958: }
2959: } /* end if mle */
2960: }
2961: } /* end wave */
2962: }
2963: jmean=sum/k;
2964: 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);
1.141 brouard 2965: 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);
1.126 brouard 2966: }
2967:
2968: /*********** Tricode ****************************/
1.145 brouard 2969: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2970: {
1.144 brouard 2971: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2972: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
1.169 brouard 2973: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2974: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 2975: * nbcode[Tvar[j]][1]=
1.144 brouard 2976: */
1.130 brouard 2977:
1.145 brouard 2978: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2979: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2980: int cptcode=0; /* Modality max of covariates j */
2981: int modmincovj=0; /* Modality min of covariates j */
2982:
2983:
1.126 brouard 2984: cptcoveff=0;
2985:
1.145 brouard 2986: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2987: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2988:
1.145 brouard 2989: /* Loop on covariates without age and products */
2990: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2991: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2992: modality of this covariate Vj*/
1.145 brouard 2993: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2994: * If product of Vn*Vm, still boolean *:
2995: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2996: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2997: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2998: modality of the nth covariate of individual i. */
1.145 brouard 2999: if (ij > modmaxcovj)
3000: modmaxcovj=ij;
3001: else if (ij < modmincovj)
3002: modmincovj=ij;
3003: if ((ij < -1) && (ij > NCOVMAX)){
3004: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3005: exit(1);
3006: }else
1.136 brouard 3007: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3008: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3009: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3010: /* getting the maximum value of the modality of the covariate
3011: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3012: female is 1, then modmaxcovj=1.*/
1.126 brouard 3013: }
1.145 brouard 3014: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3015: cptcode=modmaxcovj;
1.137 brouard 3016: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3017: /*for (i=0; i<=cptcode; i++) {*/
3018: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3019: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3020: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3021: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3022: }
3023: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3024: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3025: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3026:
1.136 brouard 3027: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 3028: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3029: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3030: modmincovj=3; modmaxcovj = 7;
3031: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3032: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3033: variables V1_1 and V1_2.
3034: nbcode[Tvar[j]][ij]=k;
3035: nbcode[Tvar[j]][1]=0;
3036: nbcode[Tvar[j]][2]=1;
3037: nbcode[Tvar[j]][3]=2;
3038: */
3039: ij=1; /* ij is similar to i but can jumps over null modalities */
3040: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3041: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3042: /*recode from 0 */
1.131 brouard 3043: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3044: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3045: k is a modality. If we have model=V1+V1*sex
3046: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3047: ij++;
3048: }
3049: if (ij > ncodemax[j]) break;
1.137 brouard 3050: } /* end of loop on */
3051: } /* end of loop on modality */
3052: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3053:
1.145 brouard 3054: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3055:
1.145 brouard 3056: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3057: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3058: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3059: Ndum[ij]++;
3060: }
1.126 brouard 3061:
3062: ij=1;
1.145 brouard 3063: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3064: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3065: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3066: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3067: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3068: ij++;
1.145 brouard 3069: }else
3070: Tvaraff[ij]=0;
1.126 brouard 3071: }
1.131 brouard 3072: ij--;
1.144 brouard 3073: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3074:
1.126 brouard 3075: }
3076:
1.145 brouard 3077:
1.126 brouard 3078: /*********** Health Expectancies ****************/
3079:
1.127 brouard 3080: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126 brouard 3081:
3082: {
3083: /* Health expectancies, no variances */
1.164 brouard 3084: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3085: int nhstepma, nstepma; /* Decreasing with age */
3086: double age, agelim, hf;
3087: double ***p3mat;
3088: double eip;
3089:
3090: pstamp(ficreseij);
3091: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3092: fprintf(ficreseij,"# Age");
3093: for(i=1; i<=nlstate;i++){
3094: for(j=1; j<=nlstate;j++){
3095: fprintf(ficreseij," e%1d%1d ",i,j);
3096: }
3097: fprintf(ficreseij," e%1d. ",i);
3098: }
3099: fprintf(ficreseij,"\n");
3100:
3101:
3102: if(estepm < stepm){
3103: printf ("Problem %d lower than %d\n",estepm, stepm);
3104: }
3105: else hstepm=estepm;
3106: /* We compute the life expectancy from trapezoids spaced every estepm months
3107: * This is mainly to measure the difference between two models: for example
3108: * if stepm=24 months pijx are given only every 2 years and by summing them
3109: * we are calculating an estimate of the Life Expectancy assuming a linear
3110: * progression in between and thus overestimating or underestimating according
3111: * to the curvature of the survival function. If, for the same date, we
3112: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3113: * to compare the new estimate of Life expectancy with the same linear
3114: * hypothesis. A more precise result, taking into account a more precise
3115: * curvature will be obtained if estepm is as small as stepm. */
3116:
3117: /* For example we decided to compute the life expectancy with the smallest unit */
3118: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3119: nhstepm is the number of hstepm from age to agelim
3120: nstepm is the number of stepm from age to agelin.
3121: Look at hpijx to understand the reason of that which relies in memory size
3122: and note for a fixed period like estepm months */
3123: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3124: survival function given by stepm (the optimization length). Unfortunately it
3125: means that if the survival funtion is printed only each two years of age and if
3126: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3127: results. So we changed our mind and took the option of the best precision.
3128: */
3129: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3130:
3131: agelim=AGESUP;
3132: /* If stepm=6 months */
3133: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3134: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3135:
3136: /* nhstepm age range expressed in number of stepm */
3137: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3138: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3139: /* if (stepm >= YEARM) hstepm=1;*/
3140: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3141: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3142:
3143: for (age=bage; age<=fage; age ++){
3144: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3145: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3146: /* if (stepm >= YEARM) hstepm=1;*/
3147: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3148:
3149: /* If stepm=6 months */
3150: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3151: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3152:
3153: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3154:
3155: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3156:
3157: printf("%d|",(int)age);fflush(stdout);
3158: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3159:
3160: /* Computing expectancies */
3161: for(i=1; i<=nlstate;i++)
3162: for(j=1; j<=nlstate;j++)
3163: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3164: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3165:
3166: /* 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]);*/
3167:
3168: }
3169:
3170: fprintf(ficreseij,"%3.0f",age );
3171: for(i=1; i<=nlstate;i++){
3172: eip=0;
3173: for(j=1; j<=nlstate;j++){
3174: eip +=eij[i][j][(int)age];
3175: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3176: }
3177: fprintf(ficreseij,"%9.4f", eip );
3178: }
3179: fprintf(ficreseij,"\n");
3180:
3181: }
3182: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3183: printf("\n");
3184: fprintf(ficlog,"\n");
3185:
3186: }
3187:
1.127 brouard 3188: 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[] )
1.126 brouard 3189:
3190: {
3191: /* Covariances of health expectancies eij and of total life expectancies according
3192: to initial status i, ei. .
3193: */
3194: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3195: int nhstepma, nstepma; /* Decreasing with age */
3196: double age, agelim, hf;
3197: double ***p3matp, ***p3matm, ***varhe;
3198: double **dnewm,**doldm;
3199: double *xp, *xm;
3200: double **gp, **gm;
3201: double ***gradg, ***trgradg;
3202: int theta;
3203:
3204: double eip, vip;
3205:
3206: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3207: xp=vector(1,npar);
3208: xm=vector(1,npar);
3209: dnewm=matrix(1,nlstate*nlstate,1,npar);
3210: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3211:
3212: pstamp(ficresstdeij);
3213: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3214: fprintf(ficresstdeij,"# Age");
3215: for(i=1; i<=nlstate;i++){
3216: for(j=1; j<=nlstate;j++)
3217: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3218: fprintf(ficresstdeij," e%1d. ",i);
3219: }
3220: fprintf(ficresstdeij,"\n");
3221:
3222: pstamp(ficrescveij);
3223: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3224: fprintf(ficrescveij,"# Age");
3225: for(i=1; i<=nlstate;i++)
3226: for(j=1; j<=nlstate;j++){
3227: cptj= (j-1)*nlstate+i;
3228: for(i2=1; i2<=nlstate;i2++)
3229: for(j2=1; j2<=nlstate;j2++){
3230: cptj2= (j2-1)*nlstate+i2;
3231: if(cptj2 <= cptj)
3232: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3233: }
3234: }
3235: fprintf(ficrescveij,"\n");
3236:
3237: if(estepm < stepm){
3238: printf ("Problem %d lower than %d\n",estepm, stepm);
3239: }
3240: else hstepm=estepm;
3241: /* We compute the life expectancy from trapezoids spaced every estepm months
3242: * This is mainly to measure the difference between two models: for example
3243: * if stepm=24 months pijx are given only every 2 years and by summing them
3244: * we are calculating an estimate of the Life Expectancy assuming a linear
3245: * progression in between and thus overestimating or underestimating according
3246: * to the curvature of the survival function. If, for the same date, we
3247: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3248: * to compare the new estimate of Life expectancy with the same linear
3249: * hypothesis. A more precise result, taking into account a more precise
3250: * curvature will be obtained if estepm is as small as stepm. */
3251:
3252: /* For example we decided to compute the life expectancy with the smallest unit */
3253: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3254: nhstepm is the number of hstepm from age to agelim
3255: nstepm is the number of stepm from age to agelin.
3256: Look at hpijx to understand the reason of that which relies in memory size
3257: and note for a fixed period like estepm months */
3258: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3259: survival function given by stepm (the optimization length). Unfortunately it
3260: means that if the survival funtion is printed only each two years of age and if
3261: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3262: results. So we changed our mind and took the option of the best precision.
3263: */
3264: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3265:
3266: /* If stepm=6 months */
3267: /* nhstepm age range expressed in number of stepm */
3268: agelim=AGESUP;
3269: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3270: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3271: /* if (stepm >= YEARM) hstepm=1;*/
3272: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3273:
3274: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3275: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3276: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3277: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3278: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3279: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3280:
3281: for (age=bage; age<=fage; age ++){
3282: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3283: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3284: /* if (stepm >= YEARM) hstepm=1;*/
3285: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3286:
3287: /* If stepm=6 months */
3288: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3289: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3290:
3291: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3292:
3293: /* Computing Variances of health expectancies */
3294: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3295: decrease memory allocation */
3296: for(theta=1; theta <=npar; theta++){
3297: for(i=1; i<=npar; i++){
3298: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3299: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3300: }
3301: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3302: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3303:
3304: for(j=1; j<= nlstate; j++){
3305: for(i=1; i<=nlstate; i++){
3306: for(h=0; h<=nhstepm-1; h++){
3307: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3308: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3309: }
3310: }
3311: }
3312:
3313: for(ij=1; ij<= nlstate*nlstate; ij++)
3314: for(h=0; h<=nhstepm-1; h++){
3315: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3316: }
3317: }/* End theta */
3318:
3319:
3320: for(h=0; h<=nhstepm-1; h++)
3321: for(j=1; j<=nlstate*nlstate;j++)
3322: for(theta=1; theta <=npar; theta++)
3323: trgradg[h][j][theta]=gradg[h][theta][j];
3324:
3325:
3326: for(ij=1;ij<=nlstate*nlstate;ij++)
3327: for(ji=1;ji<=nlstate*nlstate;ji++)
3328: varhe[ij][ji][(int)age] =0.;
3329:
3330: printf("%d|",(int)age);fflush(stdout);
3331: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3332: for(h=0;h<=nhstepm-1;h++){
3333: for(k=0;k<=nhstepm-1;k++){
3334: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3335: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3336: for(ij=1;ij<=nlstate*nlstate;ij++)
3337: for(ji=1;ji<=nlstate*nlstate;ji++)
3338: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3339: }
3340: }
3341:
3342: /* Computing expectancies */
3343: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3344: for(i=1; i<=nlstate;i++)
3345: for(j=1; j<=nlstate;j++)
3346: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3347: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3348:
3349: /* 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]);*/
3350:
3351: }
3352:
3353: fprintf(ficresstdeij,"%3.0f",age );
3354: for(i=1; i<=nlstate;i++){
3355: eip=0.;
3356: vip=0.;
3357: for(j=1; j<=nlstate;j++){
3358: eip += eij[i][j][(int)age];
3359: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3360: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3361: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3362: }
3363: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3364: }
3365: fprintf(ficresstdeij,"\n");
3366:
3367: fprintf(ficrescveij,"%3.0f",age );
3368: for(i=1; i<=nlstate;i++)
3369: for(j=1; j<=nlstate;j++){
3370: cptj= (j-1)*nlstate+i;
3371: for(i2=1; i2<=nlstate;i2++)
3372: for(j2=1; j2<=nlstate;j2++){
3373: cptj2= (j2-1)*nlstate+i2;
3374: if(cptj2 <= cptj)
3375: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3376: }
3377: }
3378: fprintf(ficrescveij,"\n");
3379:
3380: }
3381: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3382: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3383: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3384: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3385: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3386: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3387: printf("\n");
3388: fprintf(ficlog,"\n");
3389:
3390: free_vector(xm,1,npar);
3391: free_vector(xp,1,npar);
3392: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3393: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3394: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3395: }
3396:
3397: /************ Variance ******************/
3398: 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[])
3399: {
3400: /* Variance of health expectancies */
3401: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3402: /* double **newm;*/
1.169 brouard 3403: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3404:
3405: int movingaverage();
1.126 brouard 3406: double **dnewm,**doldm;
3407: double **dnewmp,**doldmp;
3408: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3409: int k;
1.126 brouard 3410: double *xp;
3411: double **gp, **gm; /* for var eij */
3412: double ***gradg, ***trgradg; /*for var eij */
3413: double **gradgp, **trgradgp; /* for var p point j */
3414: double *gpp, *gmp; /* for var p point j */
3415: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3416: double ***p3mat;
3417: double age,agelim, hf;
3418: double ***mobaverage;
3419: int theta;
3420: char digit[4];
3421: char digitp[25];
3422:
3423: char fileresprobmorprev[FILENAMELENGTH];
3424:
3425: if(popbased==1){
3426: if(mobilav!=0)
3427: strcpy(digitp,"-populbased-mobilav-");
3428: else strcpy(digitp,"-populbased-nomobil-");
3429: }
3430: else
3431: strcpy(digitp,"-stablbased-");
3432:
3433: if (mobilav!=0) {
3434: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3435: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3436: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3437: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3438: }
3439: }
3440:
3441: strcpy(fileresprobmorprev,"prmorprev");
3442: sprintf(digit,"%-d",ij);
3443: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3444: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3445: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3446: strcat(fileresprobmorprev,fileres);
3447: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3448: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3449: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3450: }
3451: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3452:
3453: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3454: pstamp(ficresprobmorprev);
3455: 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);
3456: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3457: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3458: fprintf(ficresprobmorprev," p.%-d SE",j);
3459: for(i=1; i<=nlstate;i++)
3460: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3461: }
3462: fprintf(ficresprobmorprev,"\n");
3463: fprintf(ficgp,"\n# Routine varevsij");
3464: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3465: 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");
3466: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3467: /* } */
3468: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3469: pstamp(ficresvij);
3470: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3471: if(popbased==1)
1.128 brouard 3472: 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);
1.126 brouard 3473: else
3474: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3475: fprintf(ficresvij,"# Age");
3476: for(i=1; i<=nlstate;i++)
3477: for(j=1; j<=nlstate;j++)
3478: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3479: fprintf(ficresvij,"\n");
3480:
3481: xp=vector(1,npar);
3482: dnewm=matrix(1,nlstate,1,npar);
3483: doldm=matrix(1,nlstate,1,nlstate);
3484: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3485: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3486:
3487: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3488: gpp=vector(nlstate+1,nlstate+ndeath);
3489: gmp=vector(nlstate+1,nlstate+ndeath);
3490: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3491:
3492: if(estepm < stepm){
3493: printf ("Problem %d lower than %d\n",estepm, stepm);
3494: }
3495: else hstepm=estepm;
3496: /* For example we decided to compute the life expectancy with the smallest unit */
3497: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3498: nhstepm is the number of hstepm from age to agelim
3499: nstepm is the number of stepm from age to agelin.
1.128 brouard 3500: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3501: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3502: survival function given by stepm (the optimization length). Unfortunately it
3503: means that if the survival funtion is printed every two years of age and if
3504: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3505: results. So we changed our mind and took the option of the best precision.
3506: */
3507: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3508: agelim = AGESUP;
3509: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3510: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3511: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3512: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3513: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3514: gp=matrix(0,nhstepm,1,nlstate);
3515: gm=matrix(0,nhstepm,1,nlstate);
3516:
3517:
3518: for(theta=1; theta <=npar; theta++){
3519: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3520: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3521: }
3522: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3523: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3524:
3525: if (popbased==1) {
3526: if(mobilav ==0){
3527: for(i=1; i<=nlstate;i++)
3528: prlim[i][i]=probs[(int)age][i][ij];
3529: }else{ /* mobilav */
3530: for(i=1; i<=nlstate;i++)
3531: prlim[i][i]=mobaverage[(int)age][i][ij];
3532: }
3533: }
3534:
3535: for(j=1; j<= nlstate; j++){
3536: for(h=0; h<=nhstepm; h++){
3537: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3538: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3539: }
3540: }
3541: /* This for computing probability of death (h=1 means
3542: computed over hstepm matrices product = hstepm*stepm months)
3543: as a weighted average of prlim.
3544: */
3545: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3546: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3547: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3548: }
3549: /* end probability of death */
3550:
3551: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3552: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3553: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3554: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3555:
3556: if (popbased==1) {
3557: if(mobilav ==0){
3558: for(i=1; i<=nlstate;i++)
3559: prlim[i][i]=probs[(int)age][i][ij];
3560: }else{ /* mobilav */
3561: for(i=1; i<=nlstate;i++)
3562: prlim[i][i]=mobaverage[(int)age][i][ij];
3563: }
3564: }
3565:
1.128 brouard 3566: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3567: for(h=0; h<=nhstepm; h++){
3568: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3569: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3570: }
3571: }
3572: /* This for computing probability of death (h=1 means
3573: computed over hstepm matrices product = hstepm*stepm months)
3574: as a weighted average of prlim.
3575: */
3576: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3577: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3578: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3579: }
3580: /* end probability of death */
3581:
3582: for(j=1; j<= nlstate; j++) /* vareij */
3583: for(h=0; h<=nhstepm; h++){
3584: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3585: }
3586:
3587: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3588: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3589: }
3590:
3591: } /* End theta */
3592:
3593: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3594:
3595: for(h=0; h<=nhstepm; h++) /* veij */
3596: for(j=1; j<=nlstate;j++)
3597: for(theta=1; theta <=npar; theta++)
3598: trgradg[h][j][theta]=gradg[h][theta][j];
3599:
3600: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3601: for(theta=1; theta <=npar; theta++)
3602: trgradgp[j][theta]=gradgp[theta][j];
3603:
3604:
3605: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3606: for(i=1;i<=nlstate;i++)
3607: for(j=1;j<=nlstate;j++)
3608: vareij[i][j][(int)age] =0.;
3609:
3610: for(h=0;h<=nhstepm;h++){
3611: for(k=0;k<=nhstepm;k++){
3612: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3613: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3614: for(i=1;i<=nlstate;i++)
3615: for(j=1;j<=nlstate;j++)
3616: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3617: }
3618: }
3619:
3620: /* pptj */
3621: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3622: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3623: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3624: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3625: varppt[j][i]=doldmp[j][i];
3626: /* end ppptj */
3627: /* x centered again */
3628: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3629: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3630:
3631: if (popbased==1) {
3632: if(mobilav ==0){
3633: for(i=1; i<=nlstate;i++)
3634: prlim[i][i]=probs[(int)age][i][ij];
3635: }else{ /* mobilav */
3636: for(i=1; i<=nlstate;i++)
3637: prlim[i][i]=mobaverage[(int)age][i][ij];
3638: }
3639: }
3640:
3641: /* This for computing probability of death (h=1 means
3642: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3643: as a weighted average of prlim.
3644: */
3645: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3646: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3647: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3648: }
3649: /* end probability of death */
3650:
3651: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3652: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3653: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3654: for(i=1; i<=nlstate;i++){
3655: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3656: }
3657: }
3658: fprintf(ficresprobmorprev,"\n");
3659:
3660: fprintf(ficresvij,"%.0f ",age );
3661: for(i=1; i<=nlstate;i++)
3662: for(j=1; j<=nlstate;j++){
3663: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3664: }
3665: fprintf(ficresvij,"\n");
3666: free_matrix(gp,0,nhstepm,1,nlstate);
3667: free_matrix(gm,0,nhstepm,1,nlstate);
3668: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3669: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3670: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3671: } /* End age */
3672: free_vector(gpp,nlstate+1,nlstate+ndeath);
3673: free_vector(gmp,nlstate+1,nlstate+ndeath);
3674: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3675: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3676: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3677: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3678: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3679: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3680: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3681: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3682: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3683: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3684: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3685: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3686: 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);
3687: /* 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);
3688: */
3689: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3690: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3691:
3692: free_vector(xp,1,npar);
3693: free_matrix(doldm,1,nlstate,1,nlstate);
3694: free_matrix(dnewm,1,nlstate,1,npar);
3695: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3696: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3697: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3698: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3699: fclose(ficresprobmorprev);
3700: fflush(ficgp);
3701: fflush(fichtm);
3702: } /* end varevsij */
3703:
3704: /************ Variance of prevlim ******************/
3705: 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[])
3706: {
3707: /* Variance of prevalence limit */
3708: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3709:
1.126 brouard 3710: double **dnewm,**doldm;
3711: int i, j, nhstepm, hstepm;
3712: double *xp;
3713: double *gp, *gm;
3714: double **gradg, **trgradg;
3715: double age,agelim;
3716: int theta;
3717:
3718: pstamp(ficresvpl);
3719: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3720: fprintf(ficresvpl,"# Age");
3721: for(i=1; i<=nlstate;i++)
3722: fprintf(ficresvpl," %1d-%1d",i,i);
3723: fprintf(ficresvpl,"\n");
3724:
3725: xp=vector(1,npar);
3726: dnewm=matrix(1,nlstate,1,npar);
3727: doldm=matrix(1,nlstate,1,nlstate);
3728:
3729: hstepm=1*YEARM; /* Every year of age */
3730: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3731: agelim = AGESUP;
3732: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3733: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3734: if (stepm >= YEARM) hstepm=1;
3735: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3736: gradg=matrix(1,npar,1,nlstate);
3737: gp=vector(1,nlstate);
3738: gm=vector(1,nlstate);
3739:
3740: for(theta=1; theta <=npar; theta++){
3741: for(i=1; i<=npar; i++){ /* Computes gradient */
3742: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3743: }
3744: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3745: for(i=1;i<=nlstate;i++)
3746: gp[i] = prlim[i][i];
3747:
3748: for(i=1; i<=npar; i++) /* Computes gradient */
3749: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3750: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3751: for(i=1;i<=nlstate;i++)
3752: gm[i] = prlim[i][i];
3753:
3754: for(i=1;i<=nlstate;i++)
3755: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3756: } /* End theta */
3757:
3758: trgradg =matrix(1,nlstate,1,npar);
3759:
3760: for(j=1; j<=nlstate;j++)
3761: for(theta=1; theta <=npar; theta++)
3762: trgradg[j][theta]=gradg[theta][j];
3763:
3764: for(i=1;i<=nlstate;i++)
3765: varpl[i][(int)age] =0.;
3766: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3767: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3768: for(i=1;i<=nlstate;i++)
3769: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3770:
3771: fprintf(ficresvpl,"%.0f ",age );
3772: for(i=1; i<=nlstate;i++)
3773: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3774: fprintf(ficresvpl,"\n");
3775: free_vector(gp,1,nlstate);
3776: free_vector(gm,1,nlstate);
3777: free_matrix(gradg,1,npar,1,nlstate);
3778: free_matrix(trgradg,1,nlstate,1,npar);
3779: } /* End age */
3780:
3781: free_vector(xp,1,npar);
3782: free_matrix(doldm,1,nlstate,1,npar);
3783: free_matrix(dnewm,1,nlstate,1,nlstate);
3784:
3785: }
3786:
3787: /************ Variance of one-step probabilities ******************/
3788: 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[])
3789: {
1.164 brouard 3790: int i, j=0, k1, l1, tj;
1.126 brouard 3791: int k2, l2, j1, z1;
1.164 brouard 3792: int k=0, l;
1.145 brouard 3793: int first=1, first1, first2;
1.126 brouard 3794: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3795: double **dnewm,**doldm;
3796: double *xp;
3797: double *gp, *gm;
3798: double **gradg, **trgradg;
3799: double **mu;
1.164 brouard 3800: double age, cov[NCOVMAX+1];
1.126 brouard 3801: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3802: int theta;
3803: char fileresprob[FILENAMELENGTH];
3804: char fileresprobcov[FILENAMELENGTH];
3805: char fileresprobcor[FILENAMELENGTH];
3806: double ***varpij;
3807:
3808: strcpy(fileresprob,"prob");
3809: strcat(fileresprob,fileres);
3810: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3811: printf("Problem with resultfile: %s\n", fileresprob);
3812: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3813: }
3814: strcpy(fileresprobcov,"probcov");
3815: strcat(fileresprobcov,fileres);
3816: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3817: printf("Problem with resultfile: %s\n", fileresprobcov);
3818: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3819: }
3820: strcpy(fileresprobcor,"probcor");
3821: strcat(fileresprobcor,fileres);
3822: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3823: printf("Problem with resultfile: %s\n", fileresprobcor);
3824: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3825: }
3826: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3827: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3828: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3829: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3830: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3831: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3832: pstamp(ficresprob);
3833: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3834: fprintf(ficresprob,"# Age");
3835: pstamp(ficresprobcov);
3836: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3837: fprintf(ficresprobcov,"# Age");
3838: pstamp(ficresprobcor);
3839: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3840: fprintf(ficresprobcor,"# Age");
3841:
3842:
3843: for(i=1; i<=nlstate;i++)
3844: for(j=1; j<=(nlstate+ndeath);j++){
3845: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3846: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3847: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3848: }
3849: /* fprintf(ficresprob,"\n");
3850: fprintf(ficresprobcov,"\n");
3851: fprintf(ficresprobcor,"\n");
3852: */
1.131 brouard 3853: xp=vector(1,npar);
1.126 brouard 3854: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3855: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3856: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3857: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3858: first=1;
3859: fprintf(ficgp,"\n# Routine varprob");
3860: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3861: fprintf(fichtm,"\n");
3862:
3863: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3864: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3865: file %s<br>\n",optionfilehtmcov);
3866: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3867: and drawn. It helps understanding how is the covariance between two incidences.\
3868: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3869: 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. \
3870: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3871: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3872: standard deviations wide on each axis. <br>\
3873: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3874: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3875: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3876:
3877: cov[1]=1;
1.145 brouard 3878: /* tj=cptcoveff; */
3879: tj = (int) pow(2,cptcoveff);
1.126 brouard 3880: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3881: j1=0;
1.145 brouard 3882: for(j1=1; j1<=tj;j1++){
3883: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3884: /*j1++;*/
1.126 brouard 3885: if (cptcovn>0) {
3886: fprintf(ficresprob, "\n#********** Variable ");
3887: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3888: fprintf(ficresprob, "**********\n#\n");
3889: fprintf(ficresprobcov, "\n#********** Variable ");
3890: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3891: fprintf(ficresprobcov, "**********\n#\n");
3892:
3893: fprintf(ficgp, "\n#********** Variable ");
3894: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3895: fprintf(ficgp, "**********\n#\n");
3896:
3897:
3898: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3899: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3900: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3901:
3902: fprintf(ficresprobcor, "\n#********** Variable ");
3903: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3904: fprintf(ficresprobcor, "**********\n#");
3905: }
3906:
1.145 brouard 3907: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3908: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3909: gp=vector(1,(nlstate)*(nlstate+ndeath));
3910: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3911: for (age=bage; age<=fage; age ++){
3912: cov[2]=age;
3913: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3914: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3915: * 1 1 1 1 1
3916: * 2 2 1 1 1
3917: * 3 1 2 1 1
3918: */
3919: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3920: }
3921: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3922: for (k=1; k<=cptcovprod;k++)
3923: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3924:
3925:
3926: for(theta=1; theta <=npar; theta++){
3927: for(i=1; i<=npar; i++)
3928: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3929:
3930: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3931:
3932: k=0;
3933: for(i=1; i<= (nlstate); i++){
3934: for(j=1; j<=(nlstate+ndeath);j++){
3935: k=k+1;
3936: gp[k]=pmmij[i][j];
3937: }
3938: }
3939:
3940: for(i=1; i<=npar; i++)
3941: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3942:
3943: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3944: k=0;
3945: for(i=1; i<=(nlstate); i++){
3946: for(j=1; j<=(nlstate+ndeath);j++){
3947: k=k+1;
3948: gm[k]=pmmij[i][j];
3949: }
3950: }
3951:
3952: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3953: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3954: }
3955:
3956: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3957: for(theta=1; theta <=npar; theta++)
3958: trgradg[j][theta]=gradg[theta][j];
3959:
3960: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3961: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3962:
3963: pmij(pmmij,cov,ncovmodel,x,nlstate);
3964:
3965: k=0;
3966: for(i=1; i<=(nlstate); i++){
3967: for(j=1; j<=(nlstate+ndeath);j++){
3968: k=k+1;
3969: mu[k][(int) age]=pmmij[i][j];
3970: }
3971: }
3972: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3973: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3974: varpij[i][j][(int)age] = doldm[i][j];
3975:
3976: /*printf("\n%d ",(int)age);
3977: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3978: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3979: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3980: }*/
3981:
3982: fprintf(ficresprob,"\n%d ",(int)age);
3983: fprintf(ficresprobcov,"\n%d ",(int)age);
3984: fprintf(ficresprobcor,"\n%d ",(int)age);
3985:
3986: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3987: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3988: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3989: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3990: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3991: }
3992: i=0;
3993: for (k=1; k<=(nlstate);k++){
3994: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3995: i++;
1.126 brouard 3996: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3997: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3998: for (j=1; j<=i;j++){
1.145 brouard 3999: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4000: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4001: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4002: }
4003: }
4004: }/* end of loop for state */
4005: } /* end of loop for age */
1.145 brouard 4006: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4007: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4008: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4009: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4010:
1.126 brouard 4011: /* Confidence intervalle of pij */
4012: /*
1.131 brouard 4013: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4014: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4015: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4016: 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);
4017: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4018: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4019: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4020: */
4021:
4022: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4023: first1=1;first2=2;
1.126 brouard 4024: for (k2=1; k2<=(nlstate);k2++){
4025: for (l2=1; l2<=(nlstate+ndeath);l2++){
4026: if(l2==k2) continue;
4027: j=(k2-1)*(nlstate+ndeath)+l2;
4028: for (k1=1; k1<=(nlstate);k1++){
4029: for (l1=1; l1<=(nlstate+ndeath);l1++){
4030: if(l1==k1) continue;
4031: i=(k1-1)*(nlstate+ndeath)+l1;
4032: if(i<=j) continue;
4033: for (age=bage; age<=fage; age ++){
4034: if ((int)age %5==0){
4035: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4036: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4037: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4038: mu1=mu[i][(int) age]/stepm*YEARM ;
4039: mu2=mu[j][(int) age]/stepm*YEARM;
4040: c12=cv12/sqrt(v1*v2);
4041: /* Computing eigen value of matrix of covariance */
4042: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4043: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4044: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4045: if(first2==1){
4046: first1=0;
4047: 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);
4048: }
4049: 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);
4050: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4051: /* lc2=fabs(lc2); */
1.135 brouard 4052: }
4053:
1.126 brouard 4054: /* Eigen vectors */
4055: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4056: /*v21=sqrt(1.-v11*v11); *//* error */
4057: v21=(lc1-v1)/cv12*v11;
4058: v12=-v21;
4059: v22=v11;
4060: tnalp=v21/v11;
4061: if(first1==1){
4062: first1=0;
4063: 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);
4064: }
4065: 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);
4066: /*printf(fignu*/
4067: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4068: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4069: if(first==1){
4070: first=0;
4071: fprintf(ficgp,"\nset parametric;unset label");
4072: 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);
1.145 brouard 4073: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4074: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4075: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4076: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4077: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4078: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4079: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4080: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4081: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4082: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4083: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4084: 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",\
4085: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4086: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4087: }else{
4088: first=0;
4089: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4090: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4091: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4092: 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",\
4093: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4094: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4095: }/* if first */
4096: } /* age mod 5 */
4097: } /* end loop age */
4098: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4099: first=1;
4100: } /*l12 */
4101: } /* k12 */
4102: } /*l1 */
4103: }/* k1 */
1.169 brouard 4104: /* } */ /* loop covariates */
1.126 brouard 4105: }
4106: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4107: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4108: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4109: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4110: free_vector(xp,1,npar);
4111: fclose(ficresprob);
4112: fclose(ficresprobcov);
4113: fclose(ficresprobcor);
4114: fflush(ficgp);
4115: fflush(fichtmcov);
4116: }
4117:
4118:
4119: /******************* Printing html file ***********/
4120: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4121: int lastpass, int stepm, int weightopt, char model[],\
4122: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4123: int popforecast, int estepm ,\
4124: double jprev1, double mprev1,double anprev1, \
4125: double jprev2, double mprev2,double anprev2){
4126: int jj1, k1, i1, cpt;
4127:
4128: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4129: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4130: </ul>");
4131: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4132: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4133: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4134: fprintf(fichtm,"\
4135: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4136: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4137: fprintf(fichtm,"\
4138: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4139: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4140: fprintf(fichtm,"\
1.128 brouard 4141: - (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): \
1.126 brouard 4142: <a href=\"%s\">%s</a> <br>\n",
4143: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4144: fprintf(fichtm,"\
4145: - Population projections by age and states: \
4146: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4147:
4148: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4149:
1.145 brouard 4150: m=pow(2,cptcoveff);
1.126 brouard 4151: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4152:
4153: jj1=0;
4154: for(k1=1; k1<=m;k1++){
4155: for(i1=1; i1<=ncodemax[k1];i1++){
4156: jj1++;
4157: if (cptcovn > 0) {
4158: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4159: for (cpt=1; cpt<=cptcoveff;cpt++)
4160: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4161: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4162: }
4163: /* Pij */
1.145 brouard 4164: 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> \
4165: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4166: /* Quasi-incidences */
4167: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4168: 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> \
4169: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4170: /* Period (stable) prevalence in each health state */
1.154 brouard 4171: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4172: 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> \
4173: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126 brouard 4174: }
4175: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4176: 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> \
4177: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
1.126 brouard 4178: }
4179: } /* end i1 */
4180: }/* End k1 */
4181: fprintf(fichtm,"</ul>");
4182:
4183:
4184: fprintf(fichtm,"\
4185: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4186: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4187:
4188: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4189: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4190: fprintf(fichtm,"\
4191: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4192: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4193:
4194: fprintf(fichtm,"\
4195: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4196: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4197: fprintf(fichtm,"\
4198: - 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): \
4199: <a href=\"%s\">%s</a> <br>\n</li>",
4200: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4201: fprintf(fichtm,"\
4202: - (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): \
4203: <a href=\"%s\">%s</a> <br>\n</li>",
4204: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4205: fprintf(fichtm,"\
1.128 brouard 4206: - 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",
1.126 brouard 4207: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4208: fprintf(fichtm,"\
1.128 brouard 4209: - 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",
4210: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4211: fprintf(fichtm,"\
4212: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4213: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4214:
4215: /* if(popforecast==1) fprintf(fichtm,"\n */
4216: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4217: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4218: /* <br>",fileres,fileres,fileres,fileres); */
4219: /* else */
4220: /* 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); */
4221: fflush(fichtm);
4222: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4223:
1.145 brouard 4224: m=pow(2,cptcoveff);
1.126 brouard 4225: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4226:
4227: jj1=0;
4228: for(k1=1; k1<=m;k1++){
4229: for(i1=1; i1<=ncodemax[k1];i1++){
4230: jj1++;
4231: if (cptcovn > 0) {
4232: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4233: for (cpt=1; cpt<=cptcoveff;cpt++)
4234: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4235: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4236: }
4237: for(cpt=1; cpt<=nlstate;cpt++) {
4238: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4239: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4240: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4241: }
4242: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4243: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4244: true period expectancies (those weighted with period prevalences are also\
4245: drawn in addition to the population based expectancies computed using\
4246: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4247: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4248: } /* end i1 */
4249: }/* End k1 */
4250: fprintf(fichtm,"</ul>");
4251: fflush(fichtm);
4252: }
4253:
4254: /******************* Gnuplot file **************/
4255: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4256:
4257: char dirfileres[132],optfileres[132];
1.164 brouard 4258: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4259: int ng=0;
1.126 brouard 4260: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4261: /* printf("Problem with file %s",optionfilegnuplot); */
4262: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4263: /* } */
4264:
4265: /*#ifdef windows */
4266: fprintf(ficgp,"cd \"%s\" \n",pathc);
4267: /*#endif */
4268: m=pow(2,cptcoveff);
4269:
4270: strcpy(dirfileres,optionfilefiname);
4271: strcpy(optfileres,"vpl");
4272: /* 1eme*/
1.153 brouard 4273: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4274: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4275: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4276: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4277: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4278: fprintf(ficgp,"set xlabel \"Age\" \n\
4279: set ylabel \"Probability\" \n\
1.145 brouard 4280: set ter png small size 320, 240\n\
1.170 brouard 4281: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4282:
4283: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4284: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4285: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4286: }
1.170 brouard 4287: 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);
1.126 brouard 4288: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4289: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4290: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4291: }
1.170 brouard 4292: 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);
1.126 brouard 4293: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4294: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4295: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4296: }
1.145 brouard 4297: 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));
1.126 brouard 4298: }
4299: }
4300: /*2 eme*/
1.153 brouard 4301: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4302: for (k1=1; k1<= m ; k1 ++) {
4303: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4304: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4305:
4306: for (i=1; i<= nlstate+1 ; i ++) {
4307: k=2*i;
1.170 brouard 4308: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4309: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4310: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4311: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4312: }
4313: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4314: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4315: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4316: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4317: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4318: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4319: }
1.145 brouard 4320: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4321: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4322: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4323: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4324: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4325: }
1.145 brouard 4326: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4327: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4328: }
4329: }
4330:
4331: /*3eme*/
4332:
4333: for (k1=1; k1<= m ; k1 ++) {
4334: for (cpt=1; cpt<= nlstate ; cpt ++) {
4335: /* k=2+nlstate*(2*cpt-2); */
4336: k=2+(nlstate+1)*(cpt-1);
4337: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4338: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4339: 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);
4340: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4341: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4342: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4343: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4344: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4345: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4346:
4347: */
4348: for (i=1; i< nlstate ; i ++) {
4349: 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);
4350: /* 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);*/
4351:
4352: }
4353: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4354: }
4355: }
4356:
4357: /* CV preval stable (period) */
1.153 brouard 4358: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4359: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4360: k=3;
1.153 brouard 4361: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4362: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4363: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4364: set ter png small size 320, 240\n\
1.126 brouard 4365: unset log y\n\
1.153 brouard 4366: plot [%.f:%.f] ", ageminpar, agemaxpar);
4367: for (i=1; i<= nlstate ; i ++){
4368: if(i==1)
4369: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4370: else
4371: fprintf(ficgp,", '' ");
1.154 brouard 4372: l=(nlstate+ndeath)*(i-1)+1;
4373: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4374: for (j=1; j<= (nlstate-1) ; j ++)
4375: fprintf(ficgp,"+$%d",k+l+j);
4376: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4377: } /* nlstate */
4378: fprintf(ficgp,"\n");
4379: } /* end cpt state*/
4380: } /* end covariate */
1.126 brouard 4381:
4382: /* proba elementaires */
4383: for(i=1,jk=1; i <=nlstate; i++){
4384: for(k=1; k <=(nlstate+ndeath); k++){
4385: if (k != i) {
4386: for(j=1; j <=ncovmodel; j++){
4387: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4388: jk++;
4389: fprintf(ficgp,"\n");
4390: }
4391: }
4392: }
4393: }
1.145 brouard 4394: /*goto avoid;*/
1.126 brouard 4395: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4396: for(jk=1; jk <=m; jk++) {
1.145 brouard 4397: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4398: if (ng==2)
4399: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4400: else
4401: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4402: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4403: i=1;
4404: for(k2=1; k2<=nlstate; k2++) {
4405: k3=i;
4406: for(k=1; k<=(nlstate+ndeath); k++) {
4407: if (k != k2){
4408: if(ng==2)
4409: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4410: else
4411: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4412: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4413: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4414: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4415: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4416: /* ij++; */
4417: /* } */
4418: /* else */
1.126 brouard 4419: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4420: }
4421: fprintf(ficgp,")/(1");
4422:
4423: for(k1=1; k1 <=nlstate; k1++){
4424: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4425: ij=1;
4426: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4427: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4428: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4429: /* ij++; */
4430: /* } */
4431: /* else */
1.126 brouard 4432: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4433: }
4434: fprintf(ficgp,")");
4435: }
4436: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4437: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4438: i=i+ncovmodel;
4439: }
4440: } /* end k */
4441: } /* end k2 */
4442: } /* end jk */
4443: } /* end ng */
1.164 brouard 4444: /* avoid: */
1.126 brouard 4445: fflush(ficgp);
4446: } /* end gnuplot */
4447:
4448:
4449: /*************** Moving average **************/
4450: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4451:
4452: int i, cpt, cptcod;
4453: int modcovmax =1;
4454: int mobilavrange, mob;
4455: double age;
4456:
4457: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4458: a covariate has 2 modalities */
4459: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4460:
4461: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4462: if(mobilav==1) mobilavrange=5; /* default */
4463: else mobilavrange=mobilav;
4464: for (age=bage; age<=fage; age++)
4465: for (i=1; i<=nlstate;i++)
4466: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4467: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4468: /* We keep the original values on the extreme ages bage, fage and for
4469: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4470: we use a 5 terms etc. until the borders are no more concerned.
4471: */
4472: for (mob=3;mob <=mobilavrange;mob=mob+2){
4473: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4474: for (i=1; i<=nlstate;i++){
4475: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4476: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4477: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4478: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4479: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4480: }
4481: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4482: }
4483: }
4484: }/* end age */
4485: }/* end mob */
4486: }else return -1;
4487: return 0;
4488: }/* End movingaverage */
4489:
4490:
4491: /************** Forecasting ******************/
1.169 brouard 4492: 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){
1.126 brouard 4493: /* proj1, year, month, day of starting projection
4494: agemin, agemax range of age
4495: dateprev1 dateprev2 range of dates during which prevalence is computed
4496: anproj2 year of en of projection (same day and month as proj1).
4497: */
1.164 brouard 4498: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4499: double agec; /* generic age */
4500: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4501: double *popeffectif,*popcount;
4502: double ***p3mat;
4503: double ***mobaverage;
4504: char fileresf[FILENAMELENGTH];
4505:
4506: agelim=AGESUP;
4507: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4508:
4509: strcpy(fileresf,"f");
4510: strcat(fileresf,fileres);
4511: if((ficresf=fopen(fileresf,"w"))==NULL) {
4512: printf("Problem with forecast resultfile: %s\n", fileresf);
4513: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4514: }
4515: printf("Computing forecasting: result on file '%s' \n", fileresf);
4516: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4517:
4518: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4519:
4520: if (mobilav!=0) {
4521: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4522: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4523: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4524: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4525: }
4526: }
4527:
4528: stepsize=(int) (stepm+YEARM-1)/YEARM;
4529: if (stepm<=12) stepsize=1;
4530: if(estepm < stepm){
4531: printf ("Problem %d lower than %d\n",estepm, stepm);
4532: }
4533: else hstepm=estepm;
4534:
4535: hstepm=hstepm/stepm;
4536: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4537: fractional in yp1 */
4538: anprojmean=yp;
4539: yp2=modf((yp1*12),&yp);
4540: mprojmean=yp;
4541: yp1=modf((yp2*30.5),&yp);
4542: jprojmean=yp;
4543: if(jprojmean==0) jprojmean=1;
4544: if(mprojmean==0) jprojmean=1;
4545:
4546: i1=cptcoveff;
4547: if (cptcovn < 1){i1=1;}
4548:
4549: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4550:
4551: fprintf(ficresf,"#****** Routine prevforecast **\n");
4552:
4553: /* if (h==(int)(YEARM*yearp)){ */
4554: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4555: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4556: k=k+1;
4557: fprintf(ficresf,"\n#******");
4558: for(j=1;j<=cptcoveff;j++) {
4559: 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]]);
4560: }
4561: fprintf(ficresf,"******\n");
4562: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4563: for(j=1; j<=nlstate+ndeath;j++){
4564: for(i=1; i<=nlstate;i++)
4565: fprintf(ficresf," p%d%d",i,j);
4566: fprintf(ficresf," p.%d",j);
4567: }
4568: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4569: fprintf(ficresf,"\n");
4570: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4571:
4572: for (agec=fage; agec>=(ageminpar-1); agec--){
4573: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4574: nhstepm = nhstepm/hstepm;
4575: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4576: oldm=oldms;savm=savms;
4577: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4578:
4579: for (h=0; h<=nhstepm; h++){
4580: if (h*hstepm/YEARM*stepm ==yearp) {
4581: fprintf(ficresf,"\n");
4582: for(j=1;j<=cptcoveff;j++)
4583: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4584: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4585: }
4586: for(j=1; j<=nlstate+ndeath;j++) {
4587: ppij=0.;
4588: for(i=1; i<=nlstate;i++) {
4589: if (mobilav==1)
4590: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4591: else {
4592: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4593: }
4594: if (h*hstepm/YEARM*stepm== yearp) {
4595: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4596: }
4597: } /* end i */
4598: if (h*hstepm/YEARM*stepm==yearp) {
4599: fprintf(ficresf," %.3f", ppij);
4600: }
4601: }/* end j */
4602: } /* end h */
4603: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4604: } /* end agec */
4605: } /* end yearp */
4606: } /* end cptcod */
4607: } /* end cptcov */
4608:
4609: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4610:
4611: fclose(ficresf);
4612: }
4613:
4614: /************** Forecasting *****not tested NB*************/
1.169 brouard 4615: 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){
1.126 brouard 4616:
4617: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4618: int *popage;
4619: double calagedatem, agelim, kk1, kk2;
4620: double *popeffectif,*popcount;
4621: double ***p3mat,***tabpop,***tabpopprev;
4622: double ***mobaverage;
4623: char filerespop[FILENAMELENGTH];
4624:
4625: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4626: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4627: agelim=AGESUP;
4628: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4629:
4630: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4631:
4632:
4633: strcpy(filerespop,"pop");
4634: strcat(filerespop,fileres);
4635: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4636: printf("Problem with forecast resultfile: %s\n", filerespop);
4637: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4638: }
4639: printf("Computing forecasting: result on file '%s' \n", filerespop);
4640: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4641:
4642: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4643:
4644: if (mobilav!=0) {
4645: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4646: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4647: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4648: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4649: }
4650: }
4651:
4652: stepsize=(int) (stepm+YEARM-1)/YEARM;
4653: if (stepm<=12) stepsize=1;
4654:
4655: agelim=AGESUP;
4656:
4657: hstepm=1;
4658: hstepm=hstepm/stepm;
4659:
4660: if (popforecast==1) {
4661: if((ficpop=fopen(popfile,"r"))==NULL) {
4662: printf("Problem with population file : %s\n",popfile);exit(0);
4663: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4664: }
4665: popage=ivector(0,AGESUP);
4666: popeffectif=vector(0,AGESUP);
4667: popcount=vector(0,AGESUP);
4668:
4669: i=1;
4670: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4671:
4672: imx=i;
4673: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4674: }
4675:
4676: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4677: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4678: k=k+1;
4679: fprintf(ficrespop,"\n#******");
4680: for(j=1;j<=cptcoveff;j++) {
4681: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4682: }
4683: fprintf(ficrespop,"******\n");
4684: fprintf(ficrespop,"# Age");
4685: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4686: if (popforecast==1) fprintf(ficrespop," [Population]");
4687:
4688: for (cpt=0; cpt<=0;cpt++) {
4689: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4690:
4691: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4692: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4693: nhstepm = nhstepm/hstepm;
4694:
4695: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4696: oldm=oldms;savm=savms;
4697: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4698:
4699: for (h=0; h<=nhstepm; h++){
4700: if (h==(int) (calagedatem+YEARM*cpt)) {
4701: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4702: }
4703: for(j=1; j<=nlstate+ndeath;j++) {
4704: kk1=0.;kk2=0;
4705: for(i=1; i<=nlstate;i++) {
4706: if (mobilav==1)
4707: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4708: else {
4709: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4710: }
4711: }
4712: if (h==(int)(calagedatem+12*cpt)){
4713: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4714: /*fprintf(ficrespop," %.3f", kk1);
4715: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4716: }
4717: }
4718: for(i=1; i<=nlstate;i++){
4719: kk1=0.;
4720: for(j=1; j<=nlstate;j++){
4721: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4722: }
4723: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4724: }
4725:
4726: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4727: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4728: }
4729: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4730: }
4731: }
4732:
4733: /******/
4734:
4735: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4736: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4737: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4738: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4739: nhstepm = nhstepm/hstepm;
4740:
4741: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4742: oldm=oldms;savm=savms;
4743: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4744: for (h=0; h<=nhstepm; h++){
4745: if (h==(int) (calagedatem+YEARM*cpt)) {
4746: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4747: }
4748: for(j=1; j<=nlstate+ndeath;j++) {
4749: kk1=0.;kk2=0;
4750: for(i=1; i<=nlstate;i++) {
4751: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4752: }
4753: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4754: }
4755: }
4756: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4757: }
4758: }
4759: }
4760: }
4761:
4762: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4763:
4764: if (popforecast==1) {
4765: free_ivector(popage,0,AGESUP);
4766: free_vector(popeffectif,0,AGESUP);
4767: free_vector(popcount,0,AGESUP);
4768: }
4769: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4770: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4771: fclose(ficrespop);
4772: } /* End of popforecast */
4773:
4774: int fileappend(FILE *fichier, char *optionfich)
4775: {
4776: if((fichier=fopen(optionfich,"a"))==NULL) {
4777: printf("Problem with file: %s\n", optionfich);
4778: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4779: return (0);
4780: }
4781: fflush(fichier);
4782: return (1);
4783: }
4784:
4785:
4786: /**************** function prwizard **********************/
4787: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4788: {
4789:
4790: /* Wizard to print covariance matrix template */
4791:
1.164 brouard 4792: char ca[32], cb[32];
4793: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4794: int numlinepar;
4795:
4796: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4797: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4798: for(i=1; i <=nlstate; i++){
4799: jj=0;
4800: for(j=1; j <=nlstate+ndeath; j++){
4801: if(j==i) continue;
4802: jj++;
4803: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4804: printf("%1d%1d",i,j);
4805: fprintf(ficparo,"%1d%1d",i,j);
4806: for(k=1; k<=ncovmodel;k++){
4807: /* printf(" %lf",param[i][j][k]); */
4808: /* fprintf(ficparo," %lf",param[i][j][k]); */
4809: printf(" 0.");
4810: fprintf(ficparo," 0.");
4811: }
4812: printf("\n");
4813: fprintf(ficparo,"\n");
4814: }
4815: }
4816: printf("# Scales (for hessian or gradient estimation)\n");
4817: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4818: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4819: for(i=1; i <=nlstate; i++){
4820: jj=0;
4821: for(j=1; j <=nlstate+ndeath; j++){
4822: if(j==i) continue;
4823: jj++;
4824: fprintf(ficparo,"%1d%1d",i,j);
4825: printf("%1d%1d",i,j);
4826: fflush(stdout);
4827: for(k=1; k<=ncovmodel;k++){
4828: /* printf(" %le",delti3[i][j][k]); */
4829: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4830: printf(" 0.");
4831: fprintf(ficparo," 0.");
4832: }
4833: numlinepar++;
4834: printf("\n");
4835: fprintf(ficparo,"\n");
4836: }
4837: }
4838: printf("# Covariance matrix\n");
4839: /* # 121 Var(a12)\n\ */
4840: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4841: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4842: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4843: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4844: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4845: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4846: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4847: fflush(stdout);
4848: fprintf(ficparo,"# Covariance matrix\n");
4849: /* # 121 Var(a12)\n\ */
4850: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4851: /* # ...\n\ */
4852: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4853:
4854: for(itimes=1;itimes<=2;itimes++){
4855: jj=0;
4856: for(i=1; i <=nlstate; i++){
4857: for(j=1; j <=nlstate+ndeath; j++){
4858: if(j==i) continue;
4859: for(k=1; k<=ncovmodel;k++){
4860: jj++;
4861: ca[0]= k+'a'-1;ca[1]='\0';
4862: if(itimes==1){
4863: printf("#%1d%1d%d",i,j,k);
4864: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4865: }else{
4866: printf("%1d%1d%d",i,j,k);
4867: fprintf(ficparo,"%1d%1d%d",i,j,k);
4868: /* printf(" %.5le",matcov[i][j]); */
4869: }
4870: ll=0;
4871: for(li=1;li <=nlstate; li++){
4872: for(lj=1;lj <=nlstate+ndeath; lj++){
4873: if(lj==li) continue;
4874: for(lk=1;lk<=ncovmodel;lk++){
4875: ll++;
4876: if(ll<=jj){
4877: cb[0]= lk +'a'-1;cb[1]='\0';
4878: if(ll<jj){
4879: if(itimes==1){
4880: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4881: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4882: }else{
4883: printf(" 0.");
4884: fprintf(ficparo," 0.");
4885: }
4886: }else{
4887: if(itimes==1){
4888: printf(" Var(%s%1d%1d)",ca,i,j);
4889: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4890: }else{
4891: printf(" 0.");
4892: fprintf(ficparo," 0.");
4893: }
4894: }
4895: }
4896: } /* end lk */
4897: } /* end lj */
4898: } /* end li */
4899: printf("\n");
4900: fprintf(ficparo,"\n");
4901: numlinepar++;
4902: } /* end k*/
4903: } /*end j */
4904: } /* end i */
4905: } /* end itimes */
4906:
4907: } /* end of prwizard */
4908: /******************* Gompertz Likelihood ******************************/
4909: double gompertz(double x[])
4910: {
4911: double A,B,L=0.0,sump=0.,num=0.;
4912: int i,n=0; /* n is the size of the sample */
4913:
4914: for (i=0;i<=imx-1 ; i++) {
4915: sump=sump+weight[i];
4916: /* sump=sump+1;*/
4917: num=num+1;
4918: }
4919:
4920:
4921: /* for (i=0; i<=imx; i++)
4922: 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]);*/
4923:
4924: for (i=1;i<=imx ; i++)
4925: {
4926: if (cens[i] == 1 && wav[i]>1)
4927: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4928:
4929: if (cens[i] == 0 && wav[i]>1)
4930: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4931: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4932:
4933: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4934: if (wav[i] > 1 ) { /* ??? */
4935: L=L+A*weight[i];
4936: /* 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]);*/
4937: }
4938: }
4939:
4940: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4941:
4942: return -2*L*num/sump;
4943: }
4944:
1.136 brouard 4945: #ifdef GSL
4946: /******************* Gompertz_f Likelihood ******************************/
4947: double gompertz_f(const gsl_vector *v, void *params)
4948: {
4949: double A,B,LL=0.0,sump=0.,num=0.;
4950: double *x= (double *) v->data;
4951: int i,n=0; /* n is the size of the sample */
4952:
4953: for (i=0;i<=imx-1 ; i++) {
4954: sump=sump+weight[i];
4955: /* sump=sump+1;*/
4956: num=num+1;
4957: }
4958:
4959:
4960: /* for (i=0; i<=imx; i++)
4961: 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]);*/
4962: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4963: for (i=1;i<=imx ; i++)
4964: {
4965: if (cens[i] == 1 && wav[i]>1)
4966: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4967:
4968: if (cens[i] == 0 && wav[i]>1)
4969: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4970: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4971:
4972: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4973: if (wav[i] > 1 ) { /* ??? */
4974: LL=LL+A*weight[i];
4975: /* 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]);*/
4976: }
4977: }
4978:
4979: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4980: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4981:
4982: return -2*LL*num/sump;
4983: }
4984: #endif
4985:
1.126 brouard 4986: /******************* Printing html file ***********/
4987: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4988: int lastpass, int stepm, int weightopt, char model[],\
4989: int imx, double p[],double **matcov,double agemortsup){
4990: int i,k;
4991:
4992: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4993: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4994: for (i=1;i<=2;i++)
4995: 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]));
4996: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4997: fprintf(fichtm,"</ul>");
4998:
4999: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5000:
5001: 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>");
5002:
5003: for (k=agegomp;k<(agemortsup-2);k++)
5004: 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]);
5005:
5006:
5007: fflush(fichtm);
5008: }
5009:
5010: /******************* Gnuplot file **************/
5011: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5012:
5013: char dirfileres[132],optfileres[132];
1.164 brouard 5014:
1.126 brouard 5015: int ng;
5016:
5017:
5018: /*#ifdef windows */
5019: fprintf(ficgp,"cd \"%s\" \n",pathc);
5020: /*#endif */
5021:
5022:
5023: strcpy(dirfileres,optionfilefiname);
5024: strcpy(optfileres,"vpl");
5025: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5026: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5027: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5028: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5029: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5030:
5031: }
5032:
1.136 brouard 5033: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5034: {
1.126 brouard 5035:
1.136 brouard 5036: /*-------- data file ----------*/
5037: FILE *fic;
5038: char dummy[]=" ";
1.164 brouard 5039: int i=0, j=0, n=0;
1.136 brouard 5040: int linei, month, year,iout;
5041: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5042: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5043: char *stratrunc;
5044: int lstra;
1.126 brouard 5045:
5046:
1.136 brouard 5047: if((fic=fopen(datafile,"r"))==NULL) {
5048: printf("Problem while opening datafile: %s\n", datafile);return 1;
5049: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5050: }
1.126 brouard 5051:
1.136 brouard 5052: i=1;
5053: linei=0;
5054: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5055: linei=linei+1;
5056: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5057: if(line[j] == '\t')
5058: line[j] = ' ';
5059: }
5060: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5061: ;
5062: };
5063: line[j+1]=0; /* Trims blanks at end of line */
5064: if(line[0]=='#'){
5065: fprintf(ficlog,"Comment line\n%s\n",line);
5066: printf("Comment line\n%s\n",line);
5067: continue;
5068: }
5069: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5070: strcpy(line, linetmp);
1.136 brouard 5071:
1.126 brouard 5072:
1.136 brouard 5073: for (j=maxwav;j>=1;j--){
1.137 brouard 5074: cutv(stra, strb, line, ' ');
1.136 brouard 5075: if(strb[0]=='.') { /* Missing status */
5076: lval=-1;
5077: }else{
5078: errno=0;
5079: lval=strtol(strb,&endptr,10);
5080: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5081: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5082: 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);
5083: 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);
1.136 brouard 5084: return 1;
5085: }
5086: }
5087: s[j][i]=lval;
5088:
5089: strcpy(line,stra);
5090: cutv(stra, strb,line,' ');
1.169 brouard 5091: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5092: }
1.169 brouard 5093: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5094: month=99;
5095: year=9999;
5096: }else{
1.141 brouard 5097: 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);
5098: 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);
1.136 brouard 5099: return 1;
5100: }
5101: anint[j][i]= (double) year;
5102: mint[j][i]= (double)month;
5103: strcpy(line,stra);
5104: } /* ENd Waves */
5105:
5106: cutv(stra, strb,line,' ');
1.169 brouard 5107: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5108: }
1.169 brouard 5109: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5110: month=99;
5111: year=9999;
5112: }else{
1.141 brouard 5113: 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);
5114: 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);
1.136 brouard 5115: return 1;
5116: }
5117: andc[i]=(double) year;
5118: moisdc[i]=(double) month;
5119: strcpy(line,stra);
5120:
5121: cutv(stra, strb,line,' ');
1.169 brouard 5122: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5123: }
1.169 brouard 5124: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5125: month=99;
5126: year=9999;
5127: }else{
1.141 brouard 5128: 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);
5129: 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);
1.136 brouard 5130: return 1;
5131: }
5132: if (year==9999) {
1.141 brouard 5133: 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);
5134: 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);
1.136 brouard 5135: return 1;
1.126 brouard 5136:
1.136 brouard 5137: }
5138: annais[i]=(double)(year);
5139: moisnais[i]=(double)(month);
5140: strcpy(line,stra);
5141:
5142: cutv(stra, strb,line,' ');
5143: errno=0;
5144: dval=strtod(strb,&endptr);
5145: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5146: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5147: 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);
1.136 brouard 5148: fflush(ficlog);
5149: return 1;
5150: }
5151: weight[i]=dval;
5152: strcpy(line,stra);
5153:
5154: for (j=ncovcol;j>=1;j--){
5155: cutv(stra, strb,line,' ');
5156: if(strb[0]=='.') { /* Missing status */
5157: lval=-1;
5158: }else{
5159: errno=0;
5160: lval=strtol(strb,&endptr,10);
5161: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5162: 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);
5163: 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);
1.136 brouard 5164: return 1;
5165: }
5166: }
5167: if(lval <-1 || lval >1){
1.141 brouard 5168: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5169: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5170: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5171: For example, for multinomial values like 1, 2 and 3,\n \
5172: build V1=0 V2=0 for the reference value (1),\n \
5173: V1=1 V2=0 for (2) \n \
5174: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5175: output of IMaCh is often meaningless.\n \
5176: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5177: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5178: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5179: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5180: For example, for multinomial values like 1, 2 and 3,\n \
5181: build V1=0 V2=0 for the reference value (1),\n \
5182: V1=1 V2=0 for (2) \n \
5183: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5184: output of IMaCh is often meaningless.\n \
5185: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5186: return 1;
5187: }
5188: covar[j][i]=(double)(lval);
5189: strcpy(line,stra);
5190: }
5191: lstra=strlen(stra);
5192:
5193: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5194: stratrunc = &(stra[lstra-9]);
5195: num[i]=atol(stratrunc);
5196: }
5197: else
5198: num[i]=atol(stra);
5199: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5200: 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;}*/
5201:
5202: i=i+1;
5203: } /* End loop reading data */
1.126 brouard 5204:
1.136 brouard 5205: *imax=i-1; /* Number of individuals */
5206: fclose(fic);
5207:
5208: return (0);
1.164 brouard 5209: /* endread: */
1.136 brouard 5210: printf("Exiting readdata: ");
5211: fclose(fic);
5212: return (1);
1.126 brouard 5213:
5214:
5215:
1.136 brouard 5216: }
1.145 brouard 5217: void removespace(char *str) {
5218: char *p1 = str, *p2 = str;
5219: do
5220: while (*p2 == ' ')
5221: p2++;
1.169 brouard 5222: while (*p1++ == *p2++);
1.145 brouard 5223: }
5224:
5225: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5226: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5227: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5228: * - cptcovn or number of covariates k of the models excluding age*products =6
5229: * - cptcovage number of covariates with age*products =2
5230: * - cptcovs number of simple covariates
5231: * - 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
5232: * which is a new column after the 9 (ncovcol) variables.
5233: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5234: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5235: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5236: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5237: */
1.136 brouard 5238: {
1.145 brouard 5239: int i, j, k, ks;
1.164 brouard 5240: int j1, k1, k2;
1.136 brouard 5241: char modelsav[80];
1.145 brouard 5242: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5243:
1.145 brouard 5244: /*removespace(model);*/
1.136 brouard 5245: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5246: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5247: j=nbocc(model,'+'); /**< j=Number of '+' */
5248: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5249: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5250: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5251: /* including age products which are counted in cptcovage.
1.169 brouard 5252: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5253: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5254: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5255: strcpy(modelsav,model);
1.137 brouard 5256: if (strstr(model,"AGE") !=0){
5257: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5258: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5259: return 1;
5260: }
1.141 brouard 5261: if (strstr(model,"v") !=0){
5262: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5263: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5264: return 1;
5265: }
1.136 brouard 5266:
1.145 brouard 5267: /* Design
5268: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5269: * < ncovcol=8 >
5270: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5271: * k= 1 2 3 4 5 6 7 8
5272: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5273: * covar[k,i], value of kth covariate if not including age for individual i:
5274: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5275: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5276: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5277: * Tage[++cptcovage]=k
5278: * if products, new covar are created after ncovcol with k1
5279: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5280: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5281: * 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
5282: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5283: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5284: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5285: * < ncovcol=8 >
5286: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5287: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5288: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5289: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5290: * p Tprod[1]@2={ 6, 5}
5291: *p Tvard[1][1]@4= {7, 8, 5, 6}
5292: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5293: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5294: *How to reorganize?
5295: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5296: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5297: * {2, 1, 4, 8, 5, 6, 3, 7}
5298: * Struct []
5299: */
5300:
1.136 brouard 5301: /* This loop fills the array Tvar from the string 'model'.*/
5302: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5303: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5304: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5305: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5306: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5307: /* k=1 Tvar[1]=2 (from V2) */
5308: /* k=5 Tvar[5] */
5309: /* for (k=1; k<=cptcovn;k++) { */
5310: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5311: /* } */
5312: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5313: /*
5314: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5315: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5316: Tvar[k]=0;
5317: cptcovage=0;
5318: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5319: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5320: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5321: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5322: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5323: /*scanf("%d",i);*/
1.145 brouard 5324: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5325: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5326: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5327: /* covar is not filled and then is empty */
1.136 brouard 5328: cptcovprod--;
1.145 brouard 5329: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5330: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5331: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5332: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5333: /*printf("stre=%s ", stre);*/
1.137 brouard 5334: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5335: cptcovprod--;
1.145 brouard 5336: cutl(stre,strb,strc,'V');
1.136 brouard 5337: Tvar[k]=atoi(stre);
5338: cptcovage++;
5339: Tage[cptcovage]=k;
1.137 brouard 5340: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5341: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5342: cptcovn++;
5343: cptcovprodnoage++;k1++;
5344: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5345: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5346: because this model-covariate is a construction we invent a new column
5347: ncovcol + k1
5348: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5349: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5350: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5351: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5352: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5353: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5354: k2=k2+2;
5355: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5356: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5357: for (i=1; i<=lastobs;i++){
5358: /* Computes the new covariate which is a product of
1.145 brouard 5359: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5360: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5361: }
5362: } /* End age is not in the model */
5363: } /* End if model includes a product */
1.136 brouard 5364: else { /* no more sum */
5365: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5366: /* scanf("%d",i);*/
1.145 brouard 5367: cutl(strd,strc,strb,'V');
5368: ks++; /**< Number of simple covariates */
5369: cptcovn++;
5370: Tvar[k]=atoi(strd);
1.136 brouard 5371: }
1.137 brouard 5372: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5373: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5374: scanf("%d",i);*/
5375: } /* end of loop + */
5376: } /* end model */
5377:
5378: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5379: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5380:
5381: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5382: printf("cptcovprod=%d ", cptcovprod);
5383: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5384:
5385: scanf("%d ",i);*/
5386:
5387:
1.137 brouard 5388: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5389: /*endread:*/
1.136 brouard 5390: printf("Exiting decodemodel: ");
5391: return (1);
5392: }
5393:
1.169 brouard 5394: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5395: {
5396: int i, m;
5397:
5398: for (i=1; i<=imx; i++) {
5399: for(m=2; (m<= maxwav); m++) {
5400: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5401: anint[m][i]=9999;
5402: s[m][i]=-1;
5403: }
5404: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5405: *nberr = *nberr + 1;
5406: 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);
5407: 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);
1.136 brouard 5408: s[m][i]=-1;
5409: }
5410: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5411: (*nberr)++;
1.136 brouard 5412: 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]);
5413: 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]);
5414: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5415: }
5416: }
5417: }
5418:
5419: for (i=1; i<=imx; i++) {
5420: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5421: for(m=firstpass; (m<= lastpass); m++){
5422: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5423: if (s[m][i] >= nlstate+1) {
1.169 brouard 5424: if(agedc[i]>0){
5425: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5426: agev[m][i]=agedc[i];
5427: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5428: }else {
1.136 brouard 5429: if ((int)andc[i]!=9999){
5430: nbwarn++;
5431: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5432: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5433: agev[m][i]=-1;
5434: }
5435: }
1.169 brouard 5436: } /* agedc > 0 */
1.136 brouard 5437: }
5438: else if(s[m][i] !=9){ /* Standard case, age in fractional
5439: years but with the precision of a month */
5440: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5441: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5442: agev[m][i]=1;
5443: else if(agev[m][i] < *agemin){
5444: *agemin=agev[m][i];
5445: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5446: }
5447: else if(agev[m][i] >*agemax){
5448: *agemax=agev[m][i];
1.156 brouard 5449: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5450: }
5451: /*agev[m][i]=anint[m][i]-annais[i];*/
5452: /* agev[m][i] = age[i]+2*m;*/
5453: }
5454: else { /* =9 */
5455: agev[m][i]=1;
5456: s[m][i]=-1;
5457: }
5458: }
5459: else /*= 0 Unknown */
5460: agev[m][i]=1;
5461: }
5462:
5463: }
5464: for (i=1; i<=imx; i++) {
5465: for(m=firstpass; (m<=lastpass); m++){
5466: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5467: (*nberr)++;
1.136 brouard 5468: 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);
5469: 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);
5470: return 1;
5471: }
5472: }
5473: }
5474:
5475: /*for (i=1; i<=imx; i++){
5476: for (m=firstpass; (m<lastpass); m++){
5477: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5478: }
5479:
5480: }*/
5481:
5482:
1.139 brouard 5483: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5484: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5485:
5486: return (0);
1.164 brouard 5487: /* endread:*/
1.136 brouard 5488: printf("Exiting calandcheckages: ");
5489: return (1);
5490: }
5491:
1.172 brouard 5492: #if defined(_MSC_VER)
5493: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5494: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5495: //#include "stdafx.h"
5496: //#include <stdio.h>
5497: //#include <tchar.h>
5498: //#include <windows.h>
5499: //#include <iostream>
5500: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5501:
5502: LPFN_ISWOW64PROCESS fnIsWow64Process;
5503:
5504: BOOL IsWow64()
5505: {
5506: BOOL bIsWow64 = FALSE;
5507:
5508: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5509: // (HANDLE, PBOOL);
5510:
5511: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5512:
5513: HMODULE module = GetModuleHandle(_T("kernel32"));
5514: const char funcName[] = "IsWow64Process";
5515: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5516: GetProcAddress(module, funcName);
5517:
5518: if (NULL != fnIsWow64Process)
5519: {
5520: if (!fnIsWow64Process(GetCurrentProcess(),
5521: &bIsWow64))
5522: //throw std::exception("Unknown error");
5523: printf("Unknown error\n");
5524: }
5525: return bIsWow64 != FALSE;
5526: }
5527: #endif
1.177 brouard 5528:
1.169 brouard 5529: void syscompilerinfo()
1.167 brouard 5530: {
5531: /* #include "syscompilerinfo.h"*/
1.177 brouard 5532:
5533: #if defined __INTEL_COMPILER
1.178 brouard 5534: #if defined(__GNUC__)
5535: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5536: #endif
1.177 brouard 5537: #elif defined(__GNUC__)
1.179 brouard 5538: #ifndef __APPLE__
1.174 brouard 5539: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5540: #endif
1.177 brouard 5541: struct utsname sysInfo;
1.178 brouard 5542: int cross = CROSS;
5543: if (cross){
5544: printf("Cross-");
5545: fprintf(ficlog, "Cross-");
5546: }
1.174 brouard 5547: #endif
5548:
1.171 brouard 5549: #include <stdint.h>
1.178 brouard 5550:
1.169 brouard 5551: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5552: #if defined(__clang__)
5553: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5554: #endif
5555: #if defined(__ICC) || defined(__INTEL_COMPILER)
5556: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5557: #endif
5558: #if defined(__GNUC__) || defined(__GNUG__)
5559: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5560: #endif
5561: #if defined(__HP_cc) || defined(__HP_aCC)
5562: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5563: #endif
5564: #if defined(__IBMC__) || defined(__IBMCPP__)
5565: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5566: #endif
5567: #if defined(_MSC_VER)
5568: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5569: #endif
5570: #if defined(__PGI)
5571: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5572: #endif
5573: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5574: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5575: #endif
1.174 brouard 5576: printf(" for ");fprintf(ficlog," for ");
1.169 brouard 5577:
1.167 brouard 5578: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5579: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5580: // Windows (x64 and x86)
1.174 brouard 5581: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 5582: #elif __unix__ // all unices, not all compilers
5583: // Unix
1.174 brouard 5584: printf("Unix ");fprintf(ficlog,"Unix ");
1.167 brouard 5585: #elif __linux__
5586: // linux
1.174 brouard 5587: printf("linux ");fprintf(ficlog,"linux ");
1.167 brouard 5588: #elif __APPLE__
1.174 brouard 5589: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5590: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167 brouard 5591: #endif
5592:
5593: /* __MINGW32__ */
5594: /* __CYGWIN__ */
5595: /* __MINGW64__ */
5596: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5597: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5598: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5599: /* _WIN64 // Defined for applications for Win64. */
5600: /* _M_X64 // Defined for compilations that target x64 processors. */
5601: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5602:
1.167 brouard 5603: #if UINTPTR_MAX == 0xffffffff
1.174 brouard 5604: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 5605: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174 brouard 5606: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 5607: #else
1.174 brouard 5608: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 5609: #endif
5610:
1.169 brouard 5611: #if defined(__GNUC__)
5612: # if defined(__GNUC_PATCHLEVEL__)
5613: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5614: + __GNUC_MINOR__ * 100 \
5615: + __GNUC_PATCHLEVEL__)
5616: # else
5617: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5618: + __GNUC_MINOR__ * 100)
5619: # endif
1.174 brouard 5620: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5621: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 5622:
5623: if (uname(&sysInfo) != -1) {
5624: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5625: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5626: }
5627: else
5628: perror("uname() error");
1.179 brouard 5629: //#ifndef __INTEL_COMPILER
5630: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 5631: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.179 brouard 5632: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 5633: #endif
1.169 brouard 5634: #endif
1.172 brouard 5635:
5636: // void main()
5637: // {
1.169 brouard 5638: #if defined(_MSC_VER)
1.174 brouard 5639: if (IsWow64()){
1.176 brouard 5640: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5641: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 5642: }
5643: else{
1.176 brouard 5644: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178 brouard 5645: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 5646: }
1.172 brouard 5647: // printf("\nPress Enter to continue...");
5648: // getchar();
5649: // }
5650:
1.169 brouard 5651: #endif
5652:
1.167 brouard 5653:
5654: }
1.136 brouard 5655:
1.180 brouard 5656: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5657: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5658: int i, j, k, i1 ;
5659: double ftolpl = 1.e-10;
5660: double age, agebase, agelim;
5661:
5662: strcpy(filerespl,"pl");
5663: strcat(filerespl,fileres);
5664: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5665: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5666: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5667: }
5668: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5669: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5670: pstamp(ficrespl);
5671: fprintf(ficrespl,"# Period (stable) prevalence \n");
5672: fprintf(ficrespl,"#Age ");
5673: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5674: fprintf(ficrespl,"\n");
5675:
5676: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5677:
5678: agebase=ageminpar;
5679: agelim=agemaxpar;
5680:
5681: i1=pow(2,cptcoveff);
5682: if (cptcovn < 1){i1=1;}
5683:
5684: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5685: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5686: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5687: k=k+1;
5688: /* to clean */
5689: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5690: fprintf(ficrespl,"\n#******");
5691: printf("\n#******");
5692: fprintf(ficlog,"\n#******");
5693: for(j=1;j<=cptcoveff;j++) {
5694: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5695: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5696: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5697: }
5698: fprintf(ficrespl,"******\n");
5699: printf("******\n");
5700: fprintf(ficlog,"******\n");
5701:
5702: fprintf(ficrespl,"#Age ");
5703: for(j=1;j<=cptcoveff;j++) {
5704: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5705: }
5706: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5707: fprintf(ficrespl,"\n");
5708:
5709: for (age=agebase; age<=agelim; age++){
5710: /* for (age=agebase; age<=agebase; age++){ */
5711: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5712: fprintf(ficrespl,"%.0f ",age );
5713: for(j=1;j<=cptcoveff;j++)
5714: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5715: for(i=1; i<=nlstate;i++)
5716: fprintf(ficrespl," %.5f", prlim[i][i]);
5717: fprintf(ficrespl,"\n");
5718: } /* Age */
5719: /* was end of cptcod */
5720: } /* cptcov */
5721: }
5722:
5723: int hPijx(double *p, int bage, int fage){
5724: /*------------- h Pij x at various ages ------------*/
5725:
5726: int stepsize;
5727: int agelim;
5728: int hstepm;
5729: int nhstepm;
5730: int h, i, i1, j, k;
5731:
5732: double agedeb;
5733: double ***p3mat;
5734:
5735: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5736: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5737: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5738: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5739: }
5740: printf("Computing pij: result on file '%s' \n", filerespij);
5741: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5742:
5743: stepsize=(int) (stepm+YEARM-1)/YEARM;
5744: /*if (stepm<=24) stepsize=2;*/
5745:
5746: agelim=AGESUP;
5747: hstepm=stepsize*YEARM; /* Every year of age */
5748: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5749:
5750: /* hstepm=1; aff par mois*/
5751: pstamp(ficrespij);
5752: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5753: i1= pow(2,cptcoveff);
5754: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5755: /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
5756: k=k+1;
5757: /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
5758: fprintf(ficrespij,"\n#****** ");
5759: for(j=1;j<=cptcoveff;j++)
5760: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5761: fprintf(ficrespij,"******\n");
5762:
5763: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5764: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5765: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5766:
5767: /* nhstepm=nhstepm*YEARM; aff par mois*/
5768:
5769: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5770: oldm=oldms;savm=savms;
5771: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5772: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5773: for(i=1; i<=nlstate;i++)
5774: for(j=1; j<=nlstate+ndeath;j++)
5775: fprintf(ficrespij," %1d-%1d",i,j);
5776: fprintf(ficrespij,"\n");
5777: for (h=0; h<=nhstepm; h++){
5778: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5779: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5780: for(i=1; i<=nlstate;i++)
5781: for(j=1; j<=nlstate+ndeath;j++)
5782: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5783: fprintf(ficrespij,"\n");
5784: }
5785: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5786: fprintf(ficrespij,"\n");
5787: }
5788: /*}*/
5789: }
5790: }
5791:
5792:
1.136 brouard 5793: /***********************************************/
5794: /**************** Main Program *****************/
5795: /***********************************************/
5796:
5797: int main(int argc, char *argv[])
5798: {
5799: #ifdef GSL
5800: const gsl_multimin_fminimizer_type *T;
5801: size_t iteri = 0, it;
5802: int rval = GSL_CONTINUE;
5803: int status = GSL_SUCCESS;
5804: double ssval;
5805: #endif
5806: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5807: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5808:
5809: int jj, ll, li, lj, lk;
1.136 brouard 5810: int numlinepar=0; /* Current linenumber of parameter file */
5811: int itimes;
5812: int NDIM=2;
5813: int vpopbased=0;
5814:
1.164 brouard 5815: char ca[32], cb[32];
1.136 brouard 5816: /* FILE *fichtm; *//* Html File */
5817: /* FILE *ficgp;*/ /*Gnuplot File */
5818: struct stat info;
1.164 brouard 5819: double agedeb;
1.136 brouard 5820: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5821:
1.165 brouard 5822: double fret;
1.136 brouard 5823: double dum; /* Dummy variable */
5824: double ***p3mat;
5825: double ***mobaverage;
1.164 brouard 5826:
5827: char line[MAXLINE];
1.136 brouard 5828: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5829: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5830: char *tok, *val; /* pathtot */
1.136 brouard 5831: int firstobs=1, lastobs=10;
1.164 brouard 5832: int c, h , cpt;
5833: int jl;
5834: int i1, j1, jk, stepsize;
5835: int *tab;
1.136 brouard 5836: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5837: int mobilav=0,popforecast=0;
5838: int hstepm, nhstepm;
5839: int agemortsup;
5840: float sumlpop=0.;
5841: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5842: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5843:
1.164 brouard 5844: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5845: double ftolpl=FTOL;
5846: double **prlim;
5847: double ***param; /* Matrix of parameters */
5848: double *p;
5849: double **matcov; /* Matrix of covariance */
5850: double ***delti3; /* Scale */
5851: double *delti; /* Scale */
5852: double ***eij, ***vareij;
5853: double **varpl; /* Variances of prevalence limits by age */
5854: double *epj, vepp;
1.164 brouard 5855:
1.136 brouard 5856: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5857: double **ximort;
1.145 brouard 5858: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5859: int *dcwave;
5860:
1.164 brouard 5861: char z[1]="c";
1.136 brouard 5862:
5863: /*char *strt;*/
5864: char strtend[80];
1.126 brouard 5865:
1.164 brouard 5866:
1.126 brouard 5867: /* setlocale (LC_ALL, ""); */
5868: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5869: /* textdomain (PACKAGE); */
5870: /* setlocale (LC_CTYPE, ""); */
5871: /* setlocale (LC_MESSAGES, ""); */
5872:
5873: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5874: rstart_time = time(NULL);
5875: /* (void) gettimeofday(&start_time,&tzp);*/
5876: start_time = *localtime(&rstart_time);
1.126 brouard 5877: curr_time=start_time;
1.157 brouard 5878: /*tml = *localtime(&start_time.tm_sec);*/
5879: /* strcpy(strstart,asctime(&tml)); */
5880: strcpy(strstart,asctime(&start_time));
1.126 brouard 5881:
5882: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5883: /* tp.tm_sec = tp.tm_sec +86400; */
5884: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5885: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5886: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5887: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5888: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5889: /* strt=asctime(&tmg); */
5890: /* printf("Time(after) =%s",strstart); */
5891: /* (void) time (&time_value);
5892: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5893: * tm = *localtime(&time_value);
5894: * strstart=asctime(&tm);
5895: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5896: */
5897:
5898: nberr=0; /* Number of errors and warnings */
5899: nbwarn=0;
5900: getcwd(pathcd, size);
5901:
5902: printf("\n%s\n%s",version,fullversion);
5903: if(argc <=1){
5904: printf("\nEnter the parameter file name: ");
5905: fgets(pathr,FILENAMELENGTH,stdin);
5906: i=strlen(pathr);
5907: if(pathr[i-1]=='\n')
5908: pathr[i-1]='\0';
1.156 brouard 5909: i=strlen(pathr);
5910: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5911: pathr[i-1]='\0';
1.126 brouard 5912: for (tok = pathr; tok != NULL; ){
5913: printf("Pathr |%s|\n",pathr);
5914: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5915: printf("val= |%s| pathr=%s\n",val,pathr);
5916: strcpy (pathtot, val);
5917: if(pathr[0] == '\0') break; /* Dirty */
5918: }
5919: }
5920: else{
5921: strcpy(pathtot,argv[1]);
5922: }
5923: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5924: /*cygwin_split_path(pathtot,path,optionfile);
5925: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5926: /* cutv(path,optionfile,pathtot,'\\');*/
5927:
5928: /* Split argv[0], imach program to get pathimach */
5929: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5930: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5931: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5932: /* strcpy(pathimach,argv[0]); */
5933: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5934: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5935: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5936: chdir(path); /* Can be a relative path */
5937: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5938: printf("Current directory %s!\n",pathcd);
5939: strcpy(command,"mkdir ");
5940: strcat(command,optionfilefiname);
5941: if((outcmd=system(command)) != 0){
1.169 brouard 5942: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 5943: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5944: /* fclose(ficlog); */
5945: /* exit(1); */
5946: }
5947: /* if((imk=mkdir(optionfilefiname))<0){ */
5948: /* perror("mkdir"); */
5949: /* } */
5950:
5951: /*-------- arguments in the command line --------*/
5952:
5953: /* Log file */
5954: strcat(filelog, optionfilefiname);
5955: strcat(filelog,".log"); /* */
5956: if((ficlog=fopen(filelog,"w"))==NULL) {
5957: printf("Problem with logfile %s\n",filelog);
5958: goto end;
5959: }
5960: fprintf(ficlog,"Log filename:%s\n",filelog);
5961: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5962: fprintf(ficlog,"\nEnter the parameter file name: \n");
5963: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5964: path=%s \n\
5965: optionfile=%s\n\
5966: optionfilext=%s\n\
1.156 brouard 5967: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5968:
1.167 brouard 5969: syscompilerinfo();
5970:
1.126 brouard 5971: printf("Local time (at start):%s",strstart);
5972: fprintf(ficlog,"Local time (at start): %s",strstart);
5973: fflush(ficlog);
5974: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5975: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5976:
5977: /* */
5978: strcpy(fileres,"r");
5979: strcat(fileres, optionfilefiname);
5980: strcat(fileres,".txt"); /* Other files have txt extension */
5981:
5982: /*---------arguments file --------*/
5983:
5984: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5985: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5986: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5987: fflush(ficlog);
1.149 brouard 5988: /* goto end; */
5989: exit(70);
1.126 brouard 5990: }
5991:
5992:
5993:
5994: strcpy(filereso,"o");
5995: strcat(filereso,fileres);
5996: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5997: printf("Problem with Output resultfile: %s\n", filereso);
5998: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5999: fflush(ficlog);
6000: goto end;
6001: }
6002:
6003: /* Reads comments: lines beginning with '#' */
6004: numlinepar=0;
6005: while((c=getc(ficpar))=='#' && c!= EOF){
6006: ungetc(c,ficpar);
6007: fgets(line, MAXLINE, ficpar);
6008: numlinepar++;
1.141 brouard 6009: fputs(line,stdout);
1.126 brouard 6010: fputs(line,ficparo);
6011: fputs(line,ficlog);
6012: }
6013: ungetc(c,ficpar);
6014:
6015: 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);
6016: numlinepar++;
6017: 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);
6018: 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);
6019: 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);
6020: fflush(ficlog);
6021: while((c=getc(ficpar))=='#' && c!= EOF){
6022: ungetc(c,ficpar);
6023: fgets(line, MAXLINE, ficpar);
6024: numlinepar++;
1.141 brouard 6025: fputs(line, stdout);
6026: //puts(line);
1.126 brouard 6027: fputs(line,ficparo);
6028: fputs(line,ficlog);
6029: }
6030: ungetc(c,ficpar);
6031:
6032:
1.145 brouard 6033: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6034: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6035: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6036: v1+v2*age+v2*v3 makes cptcovn = 3
6037: */
6038: if (strlen(model)>1)
1.145 brouard 6039: 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*/
6040: else
6041: ncovmodel=2;
1.126 brouard 6042: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 6043: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6044: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6045: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6046: 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);
6047: 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);
6048: fflush(stdout);
6049: fclose (ficlog);
6050: goto end;
6051: }
1.126 brouard 6052: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6053: delti=delti3[1][1];
6054: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6055: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6056: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6057: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6058: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6059: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6060: fclose (ficparo);
6061: fclose (ficlog);
6062: goto end;
6063: exit(0);
6064: }
6065: else if(mle==-3) {
6066: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6067: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6068: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6069: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6070: matcov=matrix(1,npar,1,npar);
6071: }
6072: else{
1.145 brouard 6073: /* Read guessed parameters */
1.126 brouard 6074: /* Reads comments: lines beginning with '#' */
6075: while((c=getc(ficpar))=='#' && c!= EOF){
6076: ungetc(c,ficpar);
6077: fgets(line, MAXLINE, ficpar);
6078: numlinepar++;
1.141 brouard 6079: fputs(line,stdout);
1.126 brouard 6080: fputs(line,ficparo);
6081: fputs(line,ficlog);
6082: }
6083: ungetc(c,ficpar);
6084:
6085: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6086: for(i=1; i <=nlstate; i++){
6087: j=0;
6088: for(jj=1; jj <=nlstate+ndeath; jj++){
6089: if(jj==i) continue;
6090: j++;
6091: fscanf(ficpar,"%1d%1d",&i1,&j1);
6092: if ((i1 != i) && (j1 != j)){
6093: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6094: It might be a problem of design; if ncovcol and the model are correct\n \
6095: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6096: exit(1);
6097: }
6098: fprintf(ficparo,"%1d%1d",i1,j1);
6099: if(mle==1)
6100: printf("%1d%1d",i,j);
6101: fprintf(ficlog,"%1d%1d",i,j);
6102: for(k=1; k<=ncovmodel;k++){
6103: fscanf(ficpar," %lf",¶m[i][j][k]);
6104: if(mle==1){
6105: printf(" %lf",param[i][j][k]);
6106: fprintf(ficlog," %lf",param[i][j][k]);
6107: }
6108: else
6109: fprintf(ficlog," %lf",param[i][j][k]);
6110: fprintf(ficparo," %lf",param[i][j][k]);
6111: }
6112: fscanf(ficpar,"\n");
6113: numlinepar++;
6114: if(mle==1)
6115: printf("\n");
6116: fprintf(ficlog,"\n");
6117: fprintf(ficparo,"\n");
6118: }
6119: }
6120: fflush(ficlog);
6121:
1.145 brouard 6122: /* Reads scales values */
1.126 brouard 6123: p=param[1][1];
6124:
6125: /* Reads comments: lines beginning with '#' */
6126: while((c=getc(ficpar))=='#' && c!= EOF){
6127: ungetc(c,ficpar);
6128: fgets(line, MAXLINE, ficpar);
6129: numlinepar++;
1.141 brouard 6130: fputs(line,stdout);
1.126 brouard 6131: fputs(line,ficparo);
6132: fputs(line,ficlog);
6133: }
6134: ungetc(c,ficpar);
6135:
6136: for(i=1; i <=nlstate; i++){
6137: for(j=1; j <=nlstate+ndeath-1; j++){
6138: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6139: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6140: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6141: exit(1);
6142: }
6143: printf("%1d%1d",i,j);
6144: fprintf(ficparo,"%1d%1d",i1,j1);
6145: fprintf(ficlog,"%1d%1d",i1,j1);
6146: for(k=1; k<=ncovmodel;k++){
6147: fscanf(ficpar,"%le",&delti3[i][j][k]);
6148: printf(" %le",delti3[i][j][k]);
6149: fprintf(ficparo," %le",delti3[i][j][k]);
6150: fprintf(ficlog," %le",delti3[i][j][k]);
6151: }
6152: fscanf(ficpar,"\n");
6153: numlinepar++;
6154: printf("\n");
6155: fprintf(ficparo,"\n");
6156: fprintf(ficlog,"\n");
6157: }
6158: }
6159: fflush(ficlog);
6160:
1.145 brouard 6161: /* Reads covariance matrix */
1.126 brouard 6162: delti=delti3[1][1];
6163:
6164:
6165: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6166:
6167: /* Reads comments: lines beginning with '#' */
6168: while((c=getc(ficpar))=='#' && c!= EOF){
6169: ungetc(c,ficpar);
6170: fgets(line, MAXLINE, ficpar);
6171: numlinepar++;
1.141 brouard 6172: fputs(line,stdout);
1.126 brouard 6173: fputs(line,ficparo);
6174: fputs(line,ficlog);
6175: }
6176: ungetc(c,ficpar);
6177:
6178: matcov=matrix(1,npar,1,npar);
1.131 brouard 6179: for(i=1; i <=npar; i++)
6180: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6181:
1.126 brouard 6182: for(i=1; i <=npar; i++){
1.145 brouard 6183: fscanf(ficpar,"%s",str);
1.126 brouard 6184: if(mle==1)
6185: printf("%s",str);
6186: fprintf(ficlog,"%s",str);
6187: fprintf(ficparo,"%s",str);
6188: for(j=1; j <=i; j++){
6189: fscanf(ficpar," %le",&matcov[i][j]);
6190: if(mle==1){
6191: printf(" %.5le",matcov[i][j]);
6192: }
6193: fprintf(ficlog," %.5le",matcov[i][j]);
6194: fprintf(ficparo," %.5le",matcov[i][j]);
6195: }
6196: fscanf(ficpar,"\n");
6197: numlinepar++;
6198: if(mle==1)
6199: printf("\n");
6200: fprintf(ficlog,"\n");
6201: fprintf(ficparo,"\n");
6202: }
6203: for(i=1; i <=npar; i++)
6204: for(j=i+1;j<=npar;j++)
6205: matcov[i][j]=matcov[j][i];
6206:
6207: if(mle==1)
6208: printf("\n");
6209: fprintf(ficlog,"\n");
6210:
6211: fflush(ficlog);
6212:
6213: /*-------- Rewriting parameter file ----------*/
6214: strcpy(rfileres,"r"); /* "Rparameterfile */
6215: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6216: strcat(rfileres,"."); /* */
6217: strcat(rfileres,optionfilext); /* Other files have txt extension */
6218: if((ficres =fopen(rfileres,"w"))==NULL) {
6219: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6220: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6221: }
6222: fprintf(ficres,"#%s\n",version);
6223: } /* End of mle != -3 */
6224:
6225:
6226: n= lastobs;
6227: num=lvector(1,n);
6228: moisnais=vector(1,n);
6229: annais=vector(1,n);
6230: moisdc=vector(1,n);
6231: andc=vector(1,n);
6232: agedc=vector(1,n);
6233: cod=ivector(1,n);
6234: weight=vector(1,n);
6235: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6236: mint=matrix(1,maxwav,1,n);
6237: anint=matrix(1,maxwav,1,n);
1.131 brouard 6238: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6239: tab=ivector(1,NCOVMAX);
1.144 brouard 6240: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6241:
1.136 brouard 6242: /* Reads data from file datafile */
6243: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6244: goto end;
6245:
6246: /* Calculation of the number of parameters from char model */
1.137 brouard 6247: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6248: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6249: k=3 V4 Tvar[k=3]= 4 (from V4)
6250: k=2 V1 Tvar[k=2]= 1 (from V1)
6251: k=1 Tvar[1]=2 (from V2)
6252: */
6253: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6254: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6255: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6256: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6257: */
6258: /* For model-covariate k tells which data-covariate to use but
6259: because this model-covariate is a construction we invent a new column
6260: ncovcol + k1
6261: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6262: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6263: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6264: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6265: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6266: */
1.145 brouard 6267: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6268: 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
1.141 brouard 6269: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6270: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6271: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6272: 4 covariates (3 plus signs)
6273: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6274: */
1.136 brouard 6275:
6276: if(decodemodel(model, lastobs) == 1)
6277: goto end;
6278:
1.137 brouard 6279: if((double)(lastobs-imx)/(double)imx > 1.10){
6280: nbwarn++;
6281: 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);
6282: 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);
6283: }
1.136 brouard 6284: /* if(mle==1){*/
1.137 brouard 6285: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6286: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6287: }
6288:
6289: /*-calculation of age at interview from date of interview and age at death -*/
6290: agev=matrix(1,maxwav,1,imx);
6291:
6292: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6293: goto end;
6294:
1.126 brouard 6295:
1.136 brouard 6296: agegomp=(int)agemin;
6297: free_vector(moisnais,1,n);
6298: free_vector(annais,1,n);
1.126 brouard 6299: /* free_matrix(mint,1,maxwav,1,n);
6300: free_matrix(anint,1,maxwav,1,n);*/
6301: free_vector(moisdc,1,n);
6302: free_vector(andc,1,n);
1.145 brouard 6303: /* */
6304:
1.126 brouard 6305: wav=ivector(1,imx);
6306: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6307: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6308: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6309:
6310: /* Concatenates waves */
6311: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6312: /* */
6313:
1.126 brouard 6314: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6315:
6316: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6317: ncodemax[1]=1;
1.145 brouard 6318: Ndum =ivector(-1,NCOVMAX);
6319: if (ncovmodel > 2)
6320: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6321:
6322: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6323: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6324: h=0;
6325:
6326:
6327: /*if (cptcovn > 0) */
1.126 brouard 6328:
1.145 brouard 6329:
1.126 brouard 6330: m=pow(2,cptcoveff);
6331:
1.131 brouard 6332: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6333: 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 */
6334: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6335: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
1.126 brouard 6336: h++;
1.141 brouard 6337: if (h>m)
1.136 brouard 6338: h=1;
1.144 brouard 6339: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6340: * h 1 2 3 4
6341: *______________________________
6342: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6343: * 2 2 1 1 1
6344: * 3 i=2 1 2 1 1
6345: * 4 2 2 1 1
6346: * 5 i=3 1 i=2 1 2 1
6347: * 6 2 1 2 1
6348: * 7 i=4 1 2 2 1
6349: * 8 2 2 2 1
6350: * 9 i=5 1 i=3 1 i=2 1 1
6351: * 10 2 1 1 1
6352: * 11 i=6 1 2 1 1
6353: * 12 2 2 1 1
6354: * 13 i=7 1 i=4 1 2 1
6355: * 14 2 1 2 1
6356: * 15 i=8 1 2 2 1
6357: * 16 2 2 2 1
6358: */
1.141 brouard 6359: codtab[h][k]=j;
1.145 brouard 6360: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6361: 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]]);
1.126 brouard 6362: }
6363: }
6364: }
6365: }
6366: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6367: codtab[1][2]=1;codtab[2][2]=2; */
6368: /* for(i=1; i <=m ;i++){
6369: for(k=1; k <=cptcovn; k++){
1.131 brouard 6370: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6371: }
6372: printf("\n");
6373: }
6374: scanf("%d",i);*/
1.145 brouard 6375:
6376: free_ivector(Ndum,-1,NCOVMAX);
6377:
6378:
1.126 brouard 6379:
6380: /*------------ gnuplot -------------*/
6381: strcpy(optionfilegnuplot,optionfilefiname);
6382: if(mle==-3)
6383: strcat(optionfilegnuplot,"-mort");
6384: strcat(optionfilegnuplot,".gp");
6385:
6386: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6387: printf("Problem with file %s",optionfilegnuplot);
6388: }
6389: else{
6390: fprintf(ficgp,"\n# %s\n", version);
6391: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6392: //fprintf(ficgp,"set missing 'NaNq'\n");
6393: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6394: }
6395: /* fclose(ficgp);*/
6396: /*--------- index.htm --------*/
6397:
6398: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6399: if(mle==-3)
6400: strcat(optionfilehtm,"-mort");
6401: strcat(optionfilehtm,".htm");
6402: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6403: printf("Problem with %s \n",optionfilehtm);
6404: exit(0);
1.126 brouard 6405: }
6406:
6407: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6408: strcat(optionfilehtmcov,"-cov.htm");
6409: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6410: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6411: }
6412: else{
6413: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6414: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6415: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6416: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6417: }
6418:
6419: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6420: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6421: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6422: \n\
6423: <hr size=\"2\" color=\"#EC5E5E\">\
6424: <ul><li><h4>Parameter files</h4>\n\
6425: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6426: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6427: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6428: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6429: - Date and time at start: %s</ul>\n",\
6430: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6431: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6432: fileres,fileres,\
6433: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6434: fflush(fichtm);
6435:
6436: strcpy(pathr,path);
6437: strcat(pathr,optionfilefiname);
6438: chdir(optionfilefiname); /* Move to directory named optionfile */
6439:
6440: /* Calculates basic frequencies. Computes observed prevalence at single age
6441: and prints on file fileres'p'. */
6442: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6443:
6444: fprintf(fichtm,"\n");
6445: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6446: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6447: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6448: imx,agemin,agemax,jmin,jmax,jmean);
6449: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6450: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6451: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6452: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6453: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6454:
6455:
6456: /* For Powell, parameters are in a vector p[] starting at p[1]
6457: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6458: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6459:
6460: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6461:
6462: if (mle==-3){
1.136 brouard 6463: ximort=matrix(1,NDIM,1,NDIM);
6464: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6465: cens=ivector(1,n);
6466: ageexmed=vector(1,n);
6467: agecens=vector(1,n);
6468: dcwave=ivector(1,n);
6469:
6470: for (i=1; i<=imx; i++){
6471: dcwave[i]=-1;
6472: for (m=firstpass; m<=lastpass; m++)
6473: if (s[m][i]>nlstate) {
6474: dcwave[i]=m;
6475: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6476: break;
6477: }
6478: }
6479:
6480: for (i=1; i<=imx; i++) {
6481: if (wav[i]>0){
6482: ageexmed[i]=agev[mw[1][i]][i];
6483: j=wav[i];
6484: agecens[i]=1.;
6485:
6486: if (ageexmed[i]> 1 && wav[i] > 0){
6487: agecens[i]=agev[mw[j][i]][i];
6488: cens[i]= 1;
6489: }else if (ageexmed[i]< 1)
6490: cens[i]= -1;
6491: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6492: cens[i]=0 ;
6493: }
6494: else cens[i]=-1;
6495: }
6496:
6497: for (i=1;i<=NDIM;i++) {
6498: for (j=1;j<=NDIM;j++)
6499: ximort[i][j]=(i == j ? 1.0 : 0.0);
6500: }
6501:
1.145 brouard 6502: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6503: /*printf("%lf %lf", p[1], p[2]);*/
6504:
6505:
1.136 brouard 6506: #ifdef GSL
6507: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6508: #else
1.126 brouard 6509: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6510: #endif
1.126 brouard 6511: strcpy(filerespow,"pow-mort");
6512: strcat(filerespow,fileres);
6513: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6514: printf("Problem with resultfile: %s\n", filerespow);
6515: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6516: }
1.136 brouard 6517: #ifdef GSL
6518: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6519: #else
1.126 brouard 6520: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6521: #endif
1.126 brouard 6522: /* for (i=1;i<=nlstate;i++)
6523: for(j=1;j<=nlstate+ndeath;j++)
6524: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6525: */
6526: fprintf(ficrespow,"\n");
1.136 brouard 6527: #ifdef GSL
6528: /* gsl starts here */
6529: T = gsl_multimin_fminimizer_nmsimplex;
6530: gsl_multimin_fminimizer *sfm = NULL;
6531: gsl_vector *ss, *x;
6532: gsl_multimin_function minex_func;
6533:
6534: /* Initial vertex size vector */
6535: ss = gsl_vector_alloc (NDIM);
6536:
6537: if (ss == NULL){
6538: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6539: }
6540: /* Set all step sizes to 1 */
6541: gsl_vector_set_all (ss, 0.001);
6542:
6543: /* Starting point */
1.126 brouard 6544:
1.136 brouard 6545: x = gsl_vector_alloc (NDIM);
6546:
6547: if (x == NULL){
6548: gsl_vector_free(ss);
6549: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6550: }
6551:
6552: /* Initialize method and iterate */
6553: /* p[1]=0.0268; p[NDIM]=0.083; */
6554: /* gsl_vector_set(x, 0, 0.0268); */
6555: /* gsl_vector_set(x, 1, 0.083); */
6556: gsl_vector_set(x, 0, p[1]);
6557: gsl_vector_set(x, 1, p[2]);
6558:
6559: minex_func.f = &gompertz_f;
6560: minex_func.n = NDIM;
6561: minex_func.params = (void *)&p; /* ??? */
6562:
6563: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6564: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6565:
6566: printf("Iterations beginning .....\n\n");
6567: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6568:
6569: iteri=0;
6570: while (rval == GSL_CONTINUE){
6571: iteri++;
6572: status = gsl_multimin_fminimizer_iterate(sfm);
6573:
6574: if (status) printf("error: %s\n", gsl_strerror (status));
6575: fflush(0);
6576:
6577: if (status)
6578: break;
6579:
6580: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6581: ssval = gsl_multimin_fminimizer_size (sfm);
6582:
6583: if (rval == GSL_SUCCESS)
6584: printf ("converged to a local maximum at\n");
6585:
6586: printf("%5d ", iteri);
6587: for (it = 0; it < NDIM; it++){
6588: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6589: }
6590: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6591: }
6592:
6593: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6594:
6595: gsl_vector_free(x); /* initial values */
6596: gsl_vector_free(ss); /* inital step size */
6597: for (it=0; it<NDIM; it++){
6598: p[it+1]=gsl_vector_get(sfm->x,it);
6599: fprintf(ficrespow," %.12lf", p[it]);
6600: }
6601: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6602: #endif
6603: #ifdef POWELL
6604: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6605: #endif
1.126 brouard 6606: fclose(ficrespow);
6607:
6608: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6609:
6610: for(i=1; i <=NDIM; i++)
6611: for(j=i+1;j<=NDIM;j++)
6612: matcov[i][j]=matcov[j][i];
6613:
6614: printf("\nCovariance matrix\n ");
6615: for(i=1; i <=NDIM; i++) {
6616: for(j=1;j<=NDIM;j++){
6617: printf("%f ",matcov[i][j]);
6618: }
6619: printf("\n ");
6620: }
6621:
6622: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6623: for (i=1;i<=NDIM;i++)
6624: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6625:
6626: lsurv=vector(1,AGESUP);
6627: lpop=vector(1,AGESUP);
6628: tpop=vector(1,AGESUP);
6629: lsurv[agegomp]=100000;
6630:
6631: for (k=agegomp;k<=AGESUP;k++) {
6632: agemortsup=k;
6633: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6634: }
6635:
6636: for (k=agegomp;k<agemortsup;k++)
6637: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6638:
6639: for (k=agegomp;k<agemortsup;k++){
6640: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6641: sumlpop=sumlpop+lpop[k];
6642: }
6643:
6644: tpop[agegomp]=sumlpop;
6645: for (k=agegomp;k<(agemortsup-3);k++){
6646: /* tpop[k+1]=2;*/
6647: tpop[k+1]=tpop[k]-lpop[k];
6648: }
6649:
6650:
6651: printf("\nAge lx qx dx Lx Tx e(x)\n");
6652: for (k=agegomp;k<(agemortsup-2);k++)
6653: 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]);
6654:
6655:
6656: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6657: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6658:
6659: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6660: stepm, weightopt,\
6661: model,imx,p,matcov,agemortsup);
6662:
6663: free_vector(lsurv,1,AGESUP);
6664: free_vector(lpop,1,AGESUP);
6665: free_vector(tpop,1,AGESUP);
1.136 brouard 6666: #ifdef GSL
6667: free_ivector(cens,1,n);
6668: free_vector(agecens,1,n);
6669: free_ivector(dcwave,1,n);
6670: free_matrix(ximort,1,NDIM,1,NDIM);
6671: #endif
1.126 brouard 6672: } /* Endof if mle==-3 */
6673:
6674: else{ /* For mle >=1 */
1.132 brouard 6675: globpr=0;/* debug */
6676: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6677: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6678: for (k=1; k<=npar;k++)
6679: printf(" %d %8.5f",k,p[k]);
6680: printf("\n");
6681: globpr=1; /* to print the contributions */
6682: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6683: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6684: for (k=1; k<=npar;k++)
6685: printf(" %d %8.5f",k,p[k]);
6686: printf("\n");
6687: if(mle>=1){ /* Could be 1 or 2 */
6688: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6689: }
6690:
6691: /*--------- results files --------------*/
6692: 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);
6693:
6694:
6695: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6696: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6697: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6698: for(i=1,jk=1; i <=nlstate; i++){
6699: for(k=1; k <=(nlstate+ndeath); k++){
6700: if (k != i) {
6701: printf("%d%d ",i,k);
6702: fprintf(ficlog,"%d%d ",i,k);
6703: fprintf(ficres,"%1d%1d ",i,k);
6704: for(j=1; j <=ncovmodel; j++){
6705: printf("%lf ",p[jk]);
6706: fprintf(ficlog,"%lf ",p[jk]);
6707: fprintf(ficres,"%lf ",p[jk]);
6708: jk++;
6709: }
6710: printf("\n");
6711: fprintf(ficlog,"\n");
6712: fprintf(ficres,"\n");
6713: }
6714: }
6715: }
6716: if(mle!=0){
6717: /* Computing hessian and covariance matrix */
6718: ftolhess=ftol; /* Usually correct */
6719: hesscov(matcov, p, npar, delti, ftolhess, func);
6720: }
6721: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6722: printf("# Scales (for hessian or gradient estimation)\n");
6723: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6724: for(i=1,jk=1; i <=nlstate; i++){
6725: for(j=1; j <=nlstate+ndeath; j++){
6726: if (j!=i) {
6727: fprintf(ficres,"%1d%1d",i,j);
6728: printf("%1d%1d",i,j);
6729: fprintf(ficlog,"%1d%1d",i,j);
6730: for(k=1; k<=ncovmodel;k++){
6731: printf(" %.5e",delti[jk]);
6732: fprintf(ficlog," %.5e",delti[jk]);
6733: fprintf(ficres," %.5e",delti[jk]);
6734: jk++;
6735: }
6736: printf("\n");
6737: fprintf(ficlog,"\n");
6738: fprintf(ficres,"\n");
6739: }
6740: }
6741: }
6742:
6743: 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");
6744: if(mle>=1)
6745: 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");
6746: 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");
6747: /* # 121 Var(a12)\n\ */
6748: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6749: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6750: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6751: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6752: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6753: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6754: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6755:
6756:
6757: /* Just to have a covariance matrix which will be more understandable
6758: even is we still don't want to manage dictionary of variables
6759: */
6760: for(itimes=1;itimes<=2;itimes++){
6761: jj=0;
6762: for(i=1; i <=nlstate; i++){
6763: for(j=1; j <=nlstate+ndeath; j++){
6764: if(j==i) continue;
6765: for(k=1; k<=ncovmodel;k++){
6766: jj++;
6767: ca[0]= k+'a'-1;ca[1]='\0';
6768: if(itimes==1){
6769: if(mle>=1)
6770: printf("#%1d%1d%d",i,j,k);
6771: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6772: fprintf(ficres,"#%1d%1d%d",i,j,k);
6773: }else{
6774: if(mle>=1)
6775: printf("%1d%1d%d",i,j,k);
6776: fprintf(ficlog,"%1d%1d%d",i,j,k);
6777: fprintf(ficres,"%1d%1d%d",i,j,k);
6778: }
6779: ll=0;
6780: for(li=1;li <=nlstate; li++){
6781: for(lj=1;lj <=nlstate+ndeath; lj++){
6782: if(lj==li) continue;
6783: for(lk=1;lk<=ncovmodel;lk++){
6784: ll++;
6785: if(ll<=jj){
6786: cb[0]= lk +'a'-1;cb[1]='\0';
6787: if(ll<jj){
6788: if(itimes==1){
6789: if(mle>=1)
6790: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6791: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6792: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6793: }else{
6794: if(mle>=1)
6795: printf(" %.5e",matcov[jj][ll]);
6796: fprintf(ficlog," %.5e",matcov[jj][ll]);
6797: fprintf(ficres," %.5e",matcov[jj][ll]);
6798: }
6799: }else{
6800: if(itimes==1){
6801: if(mle>=1)
6802: printf(" Var(%s%1d%1d)",ca,i,j);
6803: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6804: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6805: }else{
6806: if(mle>=1)
6807: printf(" %.5e",matcov[jj][ll]);
6808: fprintf(ficlog," %.5e",matcov[jj][ll]);
6809: fprintf(ficres," %.5e",matcov[jj][ll]);
6810: }
6811: }
6812: }
6813: } /* end lk */
6814: } /* end lj */
6815: } /* end li */
6816: if(mle>=1)
6817: printf("\n");
6818: fprintf(ficlog,"\n");
6819: fprintf(ficres,"\n");
6820: numlinepar++;
6821: } /* end k*/
6822: } /*end j */
6823: } /* end i */
6824: } /* end itimes */
6825:
6826: fflush(ficlog);
6827: fflush(ficres);
6828:
6829: while((c=getc(ficpar))=='#' && c!= EOF){
6830: ungetc(c,ficpar);
6831: fgets(line, MAXLINE, ficpar);
1.141 brouard 6832: fputs(line,stdout);
1.126 brouard 6833: fputs(line,ficparo);
6834: }
6835: ungetc(c,ficpar);
6836:
6837: estepm=0;
6838: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6839: if (estepm==0 || estepm < stepm) estepm=stepm;
6840: if (fage <= 2) {
6841: bage = ageminpar;
6842: fage = agemaxpar;
6843: }
6844:
6845: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6846: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6847: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6848:
6849: while((c=getc(ficpar))=='#' && c!= EOF){
6850: ungetc(c,ficpar);
6851: fgets(line, MAXLINE, ficpar);
1.141 brouard 6852: fputs(line,stdout);
1.126 brouard 6853: fputs(line,ficparo);
6854: }
6855: ungetc(c,ficpar);
6856:
6857: 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);
6858: 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);
6859: 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);
6860: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6861: 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);
6862:
6863: while((c=getc(ficpar))=='#' && c!= EOF){
6864: ungetc(c,ficpar);
6865: fgets(line, MAXLINE, ficpar);
1.141 brouard 6866: fputs(line,stdout);
1.126 brouard 6867: fputs(line,ficparo);
6868: }
6869: ungetc(c,ficpar);
6870:
6871:
6872: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6873: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6874:
6875: fscanf(ficpar,"pop_based=%d\n",&popbased);
6876: fprintf(ficparo,"pop_based=%d\n",popbased);
6877: fprintf(ficres,"pop_based=%d\n",popbased);
6878:
6879: while((c=getc(ficpar))=='#' && c!= EOF){
6880: ungetc(c,ficpar);
6881: fgets(line, MAXLINE, ficpar);
1.141 brouard 6882: fputs(line,stdout);
1.126 brouard 6883: fputs(line,ficparo);
6884: }
6885: ungetc(c,ficpar);
6886:
6887: 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);
6888: 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);
6889: 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);
6890: 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);
6891: 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);
6892: /* day and month of proj2 are not used but only year anproj2.*/
6893:
6894:
6895:
1.145 brouard 6896: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6897: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6898:
6899: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6900: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6901:
6902: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6903: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6904: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6905:
6906: /*------------ free_vector -------------*/
6907: /* chdir(path); */
6908:
6909: free_ivector(wav,1,imx);
6910: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6911: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6912: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6913: free_lvector(num,1,n);
6914: free_vector(agedc,1,n);
6915: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6916: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6917: fclose(ficparo);
6918: fclose(ficres);
6919:
6920:
6921: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 6922: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
6923: prlim=matrix(1,nlstate,1,nlstate);
6924: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 6925: fclose(ficrespl);
6926:
1.145 brouard 6927: #ifdef FREEEXIT2
6928: #include "freeexit2.h"
6929: #endif
6930:
1.126 brouard 6931: /*------------- h Pij x at various ages ------------*/
1.180 brouard 6932: /*#include "hpijx.h"*/
6933: hPijx(p, bage, fage);
1.145 brouard 6934: fclose(ficrespij);
1.126 brouard 6935:
1.145 brouard 6936: /*-------------- Variance of one-step probabilities---*/
6937: k=1;
1.126 brouard 6938: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6939:
6940:
6941: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6942: for(i=1;i<=AGESUP;i++)
6943: for(j=1;j<=NCOVMAX;j++)
6944: for(k=1;k<=NCOVMAX;k++)
6945: probs[i][j][k]=0.;
6946:
6947: /*---------- Forecasting ------------------*/
6948: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6949: if(prevfcast==1){
6950: /* if(stepm ==1){*/
6951: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6952: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6953: /* } */
6954: /* else{ */
6955: /* erreur=108; */
6956: /* 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); */
6957: /* 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); */
6958: /* } */
6959: }
6960:
6961:
1.127 brouard 6962: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6963:
6964: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6965: /* 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",\
6966: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6967: */
1.126 brouard 6968:
1.127 brouard 6969: if (mobilav!=0) {
6970: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6971: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6972: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6973: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6974: }
1.126 brouard 6975: }
6976:
6977:
1.127 brouard 6978: /*---------- Health expectancies, no variances ------------*/
6979:
1.126 brouard 6980: strcpy(filerese,"e");
6981: strcat(filerese,fileres);
6982: if((ficreseij=fopen(filerese,"w"))==NULL) {
6983: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6984: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6985: }
6986: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6987: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6988: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6989: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6990:
6991: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6992: fprintf(ficreseij,"\n#****** ");
6993: for(j=1;j<=cptcoveff;j++) {
6994: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6995: }
6996: fprintf(ficreseij,"******\n");
6997:
6998: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6999: oldm=oldms;savm=savms;
7000: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7001:
7002: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7003: /*}*/
1.127 brouard 7004: }
7005: fclose(ficreseij);
7006:
7007:
7008: /*---------- Health expectancies and variances ------------*/
7009:
7010:
7011: strcpy(filerest,"t");
7012: strcat(filerest,fileres);
7013: if((ficrest=fopen(filerest,"w"))==NULL) {
7014: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7015: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7016: }
7017: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7018: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7019:
1.126 brouard 7020:
7021: strcpy(fileresstde,"stde");
7022: strcat(fileresstde,fileres);
7023: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7024: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7025: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7026: }
7027: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7028: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7029:
7030: strcpy(filerescve,"cve");
7031: strcat(filerescve,fileres);
7032: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7033: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7034: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7035: }
7036: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7037: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7038:
7039: strcpy(fileresv,"v");
7040: strcat(fileresv,fileres);
7041: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7042: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7043: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7044: }
7045: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7046: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7047:
1.145 brouard 7048: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7049: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7050:
7051: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7052: fprintf(ficrest,"\n#****** ");
1.126 brouard 7053: for(j=1;j<=cptcoveff;j++)
7054: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7055: fprintf(ficrest,"******\n");
7056:
7057: fprintf(ficresstdeij,"\n#****** ");
7058: fprintf(ficrescveij,"\n#****** ");
7059: for(j=1;j<=cptcoveff;j++) {
7060: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7061: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7062: }
7063: fprintf(ficresstdeij,"******\n");
7064: fprintf(ficrescveij,"******\n");
7065:
7066: fprintf(ficresvij,"\n#****** ");
7067: for(j=1;j<=cptcoveff;j++)
7068: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7069: fprintf(ficresvij,"******\n");
7070:
7071: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7072: oldm=oldms;savm=savms;
1.127 brouard 7073: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7074: /*
7075: */
7076: /* goto endfree; */
1.126 brouard 7077:
7078: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7079: pstamp(ficrest);
1.145 brouard 7080:
7081:
1.128 brouard 7082: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7083: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7084: cptcod= 0; /* To be deleted */
7085: 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 */
1.145 brouard 7086: 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 ");
1.128 brouard 7087: if(vpopbased==1)
7088: 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);
7089: else
7090: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7091: fprintf(ficrest,"# Age e.. (std) ");
7092: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7093: fprintf(ficrest,"\n");
1.126 brouard 7094:
1.128 brouard 7095: epj=vector(1,nlstate+1);
7096: for(age=bage; age <=fage ;age++){
7097: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7098: if (vpopbased==1) {
7099: if(mobilav ==0){
7100: for(i=1; i<=nlstate;i++)
7101: prlim[i][i]=probs[(int)age][i][k];
7102: }else{ /* mobilav */
7103: for(i=1; i<=nlstate;i++)
7104: prlim[i][i]=mobaverage[(int)age][i][k];
7105: }
1.126 brouard 7106: }
7107:
1.128 brouard 7108: fprintf(ficrest," %4.0f",age);
7109: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7110: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7111: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7112: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7113: }
7114: epj[nlstate+1] +=epj[j];
1.126 brouard 7115: }
7116:
1.128 brouard 7117: for(i=1, vepp=0.;i <=nlstate;i++)
7118: for(j=1;j <=nlstate;j++)
7119: vepp += vareij[i][j][(int)age];
7120: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7121: for(j=1;j <=nlstate;j++){
7122: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7123: }
7124: fprintf(ficrest,"\n");
1.126 brouard 7125: }
7126: }
7127: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7128: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7129: free_vector(epj,1,nlstate+1);
1.145 brouard 7130: /*}*/
1.126 brouard 7131: }
7132: free_vector(weight,1,n);
1.145 brouard 7133: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7134: free_imatrix(s,1,maxwav+1,1,n);
7135: free_matrix(anint,1,maxwav,1,n);
7136: free_matrix(mint,1,maxwav,1,n);
7137: free_ivector(cod,1,n);
7138: free_ivector(tab,1,NCOVMAX);
7139: fclose(ficresstdeij);
7140: fclose(ficrescveij);
7141: fclose(ficresvij);
7142: fclose(ficrest);
7143: fclose(ficpar);
7144:
7145: /*------- Variance of period (stable) prevalence------*/
7146:
7147: strcpy(fileresvpl,"vpl");
7148: strcat(fileresvpl,fileres);
7149: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7150: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7151: exit(0);
7152: }
7153: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7154:
1.145 brouard 7155: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7156: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7157:
7158: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7159: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7160: for(j=1;j<=cptcoveff;j++)
7161: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7162: fprintf(ficresvpl,"******\n");
7163:
7164: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7165: oldm=oldms;savm=savms;
7166: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7167: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7168: /*}*/
1.126 brouard 7169: }
7170:
7171: fclose(ficresvpl);
7172:
7173: /*---------- End : free ----------------*/
7174: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7175: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7176: } /* mle==-3 arrives here for freeing */
1.164 brouard 7177: /* endfree:*/
1.141 brouard 7178: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7179: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7180: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7181: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7182: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7183: free_matrix(covar,0,NCOVMAX,1,n);
7184: free_matrix(matcov,1,npar,1,npar);
7185: /*free_vector(delti,1,npar);*/
7186: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7187: free_matrix(agev,1,maxwav,1,imx);
7188: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7189:
1.145 brouard 7190: free_ivector(ncodemax,1,NCOVMAX);
7191: free_ivector(Tvar,1,NCOVMAX);
7192: free_ivector(Tprod,1,NCOVMAX);
7193: free_ivector(Tvaraff,1,NCOVMAX);
7194: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7195:
7196: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7197: free_imatrix(codtab,1,100,1,10);
7198: fflush(fichtm);
7199: fflush(ficgp);
7200:
7201:
7202: if((nberr >0) || (nbwarn>0)){
7203: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7204: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7205: }else{
7206: printf("End of Imach\n");
7207: fprintf(ficlog,"End of Imach\n");
7208: }
7209: printf("See log file on %s\n",filelog);
7210: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7211: /*(void) gettimeofday(&end_time,&tzp);*/
7212: rend_time = time(NULL);
7213: end_time = *localtime(&rend_time);
7214: /* tml = *localtime(&end_time.tm_sec); */
7215: strcpy(strtend,asctime(&end_time));
1.126 brouard 7216: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7217: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7218: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7219:
1.157 brouard 7220: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7221: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7222: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7223: /* printf("Total time was %d uSec.\n", total_usecs);*/
7224: /* if(fileappend(fichtm,optionfilehtm)){ */
7225: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7226: fclose(fichtm);
7227: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7228: fclose(fichtmcov);
7229: fclose(ficgp);
7230: fclose(ficlog);
7231: /*------ End -----------*/
7232:
7233:
7234: printf("Before Current directory %s!\n",pathcd);
7235: if(chdir(pathcd) != 0)
7236: printf("Can't move to directory %s!\n",path);
7237: if(getcwd(pathcd,MAXLINE) > 0)
7238: printf("Current directory %s!\n",pathcd);
7239: /*strcat(plotcmd,CHARSEPARATOR);*/
7240: sprintf(plotcmd,"gnuplot");
1.157 brouard 7241: #ifdef _WIN32
1.126 brouard 7242: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7243: #endif
7244: if(!stat(plotcmd,&info)){
1.158 brouard 7245: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7246: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7247: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7248: }else
7249: strcpy(pplotcmd,plotcmd);
1.157 brouard 7250: #ifdef __unix
1.126 brouard 7251: strcpy(plotcmd,GNUPLOTPROGRAM);
7252: if(!stat(plotcmd,&info)){
1.158 brouard 7253: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7254: }else
7255: strcpy(pplotcmd,plotcmd);
7256: #endif
7257: }else
7258: strcpy(pplotcmd,plotcmd);
7259:
7260: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7261: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7262:
7263: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7264: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7265: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7266: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7267: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7268: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7269: }
1.158 brouard 7270: printf(" Successful, please wait...");
1.126 brouard 7271: while (z[0] != 'q') {
7272: /* chdir(path); */
1.154 brouard 7273: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7274: scanf("%s",z);
7275: /* if (z[0] == 'c') system("./imach"); */
7276: if (z[0] == 'e') {
1.158 brouard 7277: #ifdef __APPLE__
1.152 brouard 7278: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7279: #elif __linux
7280: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7281: #else
1.152 brouard 7282: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7283: #endif
7284: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7285: system(pplotcmd);
1.126 brouard 7286: }
7287: else if (z[0] == 'g') system(plotcmd);
7288: else if (z[0] == 'q') exit(0);
7289: }
7290: end:
7291: while (z[0] != 'q') {
7292: printf("\nType q for exiting: ");
7293: scanf("%s",z);
7294: }
7295: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>