Annotation of imach/src/imach.c, revision 1.177
1.177 ! brouard 1: /* $Id: imach.c,v 1.176 2015/01/03 16:45:04 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.177 ! brouard 4: Revision 1.176 2015/01/03 16:45:04 brouard
! 5: *** empty log message ***
! 6:
1.176 brouard 7: Revision 1.175 2015/01/03 16:33:42 brouard
8: *** empty log message ***
9:
1.175 brouard 10: Revision 1.174 2015/01/03 16:15:49 brouard
11: Summary: Still in cross-compilation
12:
1.174 brouard 13: Revision 1.173 2015/01/03 12:06:26 brouard
14: Summary: trying to detect cross-compilation
15:
1.173 brouard 16: Revision 1.172 2014/12/27 12:07:47 brouard
17: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
18:
1.172 brouard 19: Revision 1.171 2014/12/23 13:26:59 brouard
20: Summary: Back from Visual C
21:
22: Still problem with utsname.h on Windows
23:
1.171 brouard 24: Revision 1.170 2014/12/23 11:17:12 brouard
25: Summary: Cleaning some \%% back to %%
26:
27: The escape was mandatory for a specific compiler (which one?), but too many warnings.
28:
1.170 brouard 29: Revision 1.169 2014/12/22 23:08:31 brouard
30: Summary: 0.98p
31:
32: Outputs some informations on compiler used, OS etc. Testing on different platforms.
33:
1.169 brouard 34: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 35: Summary: update
1.169 brouard 36:
1.168 brouard 37: Revision 1.167 2014/12/22 13:50:56 brouard
38: Summary: Testing uname and compiler version and if compiled 32 or 64
39:
40: Testing on Linux 64
41:
1.167 brouard 42: Revision 1.166 2014/12/22 11:40:47 brouard
43: *** empty log message ***
44:
1.166 brouard 45: Revision 1.165 2014/12/16 11:20:36 brouard
46: Summary: After compiling on Visual C
47:
48: * imach.c (Module): Merging 1.61 to 1.162
49:
1.165 brouard 50: Revision 1.164 2014/12/16 10:52:11 brouard
51: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
52:
53: * imach.c (Module): Merging 1.61 to 1.162
54:
1.164 brouard 55: Revision 1.163 2014/12/16 10:30:11 brouard
56: * imach.c (Module): Merging 1.61 to 1.162
57:
1.163 brouard 58: Revision 1.162 2014/09/25 11:43:39 brouard
59: Summary: temporary backup 0.99!
60:
1.162 brouard 61: Revision 1.1 2014/09/16 11:06:58 brouard
62: Summary: With some code (wrong) for nlopt
63:
64: Author:
65:
66: Revision 1.161 2014/09/15 20:41:41 brouard
67: Summary: Problem with macro SQR on Intel compiler
68:
1.161 brouard 69: Revision 1.160 2014/09/02 09:24:05 brouard
70: *** empty log message ***
71:
1.160 brouard 72: Revision 1.159 2014/09/01 10:34:10 brouard
73: Summary: WIN32
74: Author: Brouard
75:
1.159 brouard 76: Revision 1.158 2014/08/27 17:11:51 brouard
77: *** empty log message ***
78:
1.158 brouard 79: Revision 1.157 2014/08/27 16:26:55 brouard
80: Summary: Preparing windows Visual studio version
81: Author: Brouard
82:
83: In order to compile on Visual studio, time.h is now correct and time_t
84: and tm struct should be used. difftime should be used but sometimes I
85: just make the differences in raw time format (time(&now).
86: Trying to suppress #ifdef LINUX
87: Add xdg-open for __linux in order to open default browser.
88:
1.157 brouard 89: Revision 1.156 2014/08/25 20:10:10 brouard
90: *** empty log message ***
91:
1.156 brouard 92: Revision 1.155 2014/08/25 18:32:34 brouard
93: Summary: New compile, minor changes
94: Author: Brouard
95:
1.155 brouard 96: Revision 1.154 2014/06/20 17:32:08 brouard
97: Summary: Outputs now all graphs of convergence to period prevalence
98:
1.154 brouard 99: Revision 1.153 2014/06/20 16:45:46 brouard
100: Summary: If 3 live state, convergence to period prevalence on same graph
101: Author: Brouard
102:
1.153 brouard 103: Revision 1.152 2014/06/18 17:54:09 brouard
104: Summary: open browser, use gnuplot on same dir than imach if not found in the path
105:
1.152 brouard 106: Revision 1.151 2014/06/18 16:43:30 brouard
107: *** empty log message ***
108:
1.151 brouard 109: Revision 1.150 2014/06/18 16:42:35 brouard
110: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
111: Author: brouard
112:
1.150 brouard 113: Revision 1.149 2014/06/18 15:51:14 brouard
114: Summary: Some fixes in parameter files errors
115: Author: Nicolas Brouard
116:
1.149 brouard 117: Revision 1.148 2014/06/17 17:38:48 brouard
118: Summary: Nothing new
119: Author: Brouard
120:
121: Just a new packaging for OS/X version 0.98nS
122:
1.148 brouard 123: Revision 1.147 2014/06/16 10:33:11 brouard
124: *** empty log message ***
125:
1.147 brouard 126: Revision 1.146 2014/06/16 10:20:28 brouard
127: Summary: Merge
128: Author: Brouard
129:
130: Merge, before building revised version.
131:
1.146 brouard 132: Revision 1.145 2014/06/10 21:23:15 brouard
133: Summary: Debugging with valgrind
134: Author: Nicolas Brouard
135:
136: Lot of changes in order to output the results with some covariates
137: After the Edimburgh REVES conference 2014, it seems mandatory to
138: improve the code.
139: No more memory valgrind error but a lot has to be done in order to
140: continue the work of splitting the code into subroutines.
141: Also, decodemodel has been improved. Tricode is still not
142: optimal. nbcode should be improved. Documentation has been added in
143: the source code.
144:
1.144 brouard 145: Revision 1.143 2014/01/26 09:45:38 brouard
146: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
147:
148: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
149: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
150:
1.143 brouard 151: Revision 1.142 2014/01/26 03:57:36 brouard
152: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
153:
154: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
155:
1.142 brouard 156: Revision 1.141 2014/01/26 02:42:01 brouard
157: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
158:
1.141 brouard 159: Revision 1.140 2011/09/02 10:37:54 brouard
160: Summary: times.h is ok with mingw32 now.
161:
1.140 brouard 162: Revision 1.139 2010/06/14 07:50:17 brouard
163: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
164: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
165:
1.139 brouard 166: Revision 1.138 2010/04/30 18:19:40 brouard
167: *** empty log message ***
168:
1.138 brouard 169: Revision 1.137 2010/04/29 18:11:38 brouard
170: (Module): Checking covariates for more complex models
171: than V1+V2. A lot of change to be done. Unstable.
172:
1.137 brouard 173: Revision 1.136 2010/04/26 20:30:53 brouard
174: (Module): merging some libgsl code. Fixing computation
175: of likelione (using inter/intrapolation if mle = 0) in order to
176: get same likelihood as if mle=1.
177: Some cleaning of code and comments added.
178:
1.136 brouard 179: Revision 1.135 2009/10/29 15:33:14 brouard
180: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
181:
1.135 brouard 182: Revision 1.134 2009/10/29 13:18:53 brouard
183: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
184:
1.134 brouard 185: Revision 1.133 2009/07/06 10:21:25 brouard
186: just nforces
187:
1.133 brouard 188: Revision 1.132 2009/07/06 08:22:05 brouard
189: Many tings
190:
1.132 brouard 191: Revision 1.131 2009/06/20 16:22:47 brouard
192: Some dimensions resccaled
193:
1.131 brouard 194: Revision 1.130 2009/05/26 06:44:34 brouard
195: (Module): Max Covariate is now set to 20 instead of 8. A
196: lot of cleaning with variables initialized to 0. Trying to make
197: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
198:
1.130 brouard 199: Revision 1.129 2007/08/31 13:49:27 lievre
200: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
201:
1.129 lievre 202: Revision 1.128 2006/06/30 13:02:05 brouard
203: (Module): Clarifications on computing e.j
204:
1.128 brouard 205: Revision 1.127 2006/04/28 18:11:50 brouard
206: (Module): Yes the sum of survivors was wrong since
207: imach-114 because nhstepm was no more computed in the age
208: loop. Now we define nhstepma in the age loop.
209: (Module): In order to speed up (in case of numerous covariates) we
210: compute health expectancies (without variances) in a first step
211: and then all the health expectancies with variances or standard
212: deviation (needs data from the Hessian matrices) which slows the
213: computation.
214: In the future we should be able to stop the program is only health
215: expectancies and graph are needed without standard deviations.
216:
1.127 brouard 217: Revision 1.126 2006/04/28 17:23:28 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: Version 0.98h
222:
1.126 brouard 223: Revision 1.125 2006/04/04 15:20:31 lievre
224: Errors in calculation of health expectancies. Age was not initialized.
225: Forecasting file added.
226:
227: Revision 1.124 2006/03/22 17:13:53 lievre
228: Parameters are printed with %lf instead of %f (more numbers after the comma).
229: The log-likelihood is printed in the log file
230:
231: Revision 1.123 2006/03/20 10:52:43 brouard
232: * imach.c (Module): <title> changed, corresponds to .htm file
233: name. <head> headers where missing.
234:
235: * imach.c (Module): Weights can have a decimal point as for
236: English (a comma might work with a correct LC_NUMERIC environment,
237: otherwise the weight is truncated).
238: Modification of warning when the covariates values are not 0 or
239: 1.
240: Version 0.98g
241:
242: Revision 1.122 2006/03/20 09:45:41 brouard
243: (Module): Weights can have a decimal point as for
244: English (a comma might work with a correct LC_NUMERIC environment,
245: otherwise the weight is truncated).
246: Modification of warning when the covariates values are not 0 or
247: 1.
248: Version 0.98g
249:
250: Revision 1.121 2006/03/16 17:45:01 lievre
251: * imach.c (Module): Comments concerning covariates added
252:
253: * imach.c (Module): refinements in the computation of lli if
254: status=-2 in order to have more reliable computation if stepm is
255: not 1 month. Version 0.98f
256:
257: Revision 1.120 2006/03/16 15:10:38 lievre
258: (Module): refinements in the computation of lli if
259: status=-2 in order to have more reliable computation if stepm is
260: not 1 month. Version 0.98f
261:
262: Revision 1.119 2006/03/15 17:42:26 brouard
263: (Module): Bug if status = -2, the loglikelihood was
264: computed as likelihood omitting the logarithm. Version O.98e
265:
266: Revision 1.118 2006/03/14 18:20:07 brouard
267: (Module): varevsij Comments added explaining the second
268: table of variances if popbased=1 .
269: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
270: (Module): Function pstamp added
271: (Module): Version 0.98d
272:
273: Revision 1.117 2006/03/14 17:16:22 brouard
274: (Module): varevsij Comments added explaining the second
275: table of variances if popbased=1 .
276: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
277: (Module): Function pstamp added
278: (Module): Version 0.98d
279:
280: Revision 1.116 2006/03/06 10:29:27 brouard
281: (Module): Variance-covariance wrong links and
282: varian-covariance of ej. is needed (Saito).
283:
284: Revision 1.115 2006/02/27 12:17:45 brouard
285: (Module): One freematrix added in mlikeli! 0.98c
286:
287: Revision 1.114 2006/02/26 12:57:58 brouard
288: (Module): Some improvements in processing parameter
289: filename with strsep.
290:
291: Revision 1.113 2006/02/24 14:20:24 brouard
292: (Module): Memory leaks checks with valgrind and:
293: datafile was not closed, some imatrix were not freed and on matrix
294: allocation too.
295:
296: Revision 1.112 2006/01/30 09:55:26 brouard
297: (Module): Back to gnuplot.exe instead of wgnuplot.exe
298:
299: Revision 1.111 2006/01/25 20:38:18 brouard
300: (Module): Lots of cleaning and bugs added (Gompertz)
301: (Module): Comments can be added in data file. Missing date values
302: can be a simple dot '.'.
303:
304: Revision 1.110 2006/01/25 00:51:50 brouard
305: (Module): Lots of cleaning and bugs added (Gompertz)
306:
307: Revision 1.109 2006/01/24 19:37:15 brouard
308: (Module): Comments (lines starting with a #) are allowed in data.
309:
310: Revision 1.108 2006/01/19 18:05:42 lievre
311: Gnuplot problem appeared...
312: To be fixed
313:
314: Revision 1.107 2006/01/19 16:20:37 brouard
315: Test existence of gnuplot in imach path
316:
317: Revision 1.106 2006/01/19 13:24:36 brouard
318: Some cleaning and links added in html output
319:
320: Revision 1.105 2006/01/05 20:23:19 lievre
321: *** empty log message ***
322:
323: Revision 1.104 2005/09/30 16:11:43 lievre
324: (Module): sump fixed, loop imx fixed, and simplifications.
325: (Module): If the status is missing at the last wave but we know
326: that the person is alive, then we can code his/her status as -2
327: (instead of missing=-1 in earlier versions) and his/her
328: contributions to the likelihood is 1 - Prob of dying from last
329: health status (= 1-p13= p11+p12 in the easiest case of somebody in
330: the healthy state at last known wave). Version is 0.98
331:
332: Revision 1.103 2005/09/30 15:54:49 lievre
333: (Module): sump fixed, loop imx fixed, and simplifications.
334:
335: Revision 1.102 2004/09/15 17:31:30 brouard
336: Add the possibility to read data file including tab characters.
337:
338: Revision 1.101 2004/09/15 10:38:38 brouard
339: Fix on curr_time
340:
341: Revision 1.100 2004/07/12 18:29:06 brouard
342: Add version for Mac OS X. Just define UNIX in Makefile
343:
344: Revision 1.99 2004/06/05 08:57:40 brouard
345: *** empty log message ***
346:
347: Revision 1.98 2004/05/16 15:05:56 brouard
348: New version 0.97 . First attempt to estimate force of mortality
349: directly from the data i.e. without the need of knowing the health
350: state at each age, but using a Gompertz model: log u =a + b*age .
351: This is the basic analysis of mortality and should be done before any
352: other analysis, in order to test if the mortality estimated from the
353: cross-longitudinal survey is different from the mortality estimated
354: from other sources like vital statistic data.
355:
356: The same imach parameter file can be used but the option for mle should be -3.
357:
1.133 brouard 358: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 359: former routines in order to include the new code within the former code.
360:
361: The output is very simple: only an estimate of the intercept and of
362: the slope with 95% confident intervals.
363:
364: Current limitations:
365: A) Even if you enter covariates, i.e. with the
366: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
367: B) There is no computation of Life Expectancy nor Life Table.
368:
369: Revision 1.97 2004/02/20 13:25:42 lievre
370: Version 0.96d. Population forecasting command line is (temporarily)
371: suppressed.
372:
373: Revision 1.96 2003/07/15 15:38:55 brouard
374: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
375: rewritten within the same printf. Workaround: many printfs.
376:
377: Revision 1.95 2003/07/08 07:54:34 brouard
378: * imach.c (Repository):
379: (Repository): Using imachwizard code to output a more meaningful covariance
380: matrix (cov(a12,c31) instead of numbers.
381:
382: Revision 1.94 2003/06/27 13:00:02 brouard
383: Just cleaning
384:
385: Revision 1.93 2003/06/25 16:33:55 brouard
386: (Module): On windows (cygwin) function asctime_r doesn't
387: exist so I changed back to asctime which exists.
388: (Module): Version 0.96b
389:
390: Revision 1.92 2003/06/25 16:30:45 brouard
391: (Module): On windows (cygwin) function asctime_r doesn't
392: exist so I changed back to asctime which exists.
393:
394: Revision 1.91 2003/06/25 15:30:29 brouard
395: * imach.c (Repository): Duplicated warning errors corrected.
396: (Repository): Elapsed time after each iteration is now output. It
397: helps to forecast when convergence will be reached. Elapsed time
398: is stamped in powell. We created a new html file for the graphs
399: concerning matrix of covariance. It has extension -cov.htm.
400:
401: Revision 1.90 2003/06/24 12:34:15 brouard
402: (Module): Some bugs corrected for windows. Also, when
403: mle=-1 a template is output in file "or"mypar.txt with the design
404: of the covariance matrix to be input.
405:
406: Revision 1.89 2003/06/24 12:30:52 brouard
407: (Module): Some bugs corrected for windows. Also, when
408: mle=-1 a template is output in file "or"mypar.txt with the design
409: of the covariance matrix to be input.
410:
411: Revision 1.88 2003/06/23 17:54:56 brouard
412: * 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.
413:
414: Revision 1.87 2003/06/18 12:26:01 brouard
415: Version 0.96
416:
417: Revision 1.86 2003/06/17 20:04:08 brouard
418: (Module): Change position of html and gnuplot routines and added
419: routine fileappend.
420:
421: Revision 1.85 2003/06/17 13:12:43 brouard
422: * imach.c (Repository): Check when date of death was earlier that
423: current date of interview. It may happen when the death was just
424: prior to the death. In this case, dh was negative and likelihood
425: was wrong (infinity). We still send an "Error" but patch by
426: assuming that the date of death was just one stepm after the
427: interview.
428: (Repository): Because some people have very long ID (first column)
429: we changed int to long in num[] and we added a new lvector for
430: memory allocation. But we also truncated to 8 characters (left
431: truncation)
432: (Repository): No more line truncation errors.
433:
434: Revision 1.84 2003/06/13 21:44:43 brouard
435: * imach.c (Repository): Replace "freqsummary" at a correct
436: place. It differs from routine "prevalence" which may be called
437: many times. Probs is memory consuming and must be used with
438: parcimony.
439: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
440:
441: Revision 1.83 2003/06/10 13:39:11 lievre
442: *** empty log message ***
443:
444: Revision 1.82 2003/06/05 15:57:20 brouard
445: Add log in imach.c and fullversion number is now printed.
446:
447: */
448: /*
449: Interpolated Markov Chain
450:
451: Short summary of the programme:
452:
453: This program computes Healthy Life Expectancies from
454: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
455: first survey ("cross") where individuals from different ages are
456: interviewed on their health status or degree of disability (in the
457: case of a health survey which is our main interest) -2- at least a
458: second wave of interviews ("longitudinal") which measure each change
459: (if any) in individual health status. Health expectancies are
460: computed from the time spent in each health state according to a
461: model. More health states you consider, more time is necessary to reach the
462: Maximum Likelihood of the parameters involved in the model. The
463: simplest model is the multinomial logistic model where pij is the
464: probability to be observed in state j at the second wave
465: conditional to be observed in state i at the first wave. Therefore
466: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
467: 'age' is age and 'sex' is a covariate. If you want to have a more
468: complex model than "constant and age", you should modify the program
469: where the markup *Covariates have to be included here again* invites
470: you to do it. More covariates you add, slower the
471: convergence.
472:
473: The advantage of this computer programme, compared to a simple
474: multinomial logistic model, is clear when the delay between waves is not
475: identical for each individual. Also, if a individual missed an
476: intermediate interview, the information is lost, but taken into
477: account using an interpolation or extrapolation.
478:
479: hPijx is the probability to be observed in state i at age x+h
480: conditional to the observed state i at age x. The delay 'h' can be
481: split into an exact number (nh*stepm) of unobserved intermediate
482: states. This elementary transition (by month, quarter,
483: semester or year) is modelled as a multinomial logistic. The hPx
484: matrix is simply the matrix product of nh*stepm elementary matrices
485: and the contribution of each individual to the likelihood is simply
486: hPijx.
487:
488: Also this programme outputs the covariance matrix of the parameters but also
489: of the life expectancies. It also computes the period (stable) prevalence.
490:
1.133 brouard 491: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
492: Institut national d'études démographiques, Paris.
1.126 brouard 493: This software have been partly granted by Euro-REVES, a concerted action
494: from the European Union.
495: It is copyrighted identically to a GNU software product, ie programme and
496: software can be distributed freely for non commercial use. Latest version
497: can be accessed at http://euroreves.ined.fr/imach .
498:
499: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
500: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
501:
502: **********************************************************************/
503: /*
504: main
505: read parameterfile
506: read datafile
507: concatwav
508: freqsummary
509: if (mle >= 1)
510: mlikeli
511: print results files
512: if mle==1
513: computes hessian
514: read end of parameter file: agemin, agemax, bage, fage, estepm
515: begin-prev-date,...
516: open gnuplot file
517: open html file
1.145 brouard 518: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
519: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
520: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
521: freexexit2 possible for memory heap.
522:
523: h Pij x | pij_nom ficrestpij
524: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
525: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
526: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
527:
528: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
529: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
530: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
531: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
532: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
533:
1.126 brouard 534: forecasting if prevfcast==1 prevforecast call prevalence()
535: health expectancies
536: Variance-covariance of DFLE
537: prevalence()
538: movingaverage()
539: varevsij()
540: if popbased==1 varevsij(,popbased)
541: total life expectancies
542: Variance of period (stable) prevalence
543: end
544: */
545:
1.165 brouard 546: #define POWELL /* Instead of NLOPT */
1.126 brouard 547:
548: #include <math.h>
549: #include <stdio.h>
550: #include <stdlib.h>
551: #include <string.h>
1.159 brouard 552:
553: #ifdef _WIN32
554: #include <io.h>
1.172 brouard 555: #include <windows.h>
556: #include <tchar.h>
1.159 brouard 557: #else
1.126 brouard 558: #include <unistd.h>
1.159 brouard 559: #endif
1.126 brouard 560:
561: #include <limits.h>
562: #include <sys/types.h>
1.171 brouard 563:
564: #if defined(__GNUC__)
565: #include <sys/utsname.h> /* Doesn't work on Windows */
566: #endif
567:
1.126 brouard 568: #include <sys/stat.h>
569: #include <errno.h>
1.159 brouard 570: /* extern int errno; */
1.126 brouard 571:
1.157 brouard 572: /* #ifdef LINUX */
573: /* #include <time.h> */
574: /* #include "timeval.h" */
575: /* #else */
576: /* #include <sys/time.h> */
577: /* #endif */
578:
1.126 brouard 579: #include <time.h>
580:
1.136 brouard 581: #ifdef GSL
582: #include <gsl/gsl_errno.h>
583: #include <gsl/gsl_multimin.h>
584: #endif
585:
1.167 brouard 586:
1.162 brouard 587: #ifdef NLOPT
588: #include <nlopt.h>
589: typedef struct {
590: double (* function)(double [] );
591: } myfunc_data ;
592: #endif
593:
1.126 brouard 594: /* #include <libintl.h> */
595: /* #define _(String) gettext (String) */
596:
1.141 brouard 597: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 598:
599: #define GNUPLOTPROGRAM "gnuplot"
600: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
601: #define FILENAMELENGTH 132
602:
603: #define GLOCK_ERROR_NOPATH -1 /* empty path */
604: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
605:
1.144 brouard 606: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
607: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 608:
609: #define NINTERVMAX 8
1.144 brouard 610: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
611: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
612: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 613: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 614: #define MAXN 20000
1.144 brouard 615: #define YEARM 12. /**< Number of months per year */
1.126 brouard 616: #define AGESUP 130
617: #define AGEBASE 40
1.164 brouard 618: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 619: #ifdef _WIN32
620: #define DIRSEPARATOR '\\'
621: #define CHARSEPARATOR "\\"
622: #define ODIRSEPARATOR '/'
623: #else
1.126 brouard 624: #define DIRSEPARATOR '/'
625: #define CHARSEPARATOR "/"
626: #define ODIRSEPARATOR '\\'
627: #endif
628:
1.177 ! brouard 629: /* $Id: imach.c,v 1.176 2015/01/03 16:45:04 brouard Exp $ */
1.126 brouard 630: /* $State: Exp $ */
631:
1.169 brouard 632: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.177 ! brouard 633: char fullversion[]="$Revision: 1.176 $ $Date: 2015/01/03 16:45:04 $";
1.126 brouard 634: char strstart[80];
635: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 636: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 637: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 638: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
639: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
640: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
641: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
642: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
643: int cptcovprodnoage=0; /**< Number of covariate products without age */
644: int cptcoveff=0; /* Total number of covariates to vary for printing results */
645: int cptcov=0; /* Working variable */
1.126 brouard 646: int npar=NPARMAX;
647: int nlstate=2; /* Number of live states */
648: int ndeath=1; /* Number of dead states */
1.130 brouard 649: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 650: int popbased=0;
651:
652: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 653: int maxwav=0; /* Maxim number of waves */
654: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
655: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
656: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 657: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 658: int mle=1, weightopt=0;
1.126 brouard 659: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
660: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
661: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
662: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 663: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 664: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 665: double **matprod2(); /* test */
1.126 brouard 666: double **oldm, **newm, **savm; /* Working pointers to matrices */
667: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 668: /*FILE *fic ; */ /* Used in readdata only */
669: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 670: FILE *ficlog, *ficrespow;
1.130 brouard 671: int globpr=0; /* Global variable for printing or not */
1.126 brouard 672: double fretone; /* Only one call to likelihood */
1.130 brouard 673: long ipmx=0; /* Number of contributions */
1.126 brouard 674: double sw; /* Sum of weights */
675: char filerespow[FILENAMELENGTH];
676: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
677: FILE *ficresilk;
678: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
679: FILE *ficresprobmorprev;
680: FILE *fichtm, *fichtmcov; /* Html File */
681: FILE *ficreseij;
682: char filerese[FILENAMELENGTH];
683: FILE *ficresstdeij;
684: char fileresstde[FILENAMELENGTH];
685: FILE *ficrescveij;
686: char filerescve[FILENAMELENGTH];
687: FILE *ficresvij;
688: char fileresv[FILENAMELENGTH];
689: FILE *ficresvpl;
690: char fileresvpl[FILENAMELENGTH];
691: char title[MAXLINE];
692: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
693: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
694: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
695: char command[FILENAMELENGTH];
696: int outcmd=0;
697:
698: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
699:
700: char filelog[FILENAMELENGTH]; /* Log file */
701: char filerest[FILENAMELENGTH];
702: char fileregp[FILENAMELENGTH];
703: char popfile[FILENAMELENGTH];
704:
705: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
706:
1.157 brouard 707: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
708: /* struct timezone tzp; */
709: /* extern int gettimeofday(); */
710: struct tm tml, *gmtime(), *localtime();
711:
712: extern time_t time();
713:
714: struct tm start_time, end_time, curr_time, last_time, forecast_time;
715: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
716: struct tm tm;
717:
1.126 brouard 718: char strcurr[80], strfor[80];
719:
720: char *endptr;
721: long lval;
722: double dval;
723:
724: #define NR_END 1
725: #define FREE_ARG char*
726: #define FTOL 1.0e-10
727:
728: #define NRANSI
729: #define ITMAX 200
730:
731: #define TOL 2.0e-4
732:
733: #define CGOLD 0.3819660
734: #define ZEPS 1.0e-10
735: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
736:
737: #define GOLD 1.618034
738: #define GLIMIT 100.0
739: #define TINY 1.0e-20
740:
741: static double maxarg1,maxarg2;
742: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
743: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
744:
745: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
746: #define rint(a) floor(a+0.5)
1.166 brouard 747: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
748: /* #define mytinydouble 1.0e-16 */
749: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
750: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
751: /* static double dsqrarg; */
752: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 753: static double sqrarg;
754: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
755: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
756: int agegomp= AGEGOMP;
757:
758: int imx;
759: int stepm=1;
760: /* Stepm, step in month: minimum step interpolation*/
761:
762: int estepm;
763: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
764:
765: int m,nb;
766: long *num;
767: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
768: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
769: double **pmmij, ***probs;
770: double *ageexmed,*agecens;
771: double dateintmean=0;
772:
773: double *weight;
774: int **s; /* Status */
1.141 brouard 775: double *agedc;
1.145 brouard 776: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 777: * covar=matrix(0,NCOVMAX,1,n);
778: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
779: double idx;
780: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 781: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 782: int **codtab; /**< codtab=imatrix(1,100,1,10); */
783: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 784: double *lsurv, *lpop, *tpop;
785:
1.143 brouard 786: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
787: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 788:
789: /**************** split *************************/
790: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
791: {
792: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
793: the name of the file (name), its extension only (ext) and its first part of the name (finame)
794: */
795: char *ss; /* pointer */
796: int l1, l2; /* length counters */
797:
798: l1 = strlen(path ); /* length of path */
799: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
800: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
801: if ( ss == NULL ) { /* no directory, so determine current directory */
802: strcpy( name, path ); /* we got the fullname name because no directory */
803: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
804: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
805: /* get current working directory */
806: /* extern char* getcwd ( char *buf , int len);*/
807: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
808: return( GLOCK_ERROR_GETCWD );
809: }
810: /* got dirc from getcwd*/
811: printf(" DIRC = %s \n",dirc);
812: } else { /* strip direcotry from path */
813: ss++; /* after this, the filename */
814: l2 = strlen( ss ); /* length of filename */
815: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
816: strcpy( name, ss ); /* save file name */
817: strncpy( dirc, path, l1 - l2 ); /* now the directory */
818: dirc[l1-l2] = 0; /* add zero */
819: printf(" DIRC2 = %s \n",dirc);
820: }
821: /* We add a separator at the end of dirc if not exists */
822: l1 = strlen( dirc ); /* length of directory */
823: if( dirc[l1-1] != DIRSEPARATOR ){
824: dirc[l1] = DIRSEPARATOR;
825: dirc[l1+1] = 0;
826: printf(" DIRC3 = %s \n",dirc);
827: }
828: ss = strrchr( name, '.' ); /* find last / */
829: if (ss >0){
830: ss++;
831: strcpy(ext,ss); /* save extension */
832: l1= strlen( name);
833: l2= strlen(ss)+1;
834: strncpy( finame, name, l1-l2);
835: finame[l1-l2]= 0;
836: }
837:
838: return( 0 ); /* we're done */
839: }
840:
841:
842: /******************************************/
843:
844: void replace_back_to_slash(char *s, char*t)
845: {
846: int i;
847: int lg=0;
848: i=0;
849: lg=strlen(t);
850: for(i=0; i<= lg; i++) {
851: (s[i] = t[i]);
852: if (t[i]== '\\') s[i]='/';
853: }
854: }
855:
1.132 brouard 856: char *trimbb(char *out, char *in)
1.137 brouard 857: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 858: char *s;
859: s=out;
860: while (*in != '\0'){
1.137 brouard 861: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 862: in++;
863: }
864: *out++ = *in++;
865: }
866: *out='\0';
867: return s;
868: }
869:
1.145 brouard 870: char *cutl(char *blocc, char *alocc, char *in, char occ)
871: {
872: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
873: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
874: gives blocc="abcdef2ghi" and alocc="j".
875: If occ is not found blocc is null and alocc is equal to in. Returns blocc
876: */
1.160 brouard 877: char *s, *t;
1.145 brouard 878: t=in;s=in;
879: while ((*in != occ) && (*in != '\0')){
880: *alocc++ = *in++;
881: }
882: if( *in == occ){
883: *(alocc)='\0';
884: s=++in;
885: }
886:
887: if (s == t) {/* occ not found */
888: *(alocc-(in-s))='\0';
889: in=s;
890: }
891: while ( *in != '\0'){
892: *blocc++ = *in++;
893: }
894:
895: *blocc='\0';
896: return t;
897: }
1.137 brouard 898: char *cutv(char *blocc, char *alocc, char *in, char occ)
899: {
900: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
901: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
902: gives blocc="abcdef2ghi" and alocc="j".
903: If occ is not found blocc is null and alocc is equal to in. Returns alocc
904: */
905: char *s, *t;
906: t=in;s=in;
907: while (*in != '\0'){
908: while( *in == occ){
909: *blocc++ = *in++;
910: s=in;
911: }
912: *blocc++ = *in++;
913: }
914: if (s == t) /* occ not found */
915: *(blocc-(in-s))='\0';
916: else
917: *(blocc-(in-s)-1)='\0';
918: in=s;
919: while ( *in != '\0'){
920: *alocc++ = *in++;
921: }
922:
923: *alocc='\0';
924: return s;
925: }
926:
1.126 brouard 927: int nbocc(char *s, char occ)
928: {
929: int i,j=0;
930: int lg=20;
931: i=0;
932: lg=strlen(s);
933: for(i=0; i<= lg; i++) {
934: if (s[i] == occ ) j++;
935: }
936: return j;
937: }
938:
1.137 brouard 939: /* void cutv(char *u,char *v, char*t, char occ) */
940: /* { */
941: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
942: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
943: /* gives u="abcdef2ghi" and v="j" *\/ */
944: /* int i,lg,j,p=0; */
945: /* i=0; */
946: /* lg=strlen(t); */
947: /* for(j=0; j<=lg-1; j++) { */
948: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
949: /* } */
1.126 brouard 950:
1.137 brouard 951: /* for(j=0; j<p; j++) { */
952: /* (u[j] = t[j]); */
953: /* } */
954: /* u[p]='\0'; */
1.126 brouard 955:
1.137 brouard 956: /* for(j=0; j<= lg; j++) { */
957: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
958: /* } */
959: /* } */
1.126 brouard 960:
1.160 brouard 961: #ifdef _WIN32
962: char * strsep(char **pp, const char *delim)
963: {
964: char *p, *q;
965:
966: if ((p = *pp) == NULL)
967: return 0;
968: if ((q = strpbrk (p, delim)) != NULL)
969: {
970: *pp = q + 1;
971: *q = '\0';
972: }
973: else
974: *pp = 0;
975: return p;
976: }
977: #endif
978:
1.126 brouard 979: /********************** nrerror ********************/
980:
981: void nrerror(char error_text[])
982: {
983: fprintf(stderr,"ERREUR ...\n");
984: fprintf(stderr,"%s\n",error_text);
985: exit(EXIT_FAILURE);
986: }
987: /*********************** vector *******************/
988: double *vector(int nl, int nh)
989: {
990: double *v;
991: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
992: if (!v) nrerror("allocation failure in vector");
993: return v-nl+NR_END;
994: }
995:
996: /************************ free vector ******************/
997: void free_vector(double*v, int nl, int nh)
998: {
999: free((FREE_ARG)(v+nl-NR_END));
1000: }
1001:
1002: /************************ivector *******************************/
1003: int *ivector(long nl,long nh)
1004: {
1005: int *v;
1006: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1007: if (!v) nrerror("allocation failure in ivector");
1008: return v-nl+NR_END;
1009: }
1010:
1011: /******************free ivector **************************/
1012: void free_ivector(int *v, long nl, long nh)
1013: {
1014: free((FREE_ARG)(v+nl-NR_END));
1015: }
1016:
1017: /************************lvector *******************************/
1018: long *lvector(long nl,long nh)
1019: {
1020: long *v;
1021: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1022: if (!v) nrerror("allocation failure in ivector");
1023: return v-nl+NR_END;
1024: }
1025:
1026: /******************free lvector **************************/
1027: void free_lvector(long *v, long nl, long nh)
1028: {
1029: free((FREE_ARG)(v+nl-NR_END));
1030: }
1031:
1032: /******************* imatrix *******************************/
1033: int **imatrix(long nrl, long nrh, long ncl, long nch)
1034: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1035: {
1036: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1037: int **m;
1038:
1039: /* allocate pointers to rows */
1040: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1041: if (!m) nrerror("allocation failure 1 in matrix()");
1042: m += NR_END;
1043: m -= nrl;
1044:
1045:
1046: /* allocate rows and set pointers to them */
1047: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1048: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1049: m[nrl] += NR_END;
1050: m[nrl] -= ncl;
1051:
1052: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1053:
1054: /* return pointer to array of pointers to rows */
1055: return m;
1056: }
1057:
1058: /****************** free_imatrix *************************/
1059: void free_imatrix(m,nrl,nrh,ncl,nch)
1060: int **m;
1061: long nch,ncl,nrh,nrl;
1062: /* free an int matrix allocated by imatrix() */
1063: {
1064: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1065: free((FREE_ARG) (m+nrl-NR_END));
1066: }
1067:
1068: /******************* matrix *******************************/
1069: double **matrix(long nrl, long nrh, long ncl, long nch)
1070: {
1071: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1072: double **m;
1073:
1074: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1075: if (!m) nrerror("allocation failure 1 in matrix()");
1076: m += NR_END;
1077: m -= nrl;
1078:
1079: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1080: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1081: m[nrl] += NR_END;
1082: m[nrl] -= ncl;
1083:
1084: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1085: return m;
1.145 brouard 1086: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1087: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1088: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1089: */
1090: }
1091:
1092: /*************************free matrix ************************/
1093: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1094: {
1095: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1096: free((FREE_ARG)(m+nrl-NR_END));
1097: }
1098:
1099: /******************* ma3x *******************************/
1100: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1101: {
1102: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1103: double ***m;
1104:
1105: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1106: if (!m) nrerror("allocation failure 1 in matrix()");
1107: m += NR_END;
1108: m -= nrl;
1109:
1110: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1111: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1112: m[nrl] += NR_END;
1113: m[nrl] -= ncl;
1114:
1115: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1116:
1117: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1118: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1119: m[nrl][ncl] += NR_END;
1120: m[nrl][ncl] -= nll;
1121: for (j=ncl+1; j<=nch; j++)
1122: m[nrl][j]=m[nrl][j-1]+nlay;
1123:
1124: for (i=nrl+1; i<=nrh; i++) {
1125: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1126: for (j=ncl+1; j<=nch; j++)
1127: m[i][j]=m[i][j-1]+nlay;
1128: }
1129: return m;
1130: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1131: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1132: */
1133: }
1134:
1135: /*************************free ma3x ************************/
1136: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1137: {
1138: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1139: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1140: free((FREE_ARG)(m+nrl-NR_END));
1141: }
1142:
1143: /*************** function subdirf ***********/
1144: char *subdirf(char fileres[])
1145: {
1146: /* Caution optionfilefiname is hidden */
1147: strcpy(tmpout,optionfilefiname);
1148: strcat(tmpout,"/"); /* Add to the right */
1149: strcat(tmpout,fileres);
1150: return tmpout;
1151: }
1152:
1153: /*************** function subdirf2 ***********/
1154: char *subdirf2(char fileres[], char *preop)
1155: {
1156:
1157: /* Caution optionfilefiname is hidden */
1158: strcpy(tmpout,optionfilefiname);
1159: strcat(tmpout,"/");
1160: strcat(tmpout,preop);
1161: strcat(tmpout,fileres);
1162: return tmpout;
1163: }
1164:
1165: /*************** function subdirf3 ***********/
1166: char *subdirf3(char fileres[], char *preop, char *preop2)
1167: {
1168:
1169: /* Caution optionfilefiname is hidden */
1170: strcpy(tmpout,optionfilefiname);
1171: strcat(tmpout,"/");
1172: strcat(tmpout,preop);
1173: strcat(tmpout,preop2);
1174: strcat(tmpout,fileres);
1175: return tmpout;
1176: }
1177:
1.162 brouard 1178: char *asc_diff_time(long time_sec, char ascdiff[])
1179: {
1180: long sec_left, days, hours, minutes;
1181: days = (time_sec) / (60*60*24);
1182: sec_left = (time_sec) % (60*60*24);
1183: hours = (sec_left) / (60*60) ;
1184: sec_left = (sec_left) %(60*60);
1185: minutes = (sec_left) /60;
1186: sec_left = (sec_left) % (60);
1187: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1188: return ascdiff;
1189: }
1190:
1.126 brouard 1191: /***************** f1dim *************************/
1192: extern int ncom;
1193: extern double *pcom,*xicom;
1194: extern double (*nrfunc)(double []);
1195:
1196: double f1dim(double x)
1197: {
1198: int j;
1199: double f;
1200: double *xt;
1201:
1202: xt=vector(1,ncom);
1203: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1204: f=(*nrfunc)(xt);
1205: free_vector(xt,1,ncom);
1206: return f;
1207: }
1208:
1209: /*****************brent *************************/
1210: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1211: {
1212: int iter;
1213: double a,b,d,etemp;
1.159 brouard 1214: double fu=0,fv,fw,fx;
1.164 brouard 1215: double ftemp=0.;
1.126 brouard 1216: double p,q,r,tol1,tol2,u,v,w,x,xm;
1217: double e=0.0;
1218:
1219: a=(ax < cx ? ax : cx);
1220: b=(ax > cx ? ax : cx);
1221: x=w=v=bx;
1222: fw=fv=fx=(*f)(x);
1223: for (iter=1;iter<=ITMAX;iter++) {
1224: xm=0.5*(a+b);
1225: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1226: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1227: printf(".");fflush(stdout);
1228: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1229: #ifdef DEBUGBRENT
1.126 brouard 1230: 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);
1231: 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);
1232: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1233: #endif
1234: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1235: *xmin=x;
1236: return fx;
1237: }
1238: ftemp=fu;
1239: if (fabs(e) > tol1) {
1240: r=(x-w)*(fx-fv);
1241: q=(x-v)*(fx-fw);
1242: p=(x-v)*q-(x-w)*r;
1243: q=2.0*(q-r);
1244: if (q > 0.0) p = -p;
1245: q=fabs(q);
1246: etemp=e;
1247: e=d;
1248: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1249: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1250: else {
1251: d=p/q;
1252: u=x+d;
1253: if (u-a < tol2 || b-u < tol2)
1254: d=SIGN(tol1,xm-x);
1255: }
1256: } else {
1257: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1258: }
1259: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1260: fu=(*f)(u);
1261: if (fu <= fx) {
1262: if (u >= x) a=x; else b=x;
1263: SHFT(v,w,x,u)
1264: SHFT(fv,fw,fx,fu)
1265: } else {
1266: if (u < x) a=u; else b=u;
1267: if (fu <= fw || w == x) {
1268: v=w;
1269: w=u;
1270: fv=fw;
1271: fw=fu;
1272: } else if (fu <= fv || v == x || v == w) {
1273: v=u;
1274: fv=fu;
1275: }
1276: }
1277: }
1278: nrerror("Too many iterations in brent");
1279: *xmin=x;
1280: return fx;
1281: }
1282:
1283: /****************** mnbrak ***********************/
1284:
1285: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1286: double (*func)(double))
1287: {
1288: double ulim,u,r,q, dum;
1289: double fu;
1290:
1291: *fa=(*func)(*ax);
1292: *fb=(*func)(*bx);
1293: if (*fb > *fa) {
1294: SHFT(dum,*ax,*bx,dum)
1295: SHFT(dum,*fb,*fa,dum)
1296: }
1297: *cx=(*bx)+GOLD*(*bx-*ax);
1298: *fc=(*func)(*cx);
1.162 brouard 1299: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1300: r=(*bx-*ax)*(*fb-*fc);
1301: q=(*bx-*cx)*(*fb-*fa);
1302: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1303: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1304: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1305: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1306: fu=(*func)(u);
1.163 brouard 1307: #ifdef DEBUG
1308: /* f(x)=A(x-u)**2+f(u) */
1309: double A, fparabu;
1310: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1311: fparabu= *fa - A*(*ax-u)*(*ax-u);
1312: 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);
1313: 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);
1314: #endif
1.162 brouard 1315: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1316: fu=(*func)(u);
1317: if (fu < *fc) {
1318: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1319: SHFT(*fb,*fc,fu,(*func)(u))
1320: }
1.162 brouard 1321: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1322: u=ulim;
1323: fu=(*func)(u);
1324: } else {
1325: u=(*cx)+GOLD*(*cx-*bx);
1326: fu=(*func)(u);
1327: }
1328: SHFT(*ax,*bx,*cx,u)
1329: SHFT(*fa,*fb,*fc,fu)
1330: }
1331: }
1332:
1333: /*************** linmin ************************/
1.162 brouard 1334: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1335: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1336: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1337: the value of func at the returned location p . This is actually all accomplished by calling the
1338: routines mnbrak and brent .*/
1.126 brouard 1339: int ncom;
1340: double *pcom,*xicom;
1341: double (*nrfunc)(double []);
1342:
1343: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1344: {
1345: double brent(double ax, double bx, double cx,
1346: double (*f)(double), double tol, double *xmin);
1347: double f1dim(double x);
1348: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1349: double *fc, double (*func)(double));
1350: int j;
1351: double xx,xmin,bx,ax;
1352: double fx,fb,fa;
1353:
1354: ncom=n;
1355: pcom=vector(1,n);
1356: xicom=vector(1,n);
1357: nrfunc=func;
1358: for (j=1;j<=n;j++) {
1359: pcom[j]=p[j];
1360: xicom[j]=xi[j];
1361: }
1362: ax=0.0;
1363: xx=1.0;
1.162 brouard 1364: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1365: *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 1366: #ifdef DEBUG
1367: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1368: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1369: #endif
1370: for (j=1;j<=n;j++) {
1371: xi[j] *= xmin;
1372: p[j] += xi[j];
1373: }
1374: free_vector(xicom,1,n);
1375: free_vector(pcom,1,n);
1376: }
1377:
1378:
1379: /*************** powell ************************/
1.162 brouard 1380: /*
1381: Minimization of a function func of n variables. Input consists of an initial starting point
1382: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1383: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1384: such that failure to decrease by more than this amount on one iteration signals doneness. On
1385: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1386: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1387: */
1.126 brouard 1388: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1389: double (*func)(double []))
1390: {
1391: void linmin(double p[], double xi[], int n, double *fret,
1392: double (*func)(double []));
1393: int i,ibig,j;
1394: double del,t,*pt,*ptt,*xit;
1395: double fp,fptt;
1396: double *xits;
1397: int niterf, itmp;
1398:
1399: pt=vector(1,n);
1400: ptt=vector(1,n);
1401: xit=vector(1,n);
1402: xits=vector(1,n);
1403: *fret=(*func)(p);
1404: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1405: rcurr_time = time(NULL);
1.126 brouard 1406: for (*iter=1;;++(*iter)) {
1407: fp=(*fret);
1408: ibig=0;
1409: del=0.0;
1.157 brouard 1410: rlast_time=rcurr_time;
1411: /* (void) gettimeofday(&curr_time,&tzp); */
1412: rcurr_time = time(NULL);
1413: curr_time = *localtime(&rcurr_time);
1414: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1415: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1416: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1417: for (i=1;i<=n;i++) {
1418: printf(" %d %.12f",i, p[i]);
1419: fprintf(ficlog," %d %.12lf",i, p[i]);
1420: fprintf(ficrespow," %.12lf", p[i]);
1421: }
1422: printf("\n");
1423: fprintf(ficlog,"\n");
1424: fprintf(ficrespow,"\n");fflush(ficrespow);
1425: if(*iter <=3){
1.157 brouard 1426: tml = *localtime(&rcurr_time);
1427: strcpy(strcurr,asctime(&tml));
1428: rforecast_time=rcurr_time;
1.126 brouard 1429: itmp = strlen(strcurr);
1430: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1431: strcurr[itmp-1]='\0';
1.162 brouard 1432: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1433: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1434: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1435: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1436: forecast_time = *localtime(&rforecast_time);
1437: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1438: itmp = strlen(strfor);
1439: if(strfor[itmp-1]=='\n')
1440: strfor[itmp-1]='\0';
1.157 brouard 1441: 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);
1442: 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 1443: }
1444: }
1445: for (i=1;i<=n;i++) {
1446: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1447: fptt=(*fret);
1448: #ifdef DEBUG
1.164 brouard 1449: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1450: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1451: #endif
1452: printf("%d",i);fflush(stdout);
1453: fprintf(ficlog,"%d",i);fflush(ficlog);
1454: linmin(p,xit,n,fret,func);
1455: if (fabs(fptt-(*fret)) > del) {
1456: del=fabs(fptt-(*fret));
1457: ibig=i;
1458: }
1459: #ifdef DEBUG
1460: printf("%d %.12e",i,(*fret));
1461: fprintf(ficlog,"%d %.12e",i,(*fret));
1462: for (j=1;j<=n;j++) {
1463: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1464: printf(" x(%d)=%.12e",j,xit[j]);
1465: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1466: }
1467: for(j=1;j<=n;j++) {
1.162 brouard 1468: printf(" p(%d)=%.12e",j,p[j]);
1469: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1470: }
1471: printf("\n");
1472: fprintf(ficlog,"\n");
1473: #endif
1.162 brouard 1474: } /* end i */
1.126 brouard 1475: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1476: #ifdef DEBUG
1477: int k[2],l;
1478: k[0]=1;
1479: k[1]=-1;
1480: printf("Max: %.12e",(*func)(p));
1481: fprintf(ficlog,"Max: %.12e",(*func)(p));
1482: for (j=1;j<=n;j++) {
1483: printf(" %.12e",p[j]);
1484: fprintf(ficlog," %.12e",p[j]);
1485: }
1486: printf("\n");
1487: fprintf(ficlog,"\n");
1488: for(l=0;l<=1;l++) {
1489: for (j=1;j<=n;j++) {
1490: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1491: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1492: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1493: }
1494: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1495: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1496: }
1497: #endif
1498:
1499:
1500: free_vector(xit,1,n);
1501: free_vector(xits,1,n);
1502: free_vector(ptt,1,n);
1503: free_vector(pt,1,n);
1504: return;
1505: }
1506: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1507: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1508: ptt[j]=2.0*p[j]-pt[j];
1509: xit[j]=p[j]-pt[j];
1510: pt[j]=p[j];
1511: }
1512: fptt=(*func)(ptt);
1.161 brouard 1513: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1514: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1515: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1516: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1517: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1518: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1519: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1520: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1521: /* or best gain on one ancient line 'del' with total */
1522: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1523: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1524:
1.161 brouard 1525: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1526: t= t- del*SQR(fp-fptt);
1527: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1528: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1529: #ifdef DEBUG
1530: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1531: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1532: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1533: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1534: 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);
1535: 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);
1536: #endif
1537: if (t < 0.0) { /* Then we use it for last direction */
1538: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1539: for (j=1;j<=n;j++) {
1.161 brouard 1540: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1541: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1542: }
1.161 brouard 1543: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169 brouard 1544: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1545:
1.126 brouard 1546: #ifdef DEBUG
1.164 brouard 1547: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1548: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1549: for(j=1;j<=n;j++){
1550: printf(" %.12e",xit[j]);
1551: fprintf(ficlog," %.12e",xit[j]);
1552: }
1553: printf("\n");
1554: fprintf(ficlog,"\n");
1555: #endif
1.162 brouard 1556: } /* end of t negative */
1557: } /* end if (fptt < fp) */
1.126 brouard 1558: }
1559: }
1560:
1561: /**** Prevalence limit (stable or period prevalence) ****************/
1562:
1563: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1564: {
1565: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1566: matrix by transitions matrix until convergence is reached */
1.169 brouard 1567:
1.126 brouard 1568: int i, ii,j,k;
1569: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1570: /* double **matprod2(); */ /* test */
1.131 brouard 1571: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1572: double **newm;
1573: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1574:
1.126 brouard 1575: for (ii=1;ii<=nlstate+ndeath;ii++)
1576: for (j=1;j<=nlstate+ndeath;j++){
1577: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1578: }
1.169 brouard 1579:
1580: cov[1]=1.;
1581:
1582: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1583: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1584: newm=savm;
1585: /* Covariates have to be included here again */
1.138 brouard 1586: cov[2]=agefin;
1587:
1588: for (k=1; k<=cptcovn;k++) {
1589: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1590: /*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 1591: }
1.145 brouard 1592: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1593: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1594: /* 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 1595:
1596: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1597: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1598: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1599: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1600: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1601: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1602:
1.126 brouard 1603: savm=oldm;
1604: oldm=newm;
1605: maxmax=0.;
1606: for(j=1;j<=nlstate;j++){
1607: min=1.;
1608: max=0.;
1609: for(i=1; i<=nlstate; i++) {
1610: sumnew=0;
1611: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1612: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1613: /*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 1614: max=FMAX(max,prlim[i][j]);
1615: min=FMIN(min,prlim[i][j]);
1616: }
1617: maxmin=max-min;
1618: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1619: } /* j loop */
1.126 brouard 1620: if(maxmax < ftolpl){
1621: return prlim;
1622: }
1.169 brouard 1623: } /* age loop */
1624: return prlim; /* should not reach here */
1.126 brouard 1625: }
1626:
1627: /*************** transition probabilities ***************/
1628:
1629: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1630: {
1.138 brouard 1631: /* According to parameters values stored in x and the covariate's values stored in cov,
1632: computes the probability to be observed in state j being in state i by appying the
1633: model to the ncovmodel covariates (including constant and age).
1634: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1635: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1636: ncth covariate in the global vector x is given by the formula:
1637: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1638: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1639: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1640: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1641: Outputs ps[i][j] the probability to be observed in j being in j according to
1642: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1643: */
1644: double s1, lnpijopii;
1.126 brouard 1645: /*double t34;*/
1.164 brouard 1646: int i,j, nc, ii, jj;
1.126 brouard 1647:
1648: for(i=1; i<= nlstate; i++){
1649: for(j=1; j<i;j++){
1.138 brouard 1650: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1651: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1652: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1653: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1654: }
1.138 brouard 1655: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1656: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1657: }
1658: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1659: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1660: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1661: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1662: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1663: }
1.138 brouard 1664: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1665: }
1666: }
1667:
1668: for(i=1; i<= nlstate; i++){
1669: s1=0;
1.131 brouard 1670: for(j=1; j<i; j++){
1.138 brouard 1671: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1672: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1673: }
1674: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1675: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1676: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1677: }
1.138 brouard 1678: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1679: ps[i][i]=1./(s1+1.);
1.138 brouard 1680: /* Computing other pijs */
1.126 brouard 1681: for(j=1; j<i; j++)
1682: ps[i][j]= exp(ps[i][j])*ps[i][i];
1683: for(j=i+1; j<=nlstate+ndeath; j++)
1684: ps[i][j]= exp(ps[i][j])*ps[i][i];
1685: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1686: } /* end i */
1687:
1688: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1689: for(jj=1; jj<= nlstate+ndeath; jj++){
1690: ps[ii][jj]=0;
1691: ps[ii][ii]=1;
1692: }
1693: }
1694:
1.145 brouard 1695:
1696: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1697: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1698: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1699: /* } */
1700: /* printf("\n "); */
1701: /* } */
1702: /* printf("\n ");printf("%lf ",cov[2]);*/
1703: /*
1.126 brouard 1704: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1705: goto end;*/
1706: return ps;
1707: }
1708:
1709: /**************** Product of 2 matrices ******************/
1710:
1.145 brouard 1711: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1712: {
1713: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1714: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1715: /* in, b, out are matrice of pointers which should have been initialized
1716: before: only the contents of out is modified. The function returns
1717: a pointer to pointers identical to out */
1.145 brouard 1718: int i, j, k;
1.126 brouard 1719: for(i=nrl; i<= nrh; i++)
1.145 brouard 1720: for(k=ncolol; k<=ncoloh; k++){
1721: out[i][k]=0.;
1722: for(j=ncl; j<=nch; j++)
1723: out[i][k] +=in[i][j]*b[j][k];
1724: }
1.126 brouard 1725: return out;
1726: }
1727:
1728:
1729: /************* Higher Matrix Product ***************/
1730:
1731: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1732: {
1733: /* Computes the transition matrix starting at age 'age' over
1734: 'nhstepm*hstepm*stepm' months (i.e. until
1735: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1736: nhstepm*hstepm matrices.
1737: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1738: (typically every 2 years instead of every month which is too big
1739: for the memory).
1740: Model is determined by parameters x and covariates have to be
1741: included manually here.
1742:
1743: */
1744:
1745: int i, j, d, h, k;
1.131 brouard 1746: double **out, cov[NCOVMAX+1];
1.126 brouard 1747: double **newm;
1748:
1749: /* Hstepm could be zero and should return the unit matrix */
1750: for (i=1;i<=nlstate+ndeath;i++)
1751: for (j=1;j<=nlstate+ndeath;j++){
1752: oldm[i][j]=(i==j ? 1.0 : 0.0);
1753: po[i][j][0]=(i==j ? 1.0 : 0.0);
1754: }
1755: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1756: for(h=1; h <=nhstepm; h++){
1757: for(d=1; d <=hstepm; d++){
1758: newm=savm;
1759: /* Covariates have to be included here again */
1760: cov[1]=1.;
1761: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1762: for (k=1; k<=cptcovn;k++)
1763: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1764: for (k=1; k<=cptcovage;k++)
1765: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1766: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1767: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1768:
1769:
1770: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1771: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1772: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1773: pmij(pmmij,cov,ncovmodel,x,nlstate));
1774: savm=oldm;
1775: oldm=newm;
1776: }
1777: for(i=1; i<=nlstate+ndeath; i++)
1778: for(j=1;j<=nlstate+ndeath;j++) {
1779: po[i][j][h]=newm[i][j];
1.128 brouard 1780: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1781: }
1.128 brouard 1782: /*printf("h=%d ",h);*/
1.126 brouard 1783: } /* end h */
1.128 brouard 1784: /* printf("\n H=%d \n",h); */
1.126 brouard 1785: return po;
1786: }
1787:
1.162 brouard 1788: #ifdef NLOPT
1789: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1790: double fret;
1791: double *xt;
1792: int j;
1793: myfunc_data *d2 = (myfunc_data *) pd;
1794: /* xt = (p1-1); */
1795: xt=vector(1,n);
1796: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1797:
1798: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1799: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1800: printf("Function = %.12lf ",fret);
1801: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1802: printf("\n");
1803: free_vector(xt,1,n);
1804: return fret;
1805: }
1806: #endif
1.126 brouard 1807:
1808: /*************** log-likelihood *************/
1809: double func( double *x)
1810: {
1811: int i, ii, j, k, mi, d, kk;
1.131 brouard 1812: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1813: double **out;
1814: double sw; /* Sum of weights */
1815: double lli; /* Individual log likelihood */
1816: int s1, s2;
1817: double bbh, survp;
1818: long ipmx;
1819: /*extern weight */
1820: /* We are differentiating ll according to initial status */
1821: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1822: /*for(i=1;i<imx;i++)
1823: printf(" %d\n",s[4][i]);
1824: */
1.162 brouard 1825:
1826: ++countcallfunc;
1827:
1.126 brouard 1828: cov[1]=1.;
1829:
1830: for(k=1; k<=nlstate; k++) ll[k]=0.;
1831:
1832: if(mle==1){
1833: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1834: /* Computes the values of the ncovmodel covariates of the model
1835: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1836: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1837: to be observed in j being in i according to the model.
1838: */
1.145 brouard 1839: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1840: cov[2+k]=covar[Tvar[k]][i];
1841: }
1.137 brouard 1842: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1843: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1844: has been calculated etc */
1.126 brouard 1845: for(mi=1; mi<= wav[i]-1; mi++){
1846: for (ii=1;ii<=nlstate+ndeath;ii++)
1847: for (j=1;j<=nlstate+ndeath;j++){
1848: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1849: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1850: }
1851: for(d=0; d<dh[mi][i]; d++){
1852: newm=savm;
1853: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1854: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1855: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1856: }
1857: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1858: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1859: savm=oldm;
1860: oldm=newm;
1861: } /* end mult */
1862:
1863: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1864: /* But now since version 0.9 we anticipate for bias at large stepm.
1865: * If stepm is larger than one month (smallest stepm) and if the exact delay
1866: * (in months) between two waves is not a multiple of stepm, we rounded to
1867: * the nearest (and in case of equal distance, to the lowest) interval but now
1868: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1869: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1870: * probability in order to take into account the bias as a fraction of the way
1871: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1872: * -stepm/2 to stepm/2 .
1873: * For stepm=1 the results are the same as for previous versions of Imach.
1874: * For stepm > 1 the results are less biased than in previous versions.
1875: */
1876: s1=s[mw[mi][i]][i];
1877: s2=s[mw[mi+1][i]][i];
1878: bbh=(double)bh[mi][i]/(double)stepm;
1879: /* bias bh is positive if real duration
1880: * is higher than the multiple of stepm and negative otherwise.
1881: */
1882: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1883: if( s2 > nlstate){
1884: /* i.e. if s2 is a death state and if the date of death is known
1885: then the contribution to the likelihood is the probability to
1886: die between last step unit time and current step unit time,
1887: which is also equal to probability to die before dh
1888: minus probability to die before dh-stepm .
1889: In version up to 0.92 likelihood was computed
1890: as if date of death was unknown. Death was treated as any other
1891: health state: the date of the interview describes the actual state
1892: and not the date of a change in health state. The former idea was
1893: to consider that at each interview the state was recorded
1894: (healthy, disable or death) and IMaCh was corrected; but when we
1895: introduced the exact date of death then we should have modified
1896: the contribution of an exact death to the likelihood. This new
1897: contribution is smaller and very dependent of the step unit
1898: stepm. It is no more the probability to die between last interview
1899: and month of death but the probability to survive from last
1900: interview up to one month before death multiplied by the
1901: probability to die within a month. Thanks to Chris
1902: Jackson for correcting this bug. Former versions increased
1903: mortality artificially. The bad side is that we add another loop
1904: which slows down the processing. The difference can be up to 10%
1905: lower mortality.
1906: */
1907: lli=log(out[s1][s2] - savm[s1][s2]);
1908:
1909:
1910: } else if (s2==-2) {
1911: for (j=1,survp=0. ; j<=nlstate; j++)
1912: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1913: /*survp += out[s1][j]; */
1914: lli= log(survp);
1915: }
1916:
1917: else if (s2==-4) {
1918: for (j=3,survp=0. ; j<=nlstate; j++)
1919: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1920: lli= log(survp);
1921: }
1922:
1923: else if (s2==-5) {
1924: for (j=1,survp=0. ; j<=2; j++)
1925: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1926: lli= log(survp);
1927: }
1928:
1929: else{
1930: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1931: /* 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 */
1932: }
1933: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1934: /*if(lli ==000.0)*/
1935: /*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); */
1936: ipmx +=1;
1937: sw += weight[i];
1938: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1939: } /* end of wave */
1940: } /* end of individual */
1941: } else if(mle==2){
1942: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1943: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1944: for(mi=1; mi<= wav[i]-1; mi++){
1945: for (ii=1;ii<=nlstate+ndeath;ii++)
1946: for (j=1;j<=nlstate+ndeath;j++){
1947: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1948: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1949: }
1950: for(d=0; d<=dh[mi][i]; d++){
1951: newm=savm;
1952: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1953: for (kk=1; kk<=cptcovage;kk++) {
1954: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1955: }
1956: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1957: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1958: savm=oldm;
1959: oldm=newm;
1960: } /* end mult */
1961:
1962: s1=s[mw[mi][i]][i];
1963: s2=s[mw[mi+1][i]][i];
1964: bbh=(double)bh[mi][i]/(double)stepm;
1965: 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 */
1966: ipmx +=1;
1967: sw += weight[i];
1968: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1969: } /* end of wave */
1970: } /* end of individual */
1971: } else if(mle==3){ /* exponential inter-extrapolation */
1972: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1973: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1974: for(mi=1; mi<= wav[i]-1; mi++){
1975: for (ii=1;ii<=nlstate+ndeath;ii++)
1976: for (j=1;j<=nlstate+ndeath;j++){
1977: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1978: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1979: }
1980: for(d=0; d<dh[mi][i]; d++){
1981: newm=savm;
1982: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1983: for (kk=1; kk<=cptcovage;kk++) {
1984: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1985: }
1986: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1987: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1988: savm=oldm;
1989: oldm=newm;
1990: } /* end mult */
1991:
1992: s1=s[mw[mi][i]][i];
1993: s2=s[mw[mi+1][i]][i];
1994: bbh=(double)bh[mi][i]/(double)stepm;
1995: 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 */
1996: ipmx +=1;
1997: sw += weight[i];
1998: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1999: } /* end of wave */
2000: } /* end of individual */
2001: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2002: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2003: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2004: for(mi=1; mi<= wav[i]-1; mi++){
2005: for (ii=1;ii<=nlstate+ndeath;ii++)
2006: for (j=1;j<=nlstate+ndeath;j++){
2007: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2008: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2009: }
2010: for(d=0; d<dh[mi][i]; d++){
2011: newm=savm;
2012: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2013: for (kk=1; kk<=cptcovage;kk++) {
2014: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2015: }
2016:
2017: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2018: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2019: savm=oldm;
2020: oldm=newm;
2021: } /* end mult */
2022:
2023: s1=s[mw[mi][i]][i];
2024: s2=s[mw[mi+1][i]][i];
2025: if( s2 > nlstate){
2026: lli=log(out[s1][s2] - savm[s1][s2]);
2027: }else{
2028: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2029: }
2030: ipmx +=1;
2031: sw += weight[i];
2032: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2033: /* 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]); */
2034: } /* end of wave */
2035: } /* end of individual */
2036: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2037: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2038: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2039: for(mi=1; mi<= wav[i]-1; mi++){
2040: for (ii=1;ii<=nlstate+ndeath;ii++)
2041: for (j=1;j<=nlstate+ndeath;j++){
2042: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2043: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2044: }
2045: for(d=0; d<dh[mi][i]; d++){
2046: newm=savm;
2047: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2048: for (kk=1; kk<=cptcovage;kk++) {
2049: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2050: }
2051:
2052: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2053: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2054: savm=oldm;
2055: oldm=newm;
2056: } /* end mult */
2057:
2058: s1=s[mw[mi][i]][i];
2059: s2=s[mw[mi+1][i]][i];
2060: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2061: ipmx +=1;
2062: sw += weight[i];
2063: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2064: /*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]);*/
2065: } /* end of wave */
2066: } /* end of individual */
2067: } /* End of if */
2068: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2069: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2070: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2071: return -l;
2072: }
2073:
2074: /*************** log-likelihood *************/
2075: double funcone( double *x)
2076: {
2077: /* Same as likeli but slower because of a lot of printf and if */
2078: int i, ii, j, k, mi, d, kk;
1.131 brouard 2079: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2080: double **out;
2081: double lli; /* Individual log likelihood */
2082: double llt;
2083: int s1, s2;
2084: double bbh, survp;
2085: /*extern weight */
2086: /* We are differentiating ll according to initial status */
2087: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2088: /*for(i=1;i<imx;i++)
2089: printf(" %d\n",s[4][i]);
2090: */
2091: cov[1]=1.;
2092:
2093: for(k=1; k<=nlstate; k++) ll[k]=0.;
2094:
2095: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2096: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2097: for(mi=1; mi<= wav[i]-1; mi++){
2098: for (ii=1;ii<=nlstate+ndeath;ii++)
2099: for (j=1;j<=nlstate+ndeath;j++){
2100: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2101: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2102: }
2103: for(d=0; d<dh[mi][i]; d++){
2104: newm=savm;
2105: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2106: for (kk=1; kk<=cptcovage;kk++) {
2107: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2108: }
1.145 brouard 2109: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2110: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2111: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2112: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2113: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2114: savm=oldm;
2115: oldm=newm;
2116: } /* end mult */
2117:
2118: s1=s[mw[mi][i]][i];
2119: s2=s[mw[mi+1][i]][i];
2120: bbh=(double)bh[mi][i]/(double)stepm;
2121: /* bias is positive if real duration
2122: * is higher than the multiple of stepm and negative otherwise.
2123: */
2124: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2125: lli=log(out[s1][s2] - savm[s1][s2]);
2126: } else if (s2==-2) {
2127: for (j=1,survp=0. ; j<=nlstate; j++)
2128: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2129: lli= log(survp);
2130: }else if (mle==1){
2131: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2132: } else if(mle==2){
2133: 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 */
2134: } else if(mle==3){ /* exponential inter-extrapolation */
2135: 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 */
2136: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2137: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2138: } else{ /* mle=0 back to 1 */
2139: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2140: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2141: } /* End of if */
2142: ipmx +=1;
2143: sw += weight[i];
2144: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2145: /*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 2146: if(globpr){
1.141 brouard 2147: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2148: %11.6f %11.6f %11.6f ", \
2149: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2150: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2151: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2152: llt +=ll[k]*gipmx/gsw;
2153: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2154: }
2155: fprintf(ficresilk," %10.6f\n", -llt);
2156: }
2157: } /* end of wave */
2158: } /* end of individual */
2159: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2160: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2161: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2162: if(globpr==0){ /* First time we count the contributions and weights */
2163: gipmx=ipmx;
2164: gsw=sw;
2165: }
2166: return -l;
2167: }
2168:
2169:
2170: /*************** function likelione ***********/
2171: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2172: {
2173: /* This routine should help understanding what is done with
2174: the selection of individuals/waves and
2175: to check the exact contribution to the likelihood.
2176: Plotting could be done.
2177: */
2178: int k;
2179:
2180: if(*globpri !=0){ /* Just counts and sums, no printings */
2181: strcpy(fileresilk,"ilk");
2182: strcat(fileresilk,fileres);
2183: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2184: printf("Problem with resultfile: %s\n", fileresilk);
2185: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2186: }
2187: 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");
2188: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2189: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2190: for(k=1; k<=nlstate; k++)
2191: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2192: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2193: }
2194:
2195: *fretone=(*funcone)(p);
2196: if(*globpri !=0){
2197: fclose(ficresilk);
2198: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2199: fflush(fichtm);
2200: }
2201: return;
2202: }
2203:
2204:
2205: /*********** Maximum Likelihood Estimation ***************/
2206:
2207: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2208: {
1.165 brouard 2209: int i,j, iter=0;
1.126 brouard 2210: double **xi;
2211: double fret;
2212: double fretone; /* Only one call to likelihood */
2213: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2214:
2215: #ifdef NLOPT
2216: int creturn;
2217: nlopt_opt opt;
2218: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2219: double *lb;
2220: double minf; /* the minimum objective value, upon return */
2221: double * p1; /* Shifted parameters from 0 instead of 1 */
2222: myfunc_data dinst, *d = &dinst;
2223: #endif
2224:
2225:
1.126 brouard 2226: xi=matrix(1,npar,1,npar);
2227: for (i=1;i<=npar;i++)
2228: for (j=1;j<=npar;j++)
2229: xi[i][j]=(i==j ? 1.0 : 0.0);
2230: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2231: strcpy(filerespow,"pow");
2232: strcat(filerespow,fileres);
2233: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2234: printf("Problem with resultfile: %s\n", filerespow);
2235: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2236: }
2237: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2238: for (i=1;i<=nlstate;i++)
2239: for(j=1;j<=nlstate+ndeath;j++)
2240: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2241: fprintf(ficrespow,"\n");
1.162 brouard 2242: #ifdef POWELL
1.126 brouard 2243: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2244: #endif
1.126 brouard 2245:
1.162 brouard 2246: #ifdef NLOPT
2247: #ifdef NEWUOA
2248: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2249: #else
2250: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2251: #endif
2252: lb=vector(0,npar-1);
2253: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2254: nlopt_set_lower_bounds(opt, lb);
2255: nlopt_set_initial_step1(opt, 0.1);
2256:
2257: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2258: d->function = func;
2259: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2260: nlopt_set_min_objective(opt, myfunc, d);
2261: nlopt_set_xtol_rel(opt, ftol);
2262: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2263: printf("nlopt failed! %d\n",creturn);
2264: }
2265: else {
2266: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2267: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2268: iter=1; /* not equal */
2269: }
2270: nlopt_destroy(opt);
2271: #endif
1.126 brouard 2272: free_matrix(xi,1,npar,1,npar);
2273: fclose(ficrespow);
1.162 brouard 2274: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2275: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2276: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2277:
2278: }
2279:
2280: /**** Computes Hessian and covariance matrix ***/
2281: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2282: {
2283: double **a,**y,*x,pd;
2284: double **hess;
1.164 brouard 2285: int i, j;
1.126 brouard 2286: int *indx;
2287:
2288: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2289: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2290: void lubksb(double **a, int npar, int *indx, double b[]) ;
2291: void ludcmp(double **a, int npar, int *indx, double *d) ;
2292: double gompertz(double p[]);
2293: hess=matrix(1,npar,1,npar);
2294:
2295: printf("\nCalculation of the hessian matrix. Wait...\n");
2296: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2297: for (i=1;i<=npar;i++){
2298: printf("%d",i);fflush(stdout);
2299: fprintf(ficlog,"%d",i);fflush(ficlog);
2300:
2301: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2302:
2303: /* printf(" %f ",p[i]);
2304: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2305: }
2306:
2307: for (i=1;i<=npar;i++) {
2308: for (j=1;j<=npar;j++) {
2309: if (j>i) {
2310: printf(".%d%d",i,j);fflush(stdout);
2311: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2312: hess[i][j]=hessij(p,delti,i,j,func,npar);
2313:
2314: hess[j][i]=hess[i][j];
2315: /*printf(" %lf ",hess[i][j]);*/
2316: }
2317: }
2318: }
2319: printf("\n");
2320: fprintf(ficlog,"\n");
2321:
2322: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2323: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2324:
2325: a=matrix(1,npar,1,npar);
2326: y=matrix(1,npar,1,npar);
2327: x=vector(1,npar);
2328: indx=ivector(1,npar);
2329: for (i=1;i<=npar;i++)
2330: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2331: ludcmp(a,npar,indx,&pd);
2332:
2333: for (j=1;j<=npar;j++) {
2334: for (i=1;i<=npar;i++) x[i]=0;
2335: x[j]=1;
2336: lubksb(a,npar,indx,x);
2337: for (i=1;i<=npar;i++){
2338: matcov[i][j]=x[i];
2339: }
2340: }
2341:
2342: printf("\n#Hessian matrix#\n");
2343: fprintf(ficlog,"\n#Hessian matrix#\n");
2344: for (i=1;i<=npar;i++) {
2345: for (j=1;j<=npar;j++) {
2346: printf("%.3e ",hess[i][j]);
2347: fprintf(ficlog,"%.3e ",hess[i][j]);
2348: }
2349: printf("\n");
2350: fprintf(ficlog,"\n");
2351: }
2352:
2353: /* Recompute Inverse */
2354: for (i=1;i<=npar;i++)
2355: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2356: ludcmp(a,npar,indx,&pd);
2357:
2358: /* printf("\n#Hessian matrix recomputed#\n");
2359:
2360: for (j=1;j<=npar;j++) {
2361: for (i=1;i<=npar;i++) x[i]=0;
2362: x[j]=1;
2363: lubksb(a,npar,indx,x);
2364: for (i=1;i<=npar;i++){
2365: y[i][j]=x[i];
2366: printf("%.3e ",y[i][j]);
2367: fprintf(ficlog,"%.3e ",y[i][j]);
2368: }
2369: printf("\n");
2370: fprintf(ficlog,"\n");
2371: }
2372: */
2373:
2374: free_matrix(a,1,npar,1,npar);
2375: free_matrix(y,1,npar,1,npar);
2376: free_vector(x,1,npar);
2377: free_ivector(indx,1,npar);
2378: free_matrix(hess,1,npar,1,npar);
2379:
2380:
2381: }
2382:
2383: /*************** hessian matrix ****************/
2384: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2385: {
2386: int i;
2387: int l=1, lmax=20;
2388: double k1,k2;
1.132 brouard 2389: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2390: double res;
2391: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2392: double fx;
2393: int k=0,kmax=10;
2394: double l1;
2395:
2396: fx=func(x);
2397: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2398: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2399: l1=pow(10,l);
2400: delts=delt;
2401: for(k=1 ; k <kmax; k=k+1){
2402: delt = delta*(l1*k);
2403: p2[theta]=x[theta] +delt;
1.145 brouard 2404: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2405: p2[theta]=x[theta]-delt;
2406: k2=func(p2)-fx;
2407: /*res= (k1-2.0*fx+k2)/delt/delt; */
2408: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2409:
1.132 brouard 2410: #ifdef DEBUGHESS
1.126 brouard 2411: 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);
2412: 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);
2413: #endif
2414: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2415: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2416: k=kmax;
2417: }
2418: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2419: k=kmax; l=lmax*10;
1.126 brouard 2420: }
2421: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2422: delts=delt;
2423: }
2424: }
2425: }
2426: delti[theta]=delts;
2427: return res;
2428:
2429: }
2430:
2431: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2432: {
2433: int i;
1.164 brouard 2434: int l=1, lmax=20;
1.126 brouard 2435: double k1,k2,k3,k4,res,fx;
1.132 brouard 2436: double p2[MAXPARM+1];
1.126 brouard 2437: int k;
2438:
2439: fx=func(x);
2440: for (k=1; k<=2; k++) {
2441: for (i=1;i<=npar;i++) p2[i]=x[i];
2442: p2[thetai]=x[thetai]+delti[thetai]/k;
2443: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2444: k1=func(p2)-fx;
2445:
2446: p2[thetai]=x[thetai]+delti[thetai]/k;
2447: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2448: k2=func(p2)-fx;
2449:
2450: p2[thetai]=x[thetai]-delti[thetai]/k;
2451: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2452: k3=func(p2)-fx;
2453:
2454: p2[thetai]=x[thetai]-delti[thetai]/k;
2455: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2456: k4=func(p2)-fx;
2457: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2458: #ifdef DEBUG
2459: 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);
2460: 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);
2461: #endif
2462: }
2463: return res;
2464: }
2465:
2466: /************** Inverse of matrix **************/
2467: void ludcmp(double **a, int n, int *indx, double *d)
2468: {
2469: int i,imax,j,k;
2470: double big,dum,sum,temp;
2471: double *vv;
2472:
2473: vv=vector(1,n);
2474: *d=1.0;
2475: for (i=1;i<=n;i++) {
2476: big=0.0;
2477: for (j=1;j<=n;j++)
2478: if ((temp=fabs(a[i][j])) > big) big=temp;
2479: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2480: vv[i]=1.0/big;
2481: }
2482: for (j=1;j<=n;j++) {
2483: for (i=1;i<j;i++) {
2484: sum=a[i][j];
2485: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2486: a[i][j]=sum;
2487: }
2488: big=0.0;
2489: for (i=j;i<=n;i++) {
2490: sum=a[i][j];
2491: for (k=1;k<j;k++)
2492: sum -= a[i][k]*a[k][j];
2493: a[i][j]=sum;
2494: if ( (dum=vv[i]*fabs(sum)) >= big) {
2495: big=dum;
2496: imax=i;
2497: }
2498: }
2499: if (j != imax) {
2500: for (k=1;k<=n;k++) {
2501: dum=a[imax][k];
2502: a[imax][k]=a[j][k];
2503: a[j][k]=dum;
2504: }
2505: *d = -(*d);
2506: vv[imax]=vv[j];
2507: }
2508: indx[j]=imax;
2509: if (a[j][j] == 0.0) a[j][j]=TINY;
2510: if (j != n) {
2511: dum=1.0/(a[j][j]);
2512: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2513: }
2514: }
2515: free_vector(vv,1,n); /* Doesn't work */
2516: ;
2517: }
2518:
2519: void lubksb(double **a, int n, int *indx, double b[])
2520: {
2521: int i,ii=0,ip,j;
2522: double sum;
2523:
2524: for (i=1;i<=n;i++) {
2525: ip=indx[i];
2526: sum=b[ip];
2527: b[ip]=b[i];
2528: if (ii)
2529: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2530: else if (sum) ii=i;
2531: b[i]=sum;
2532: }
2533: for (i=n;i>=1;i--) {
2534: sum=b[i];
2535: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2536: b[i]=sum/a[i][i];
2537: }
2538: }
2539:
2540: void pstamp(FILE *fichier)
2541: {
2542: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2543: }
2544:
2545: /************ Frequencies ********************/
2546: 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[])
2547: { /* Some frequencies */
2548:
1.164 brouard 2549: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2550: int first;
2551: double ***freq; /* Frequencies */
2552: double *pp, **prop;
2553: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2554: char fileresp[FILENAMELENGTH];
2555:
2556: pp=vector(1,nlstate);
2557: prop=matrix(1,nlstate,iagemin,iagemax+3);
2558: strcpy(fileresp,"p");
2559: strcat(fileresp,fileres);
2560: if((ficresp=fopen(fileresp,"w"))==NULL) {
2561: printf("Problem with prevalence resultfile: %s\n", fileresp);
2562: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2563: exit(0);
2564: }
2565: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2566: j1=0;
2567:
2568: j=cptcoveff;
2569: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2570:
2571: first=1;
2572:
1.169 brouard 2573: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2574: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2575: /* j1++; */
1.145 brouard 2576: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2577: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2578: scanf("%d", i);*/
2579: for (i=-5; i<=nlstate+ndeath; i++)
2580: for (jk=-5; jk<=nlstate+ndeath; jk++)
2581: for(m=iagemin; m <= iagemax+3; m++)
2582: freq[i][jk][m]=0;
1.143 brouard 2583:
2584: for (i=1; i<=nlstate; i++)
2585: for(m=iagemin; m <= iagemax+3; m++)
2586: prop[i][m]=0;
1.126 brouard 2587:
2588: dateintsum=0;
2589: k2cpt=0;
2590: for (i=1; i<=imx; i++) {
2591: bool=1;
1.144 brouard 2592: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2593: for (z1=1; z1<=cptcoveff; z1++)
2594: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2595: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2596: bool=0;
1.145 brouard 2597: /* 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",
2598: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2599: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2600: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2601: }
1.126 brouard 2602: }
1.144 brouard 2603:
1.126 brouard 2604: if (bool==1){
2605: for(m=firstpass; m<=lastpass; m++){
2606: k2=anint[m][i]+(mint[m][i]/12.);
2607: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2608: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2609: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2610: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2611: if (m<lastpass) {
2612: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2613: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2614: }
2615:
2616: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2617: dateintsum=dateintsum+k2;
2618: k2cpt++;
2619: }
2620: /*}*/
2621: }
2622: }
1.145 brouard 2623: } /* end i */
1.126 brouard 2624:
2625: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2626: pstamp(ficresp);
2627: if (cptcovn>0) {
2628: fprintf(ficresp, "\n#********** Variable ");
2629: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2630: fprintf(ficresp, "**********\n#");
1.143 brouard 2631: fprintf(ficlog, "\n#********** Variable ");
2632: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2633: fprintf(ficlog, "**********\n#");
1.126 brouard 2634: }
2635: for(i=1; i<=nlstate;i++)
2636: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2637: fprintf(ficresp, "\n");
2638:
2639: for(i=iagemin; i <= iagemax+3; i++){
2640: if(i==iagemax+3){
2641: fprintf(ficlog,"Total");
2642: }else{
2643: if(first==1){
2644: first=0;
2645: printf("See log file for details...\n");
2646: }
2647: fprintf(ficlog,"Age %d", i);
2648: }
2649: for(jk=1; jk <=nlstate ; jk++){
2650: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2651: pp[jk] += freq[jk][m][i];
2652: }
2653: for(jk=1; jk <=nlstate ; jk++){
2654: for(m=-1, pos=0; m <=0 ; m++)
2655: pos += freq[jk][m][i];
2656: if(pp[jk]>=1.e-10){
2657: if(first==1){
1.132 brouard 2658: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2659: }
2660: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2661: }else{
2662: if(first==1)
2663: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2664: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2665: }
2666: }
2667:
2668: for(jk=1; jk <=nlstate ; jk++){
2669: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2670: pp[jk] += freq[jk][m][i];
2671: }
2672: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2673: pos += pp[jk];
2674: posprop += prop[jk][i];
2675: }
2676: for(jk=1; jk <=nlstate ; jk++){
2677: if(pos>=1.e-5){
2678: if(first==1)
2679: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2680: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2681: }else{
2682: if(first==1)
2683: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2684: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2685: }
2686: if( i <= iagemax){
2687: if(pos>=1.e-5){
2688: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2689: /*probs[i][jk][j1]= pp[jk]/pos;*/
2690: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2691: }
2692: else
2693: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2694: }
2695: }
2696:
2697: for(jk=-1; jk <=nlstate+ndeath; jk++)
2698: for(m=-1; m <=nlstate+ndeath; m++)
2699: if(freq[jk][m][i] !=0 ) {
2700: if(first==1)
2701: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2702: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2703: }
2704: if(i <= iagemax)
2705: fprintf(ficresp,"\n");
2706: if(first==1)
2707: printf("Others in log...\n");
2708: fprintf(ficlog,"\n");
2709: }
1.145 brouard 2710: /*}*/
1.126 brouard 2711: }
2712: dateintmean=dateintsum/k2cpt;
2713:
2714: fclose(ficresp);
2715: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2716: free_vector(pp,1,nlstate);
2717: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2718: /* End of Freq */
2719: }
2720:
2721: /************ Prevalence ********************/
2722: 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)
2723: {
2724: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2725: in each health status at the date of interview (if between dateprev1 and dateprev2).
2726: We still use firstpass and lastpass as another selection.
2727: */
2728:
1.164 brouard 2729: int i, m, jk, j1, bool, z1,j;
2730:
2731: double **prop;
2732: double posprop;
1.126 brouard 2733: double y2; /* in fractional years */
2734: int iagemin, iagemax;
1.145 brouard 2735: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2736:
2737: iagemin= (int) agemin;
2738: iagemax= (int) agemax;
2739: /*pp=vector(1,nlstate);*/
2740: prop=matrix(1,nlstate,iagemin,iagemax+3);
2741: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2742: j1=0;
2743:
1.145 brouard 2744: /*j=cptcoveff;*/
1.126 brouard 2745: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2746:
1.145 brouard 2747: first=1;
2748: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2749: /*for(i1=1; i1<=ncodemax[k1];i1++){
2750: j1++;*/
1.126 brouard 2751:
2752: for (i=1; i<=nlstate; i++)
2753: for(m=iagemin; m <= iagemax+3; m++)
2754: prop[i][m]=0.0;
2755:
2756: for (i=1; i<=imx; i++) { /* Each individual */
2757: bool=1;
2758: if (cptcovn>0) {
2759: for (z1=1; z1<=cptcoveff; z1++)
2760: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2761: bool=0;
2762: }
2763: if (bool==1) {
2764: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2765: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2766: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2767: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2768: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2769: 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);
2770: if (s[m][i]>0 && s[m][i]<=nlstate) {
2771: /*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]]);*/
2772: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2773: prop[s[m][i]][iagemax+3] += weight[i];
2774: }
2775: }
2776: } /* end selection of waves */
2777: }
2778: }
2779: for(i=iagemin; i <= iagemax+3; i++){
2780: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2781: posprop += prop[jk][i];
2782: }
1.145 brouard 2783:
1.126 brouard 2784: for(jk=1; jk <=nlstate ; jk++){
2785: if( i <= iagemax){
2786: if(posprop>=1.e-5){
2787: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2788: } else{
2789: if(first==1){
2790: first=0;
2791: 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]);
2792: }
2793: }
1.126 brouard 2794: }
2795: }/* end jk */
2796: }/* end i */
1.145 brouard 2797: /*} *//* end i1 */
2798: } /* end j1 */
1.126 brouard 2799:
2800: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2801: /*free_vector(pp,1,nlstate);*/
2802: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2803: } /* End of prevalence */
2804:
2805: /************* Waves Concatenation ***************/
2806:
2807: 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)
2808: {
2809: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2810: Death is a valid wave (if date is known).
2811: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2812: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2813: and mw[mi+1][i]. dh depends on stepm.
2814: */
2815:
2816: int i, mi, m;
2817: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2818: double sum=0., jmean=0.;*/
2819: int first;
2820: int j, k=0,jk, ju, jl;
2821: double sum=0.;
2822: first=0;
1.164 brouard 2823: jmin=100000;
1.126 brouard 2824: jmax=-1;
2825: jmean=0.;
2826: for(i=1; i<=imx; i++){
2827: mi=0;
2828: m=firstpass;
2829: while(s[m][i] <= nlstate){
2830: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2831: mw[++mi][i]=m;
2832: if(m >=lastpass)
2833: break;
2834: else
2835: m++;
2836: }/* end while */
2837: if (s[m][i] > nlstate){
2838: mi++; /* Death is another wave */
2839: /* if(mi==0) never been interviewed correctly before death */
2840: /* Only death is a correct wave */
2841: mw[mi][i]=m;
2842: }
2843:
2844: wav[i]=mi;
2845: if(mi==0){
2846: nbwarn++;
2847: if(first==0){
2848: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2849: first=1;
2850: }
2851: if(first==1){
2852: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2853: }
2854: } /* end mi==0 */
2855: } /* End individuals */
2856:
2857: for(i=1; i<=imx; i++){
2858: for(mi=1; mi<wav[i];mi++){
2859: if (stepm <=0)
2860: dh[mi][i]=1;
2861: else{
2862: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2863: if (agedc[i] < 2*AGESUP) {
2864: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2865: if(j==0) j=1; /* Survives at least one month after exam */
2866: else if(j<0){
2867: nberr++;
2868: 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]);
2869: j=1; /* Temporary Dangerous patch */
2870: 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);
2871: 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]);
2872: 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);
2873: }
2874: k=k+1;
2875: if (j >= jmax){
2876: jmax=j;
2877: ijmax=i;
2878: }
2879: if (j <= jmin){
2880: jmin=j;
2881: ijmin=i;
2882: }
2883: sum=sum+j;
2884: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2885: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2886: }
2887: }
2888: else{
2889: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2890: /* 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]); */
2891:
2892: k=k+1;
2893: if (j >= jmax) {
2894: jmax=j;
2895: ijmax=i;
2896: }
2897: else if (j <= jmin){
2898: jmin=j;
2899: ijmin=i;
2900: }
2901: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2902: /*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]);*/
2903: if(j<0){
2904: nberr++;
2905: 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]);
2906: 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]);
2907: }
2908: sum=sum+j;
2909: }
2910: jk= j/stepm;
2911: jl= j -jk*stepm;
2912: ju= j -(jk+1)*stepm;
2913: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2914: if(jl==0){
2915: dh[mi][i]=jk;
2916: bh[mi][i]=0;
2917: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2918: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2919: dh[mi][i]=jk+1;
2920: bh[mi][i]=ju;
2921: }
2922: }else{
2923: if(jl <= -ju){
2924: dh[mi][i]=jk;
2925: bh[mi][i]=jl; /* bias is positive if real duration
2926: * is higher than the multiple of stepm and negative otherwise.
2927: */
2928: }
2929: else{
2930: dh[mi][i]=jk+1;
2931: bh[mi][i]=ju;
2932: }
2933: if(dh[mi][i]==0){
2934: dh[mi][i]=1; /* At least one step */
2935: bh[mi][i]=ju; /* At least one step */
2936: /* 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);*/
2937: }
2938: } /* end if mle */
2939: }
2940: } /* end wave */
2941: }
2942: jmean=sum/k;
2943: 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 2944: 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 2945: }
2946:
2947: /*********** Tricode ****************************/
1.145 brouard 2948: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2949: {
1.144 brouard 2950: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2951: /* 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 2952: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2953: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 2954: * nbcode[Tvar[j]][1]=
1.144 brouard 2955: */
1.130 brouard 2956:
1.145 brouard 2957: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2958: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2959: int cptcode=0; /* Modality max of covariates j */
2960: int modmincovj=0; /* Modality min of covariates j */
2961:
2962:
1.126 brouard 2963: cptcoveff=0;
2964:
1.145 brouard 2965: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2966: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2967:
1.145 brouard 2968: /* Loop on covariates without age and products */
2969: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2970: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2971: modality of this covariate Vj*/
1.145 brouard 2972: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2973: * If product of Vn*Vm, still boolean *:
2974: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2975: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2976: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2977: modality of the nth covariate of individual i. */
1.145 brouard 2978: if (ij > modmaxcovj)
2979: modmaxcovj=ij;
2980: else if (ij < modmincovj)
2981: modmincovj=ij;
2982: if ((ij < -1) && (ij > NCOVMAX)){
2983: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2984: exit(1);
2985: }else
1.136 brouard 2986: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2987: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2988: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2989: /* getting the maximum value of the modality of the covariate
2990: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2991: female is 1, then modmaxcovj=1.*/
1.126 brouard 2992: }
1.145 brouard 2993: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2994: cptcode=modmaxcovj;
1.137 brouard 2995: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2996: /*for (i=0; i<=cptcode; i++) {*/
2997: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2998: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2999: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3000: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3001: }
3002: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3003: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3004: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3005:
1.136 brouard 3006: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 3007: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3008: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3009: modmincovj=3; modmaxcovj = 7;
3010: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3011: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3012: variables V1_1 and V1_2.
3013: nbcode[Tvar[j]][ij]=k;
3014: nbcode[Tvar[j]][1]=0;
3015: nbcode[Tvar[j]][2]=1;
3016: nbcode[Tvar[j]][3]=2;
3017: */
3018: ij=1; /* ij is similar to i but can jumps over null modalities */
3019: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3020: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3021: /*recode from 0 */
1.131 brouard 3022: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3023: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3024: k is a modality. If we have model=V1+V1*sex
3025: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3026: ij++;
3027: }
3028: if (ij > ncodemax[j]) break;
1.137 brouard 3029: } /* end of loop on */
3030: } /* end of loop on modality */
3031: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3032:
1.145 brouard 3033: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3034:
1.145 brouard 3035: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3036: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3037: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3038: Ndum[ij]++;
3039: }
1.126 brouard 3040:
3041: ij=1;
1.145 brouard 3042: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3043: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3044: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3045: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3046: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3047: ij++;
1.145 brouard 3048: }else
3049: Tvaraff[ij]=0;
1.126 brouard 3050: }
1.131 brouard 3051: ij--;
1.144 brouard 3052: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3053:
1.126 brouard 3054: }
3055:
1.145 brouard 3056:
1.126 brouard 3057: /*********** Health Expectancies ****************/
3058:
1.127 brouard 3059: 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 3060:
3061: {
3062: /* Health expectancies, no variances */
1.164 brouard 3063: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3064: int nhstepma, nstepma; /* Decreasing with age */
3065: double age, agelim, hf;
3066: double ***p3mat;
3067: double eip;
3068:
3069: pstamp(ficreseij);
3070: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3071: fprintf(ficreseij,"# Age");
3072: for(i=1; i<=nlstate;i++){
3073: for(j=1; j<=nlstate;j++){
3074: fprintf(ficreseij," e%1d%1d ",i,j);
3075: }
3076: fprintf(ficreseij," e%1d. ",i);
3077: }
3078: fprintf(ficreseij,"\n");
3079:
3080:
3081: if(estepm < stepm){
3082: printf ("Problem %d lower than %d\n",estepm, stepm);
3083: }
3084: else hstepm=estepm;
3085: /* We compute the life expectancy from trapezoids spaced every estepm months
3086: * This is mainly to measure the difference between two models: for example
3087: * if stepm=24 months pijx are given only every 2 years and by summing them
3088: * we are calculating an estimate of the Life Expectancy assuming a linear
3089: * progression in between and thus overestimating or underestimating according
3090: * to the curvature of the survival function. If, for the same date, we
3091: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3092: * to compare the new estimate of Life expectancy with the same linear
3093: * hypothesis. A more precise result, taking into account a more precise
3094: * curvature will be obtained if estepm is as small as stepm. */
3095:
3096: /* For example we decided to compute the life expectancy with the smallest unit */
3097: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3098: nhstepm is the number of hstepm from age to agelim
3099: nstepm is the number of stepm from age to agelin.
3100: Look at hpijx to understand the reason of that which relies in memory size
3101: and note for a fixed period like estepm months */
3102: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3103: survival function given by stepm (the optimization length). Unfortunately it
3104: means that if the survival funtion is printed only each two years of age and if
3105: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3106: results. So we changed our mind and took the option of the best precision.
3107: */
3108: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3109:
3110: agelim=AGESUP;
3111: /* If stepm=6 months */
3112: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3113: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3114:
3115: /* nhstepm age range expressed in number of stepm */
3116: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3117: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3118: /* if (stepm >= YEARM) hstepm=1;*/
3119: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3120: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3121:
3122: for (age=bage; age<=fage; age ++){
3123: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3124: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3125: /* if (stepm >= YEARM) hstepm=1;*/
3126: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3127:
3128: /* If stepm=6 months */
3129: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3130: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3131:
3132: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3133:
3134: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3135:
3136: printf("%d|",(int)age);fflush(stdout);
3137: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3138:
3139: /* Computing expectancies */
3140: for(i=1; i<=nlstate;i++)
3141: for(j=1; j<=nlstate;j++)
3142: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3143: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3144:
3145: /* 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]);*/
3146:
3147: }
3148:
3149: fprintf(ficreseij,"%3.0f",age );
3150: for(i=1; i<=nlstate;i++){
3151: eip=0;
3152: for(j=1; j<=nlstate;j++){
3153: eip +=eij[i][j][(int)age];
3154: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3155: }
3156: fprintf(ficreseij,"%9.4f", eip );
3157: }
3158: fprintf(ficreseij,"\n");
3159:
3160: }
3161: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3162: printf("\n");
3163: fprintf(ficlog,"\n");
3164:
3165: }
3166:
1.127 brouard 3167: 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 3168:
3169: {
3170: /* Covariances of health expectancies eij and of total life expectancies according
3171: to initial status i, ei. .
3172: */
3173: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3174: int nhstepma, nstepma; /* Decreasing with age */
3175: double age, agelim, hf;
3176: double ***p3matp, ***p3matm, ***varhe;
3177: double **dnewm,**doldm;
3178: double *xp, *xm;
3179: double **gp, **gm;
3180: double ***gradg, ***trgradg;
3181: int theta;
3182:
3183: double eip, vip;
3184:
3185: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3186: xp=vector(1,npar);
3187: xm=vector(1,npar);
3188: dnewm=matrix(1,nlstate*nlstate,1,npar);
3189: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3190:
3191: pstamp(ficresstdeij);
3192: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3193: fprintf(ficresstdeij,"# Age");
3194: for(i=1; i<=nlstate;i++){
3195: for(j=1; j<=nlstate;j++)
3196: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3197: fprintf(ficresstdeij," e%1d. ",i);
3198: }
3199: fprintf(ficresstdeij,"\n");
3200:
3201: pstamp(ficrescveij);
3202: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3203: fprintf(ficrescveij,"# Age");
3204: for(i=1; i<=nlstate;i++)
3205: for(j=1; j<=nlstate;j++){
3206: cptj= (j-1)*nlstate+i;
3207: for(i2=1; i2<=nlstate;i2++)
3208: for(j2=1; j2<=nlstate;j2++){
3209: cptj2= (j2-1)*nlstate+i2;
3210: if(cptj2 <= cptj)
3211: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3212: }
3213: }
3214: fprintf(ficrescveij,"\n");
3215:
3216: if(estepm < stepm){
3217: printf ("Problem %d lower than %d\n",estepm, stepm);
3218: }
3219: else hstepm=estepm;
3220: /* We compute the life expectancy from trapezoids spaced every estepm months
3221: * This is mainly to measure the difference between two models: for example
3222: * if stepm=24 months pijx are given only every 2 years and by summing them
3223: * we are calculating an estimate of the Life Expectancy assuming a linear
3224: * progression in between and thus overestimating or underestimating according
3225: * to the curvature of the survival function. If, for the same date, we
3226: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3227: * to compare the new estimate of Life expectancy with the same linear
3228: * hypothesis. A more precise result, taking into account a more precise
3229: * curvature will be obtained if estepm is as small as stepm. */
3230:
3231: /* For example we decided to compute the life expectancy with the smallest unit */
3232: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3233: nhstepm is the number of hstepm from age to agelim
3234: nstepm is the number of stepm from age to agelin.
3235: Look at hpijx to understand the reason of that which relies in memory size
3236: and note for a fixed period like estepm months */
3237: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3238: survival function given by stepm (the optimization length). Unfortunately it
3239: means that if the survival funtion is printed only each two years of age and if
3240: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3241: results. So we changed our mind and took the option of the best precision.
3242: */
3243: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3244:
3245: /* If stepm=6 months */
3246: /* nhstepm age range expressed in number of stepm */
3247: agelim=AGESUP;
3248: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3249: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3250: /* if (stepm >= YEARM) hstepm=1;*/
3251: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3252:
3253: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3254: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3255: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3256: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3257: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3258: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3259:
3260: for (age=bage; age<=fage; age ++){
3261: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3262: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3263: /* if (stepm >= YEARM) hstepm=1;*/
3264: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3265:
3266: /* If stepm=6 months */
3267: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3268: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3269:
3270: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3271:
3272: /* Computing Variances of health expectancies */
3273: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3274: decrease memory allocation */
3275: for(theta=1; theta <=npar; theta++){
3276: for(i=1; i<=npar; i++){
3277: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3278: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3279: }
3280: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3281: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3282:
3283: for(j=1; j<= nlstate; j++){
3284: for(i=1; i<=nlstate; i++){
3285: for(h=0; h<=nhstepm-1; h++){
3286: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3287: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3288: }
3289: }
3290: }
3291:
3292: for(ij=1; ij<= nlstate*nlstate; ij++)
3293: for(h=0; h<=nhstepm-1; h++){
3294: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3295: }
3296: }/* End theta */
3297:
3298:
3299: for(h=0; h<=nhstepm-1; h++)
3300: for(j=1; j<=nlstate*nlstate;j++)
3301: for(theta=1; theta <=npar; theta++)
3302: trgradg[h][j][theta]=gradg[h][theta][j];
3303:
3304:
3305: for(ij=1;ij<=nlstate*nlstate;ij++)
3306: for(ji=1;ji<=nlstate*nlstate;ji++)
3307: varhe[ij][ji][(int)age] =0.;
3308:
3309: printf("%d|",(int)age);fflush(stdout);
3310: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3311: for(h=0;h<=nhstepm-1;h++){
3312: for(k=0;k<=nhstepm-1;k++){
3313: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3314: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3315: for(ij=1;ij<=nlstate*nlstate;ij++)
3316: for(ji=1;ji<=nlstate*nlstate;ji++)
3317: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3318: }
3319: }
3320:
3321: /* Computing expectancies */
3322: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3323: for(i=1; i<=nlstate;i++)
3324: for(j=1; j<=nlstate;j++)
3325: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3326: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3327:
3328: /* 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]);*/
3329:
3330: }
3331:
3332: fprintf(ficresstdeij,"%3.0f",age );
3333: for(i=1; i<=nlstate;i++){
3334: eip=0.;
3335: vip=0.;
3336: for(j=1; j<=nlstate;j++){
3337: eip += eij[i][j][(int)age];
3338: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3339: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3340: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3341: }
3342: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3343: }
3344: fprintf(ficresstdeij,"\n");
3345:
3346: fprintf(ficrescveij,"%3.0f",age );
3347: for(i=1; i<=nlstate;i++)
3348: for(j=1; j<=nlstate;j++){
3349: cptj= (j-1)*nlstate+i;
3350: for(i2=1; i2<=nlstate;i2++)
3351: for(j2=1; j2<=nlstate;j2++){
3352: cptj2= (j2-1)*nlstate+i2;
3353: if(cptj2 <= cptj)
3354: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3355: }
3356: }
3357: fprintf(ficrescveij,"\n");
3358:
3359: }
3360: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3361: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3362: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3363: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3364: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3365: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3366: printf("\n");
3367: fprintf(ficlog,"\n");
3368:
3369: free_vector(xm,1,npar);
3370: free_vector(xp,1,npar);
3371: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3372: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3373: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3374: }
3375:
3376: /************ Variance ******************/
3377: 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[])
3378: {
3379: /* Variance of health expectancies */
3380: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3381: /* double **newm;*/
1.169 brouard 3382: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3383:
3384: int movingaverage();
1.126 brouard 3385: double **dnewm,**doldm;
3386: double **dnewmp,**doldmp;
3387: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3388: int k;
1.126 brouard 3389: double *xp;
3390: double **gp, **gm; /* for var eij */
3391: double ***gradg, ***trgradg; /*for var eij */
3392: double **gradgp, **trgradgp; /* for var p point j */
3393: double *gpp, *gmp; /* for var p point j */
3394: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3395: double ***p3mat;
3396: double age,agelim, hf;
3397: double ***mobaverage;
3398: int theta;
3399: char digit[4];
3400: char digitp[25];
3401:
3402: char fileresprobmorprev[FILENAMELENGTH];
3403:
3404: if(popbased==1){
3405: if(mobilav!=0)
3406: strcpy(digitp,"-populbased-mobilav-");
3407: else strcpy(digitp,"-populbased-nomobil-");
3408: }
3409: else
3410: strcpy(digitp,"-stablbased-");
3411:
3412: if (mobilav!=0) {
3413: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3414: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3415: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3416: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3417: }
3418: }
3419:
3420: strcpy(fileresprobmorprev,"prmorprev");
3421: sprintf(digit,"%-d",ij);
3422: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3423: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3424: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3425: strcat(fileresprobmorprev,fileres);
3426: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3427: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3428: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3429: }
3430: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3431:
3432: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3433: pstamp(ficresprobmorprev);
3434: 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);
3435: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3436: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3437: fprintf(ficresprobmorprev," p.%-d SE",j);
3438: for(i=1; i<=nlstate;i++)
3439: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3440: }
3441: fprintf(ficresprobmorprev,"\n");
3442: fprintf(ficgp,"\n# Routine varevsij");
3443: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3444: 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");
3445: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3446: /* } */
3447: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3448: pstamp(ficresvij);
3449: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3450: if(popbased==1)
1.128 brouard 3451: 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 3452: else
3453: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3454: fprintf(ficresvij,"# Age");
3455: for(i=1; i<=nlstate;i++)
3456: for(j=1; j<=nlstate;j++)
3457: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3458: fprintf(ficresvij,"\n");
3459:
3460: xp=vector(1,npar);
3461: dnewm=matrix(1,nlstate,1,npar);
3462: doldm=matrix(1,nlstate,1,nlstate);
3463: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3464: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3465:
3466: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3467: gpp=vector(nlstate+1,nlstate+ndeath);
3468: gmp=vector(nlstate+1,nlstate+ndeath);
3469: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3470:
3471: if(estepm < stepm){
3472: printf ("Problem %d lower than %d\n",estepm, stepm);
3473: }
3474: else hstepm=estepm;
3475: /* For example we decided to compute the life expectancy with the smallest unit */
3476: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3477: nhstepm is the number of hstepm from age to agelim
3478: nstepm is the number of stepm from age to agelin.
1.128 brouard 3479: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3480: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3481: survival function given by stepm (the optimization length). Unfortunately it
3482: means that if the survival funtion is printed every two years of age and if
3483: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3484: results. So we changed our mind and took the option of the best precision.
3485: */
3486: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3487: agelim = AGESUP;
3488: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3489: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3490: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3491: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3492: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3493: gp=matrix(0,nhstepm,1,nlstate);
3494: gm=matrix(0,nhstepm,1,nlstate);
3495:
3496:
3497: for(theta=1; theta <=npar; theta++){
3498: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3499: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3500: }
3501: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3502: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3503:
3504: if (popbased==1) {
3505: if(mobilav ==0){
3506: for(i=1; i<=nlstate;i++)
3507: prlim[i][i]=probs[(int)age][i][ij];
3508: }else{ /* mobilav */
3509: for(i=1; i<=nlstate;i++)
3510: prlim[i][i]=mobaverage[(int)age][i][ij];
3511: }
3512: }
3513:
3514: for(j=1; j<= nlstate; j++){
3515: for(h=0; h<=nhstepm; h++){
3516: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3517: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3518: }
3519: }
3520: /* This for computing probability of death (h=1 means
3521: computed over hstepm matrices product = hstepm*stepm months)
3522: as a weighted average of prlim.
3523: */
3524: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3525: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3526: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3527: }
3528: /* end probability of death */
3529:
3530: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3531: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3532: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3533: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3534:
3535: if (popbased==1) {
3536: if(mobilav ==0){
3537: for(i=1; i<=nlstate;i++)
3538: prlim[i][i]=probs[(int)age][i][ij];
3539: }else{ /* mobilav */
3540: for(i=1; i<=nlstate;i++)
3541: prlim[i][i]=mobaverage[(int)age][i][ij];
3542: }
3543: }
3544:
1.128 brouard 3545: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3546: for(h=0; h<=nhstepm; h++){
3547: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3548: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3549: }
3550: }
3551: /* This for computing probability of death (h=1 means
3552: computed over hstepm matrices product = hstepm*stepm months)
3553: as a weighted average of prlim.
3554: */
3555: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3556: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3557: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3558: }
3559: /* end probability of death */
3560:
3561: for(j=1; j<= nlstate; j++) /* vareij */
3562: for(h=0; h<=nhstepm; h++){
3563: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3564: }
3565:
3566: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3567: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3568: }
3569:
3570: } /* End theta */
3571:
3572: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3573:
3574: for(h=0; h<=nhstepm; h++) /* veij */
3575: for(j=1; j<=nlstate;j++)
3576: for(theta=1; theta <=npar; theta++)
3577: trgradg[h][j][theta]=gradg[h][theta][j];
3578:
3579: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3580: for(theta=1; theta <=npar; theta++)
3581: trgradgp[j][theta]=gradgp[theta][j];
3582:
3583:
3584: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3585: for(i=1;i<=nlstate;i++)
3586: for(j=1;j<=nlstate;j++)
3587: vareij[i][j][(int)age] =0.;
3588:
3589: for(h=0;h<=nhstepm;h++){
3590: for(k=0;k<=nhstepm;k++){
3591: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3592: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3593: for(i=1;i<=nlstate;i++)
3594: for(j=1;j<=nlstate;j++)
3595: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3596: }
3597: }
3598:
3599: /* pptj */
3600: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3601: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3602: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3603: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3604: varppt[j][i]=doldmp[j][i];
3605: /* end ppptj */
3606: /* x centered again */
3607: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3608: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3609:
3610: if (popbased==1) {
3611: if(mobilav ==0){
3612: for(i=1; i<=nlstate;i++)
3613: prlim[i][i]=probs[(int)age][i][ij];
3614: }else{ /* mobilav */
3615: for(i=1; i<=nlstate;i++)
3616: prlim[i][i]=mobaverage[(int)age][i][ij];
3617: }
3618: }
3619:
3620: /* This for computing probability of death (h=1 means
3621: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3622: as a weighted average of prlim.
3623: */
3624: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3625: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3626: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3627: }
3628: /* end probability of death */
3629:
3630: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3631: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3632: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3633: for(i=1; i<=nlstate;i++){
3634: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3635: }
3636: }
3637: fprintf(ficresprobmorprev,"\n");
3638:
3639: fprintf(ficresvij,"%.0f ",age );
3640: for(i=1; i<=nlstate;i++)
3641: for(j=1; j<=nlstate;j++){
3642: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3643: }
3644: fprintf(ficresvij,"\n");
3645: free_matrix(gp,0,nhstepm,1,nlstate);
3646: free_matrix(gm,0,nhstepm,1,nlstate);
3647: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3648: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3649: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3650: } /* End age */
3651: free_vector(gpp,nlstate+1,nlstate+ndeath);
3652: free_vector(gmp,nlstate+1,nlstate+ndeath);
3653: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3654: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3655: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3656: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3657: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3658: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3659: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3660: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3661: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3662: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3663: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3664: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3665: 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);
3666: /* 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);
3667: */
3668: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3669: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3670:
3671: free_vector(xp,1,npar);
3672: free_matrix(doldm,1,nlstate,1,nlstate);
3673: free_matrix(dnewm,1,nlstate,1,npar);
3674: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3675: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3676: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3677: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3678: fclose(ficresprobmorprev);
3679: fflush(ficgp);
3680: fflush(fichtm);
3681: } /* end varevsij */
3682:
3683: /************ Variance of prevlim ******************/
3684: 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[])
3685: {
3686: /* Variance of prevalence limit */
3687: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3688:
1.126 brouard 3689: double **dnewm,**doldm;
3690: int i, j, nhstepm, hstepm;
3691: double *xp;
3692: double *gp, *gm;
3693: double **gradg, **trgradg;
3694: double age,agelim;
3695: int theta;
3696:
3697: pstamp(ficresvpl);
3698: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3699: fprintf(ficresvpl,"# Age");
3700: for(i=1; i<=nlstate;i++)
3701: fprintf(ficresvpl," %1d-%1d",i,i);
3702: fprintf(ficresvpl,"\n");
3703:
3704: xp=vector(1,npar);
3705: dnewm=matrix(1,nlstate,1,npar);
3706: doldm=matrix(1,nlstate,1,nlstate);
3707:
3708: hstepm=1*YEARM; /* Every year of age */
3709: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3710: agelim = AGESUP;
3711: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3712: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3713: if (stepm >= YEARM) hstepm=1;
3714: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3715: gradg=matrix(1,npar,1,nlstate);
3716: gp=vector(1,nlstate);
3717: gm=vector(1,nlstate);
3718:
3719: for(theta=1; theta <=npar; theta++){
3720: for(i=1; i<=npar; i++){ /* Computes gradient */
3721: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3722: }
3723: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3724: for(i=1;i<=nlstate;i++)
3725: gp[i] = prlim[i][i];
3726:
3727: for(i=1; i<=npar; i++) /* Computes gradient */
3728: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3729: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3730: for(i=1;i<=nlstate;i++)
3731: gm[i] = prlim[i][i];
3732:
3733: for(i=1;i<=nlstate;i++)
3734: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3735: } /* End theta */
3736:
3737: trgradg =matrix(1,nlstate,1,npar);
3738:
3739: for(j=1; j<=nlstate;j++)
3740: for(theta=1; theta <=npar; theta++)
3741: trgradg[j][theta]=gradg[theta][j];
3742:
3743: for(i=1;i<=nlstate;i++)
3744: varpl[i][(int)age] =0.;
3745: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3746: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3747: for(i=1;i<=nlstate;i++)
3748: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3749:
3750: fprintf(ficresvpl,"%.0f ",age );
3751: for(i=1; i<=nlstate;i++)
3752: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3753: fprintf(ficresvpl,"\n");
3754: free_vector(gp,1,nlstate);
3755: free_vector(gm,1,nlstate);
3756: free_matrix(gradg,1,npar,1,nlstate);
3757: free_matrix(trgradg,1,nlstate,1,npar);
3758: } /* End age */
3759:
3760: free_vector(xp,1,npar);
3761: free_matrix(doldm,1,nlstate,1,npar);
3762: free_matrix(dnewm,1,nlstate,1,nlstate);
3763:
3764: }
3765:
3766: /************ Variance of one-step probabilities ******************/
3767: 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[])
3768: {
1.164 brouard 3769: int i, j=0, k1, l1, tj;
1.126 brouard 3770: int k2, l2, j1, z1;
1.164 brouard 3771: int k=0, l;
1.145 brouard 3772: int first=1, first1, first2;
1.126 brouard 3773: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3774: double **dnewm,**doldm;
3775: double *xp;
3776: double *gp, *gm;
3777: double **gradg, **trgradg;
3778: double **mu;
1.164 brouard 3779: double age, cov[NCOVMAX+1];
1.126 brouard 3780: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3781: int theta;
3782: char fileresprob[FILENAMELENGTH];
3783: char fileresprobcov[FILENAMELENGTH];
3784: char fileresprobcor[FILENAMELENGTH];
3785: double ***varpij;
3786:
3787: strcpy(fileresprob,"prob");
3788: strcat(fileresprob,fileres);
3789: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3790: printf("Problem with resultfile: %s\n", fileresprob);
3791: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3792: }
3793: strcpy(fileresprobcov,"probcov");
3794: strcat(fileresprobcov,fileres);
3795: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3796: printf("Problem with resultfile: %s\n", fileresprobcov);
3797: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3798: }
3799: strcpy(fileresprobcor,"probcor");
3800: strcat(fileresprobcor,fileres);
3801: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3802: printf("Problem with resultfile: %s\n", fileresprobcor);
3803: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3804: }
3805: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3806: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3807: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3808: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3809: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3810: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3811: pstamp(ficresprob);
3812: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3813: fprintf(ficresprob,"# Age");
3814: pstamp(ficresprobcov);
3815: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3816: fprintf(ficresprobcov,"# Age");
3817: pstamp(ficresprobcor);
3818: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3819: fprintf(ficresprobcor,"# Age");
3820:
3821:
3822: for(i=1; i<=nlstate;i++)
3823: for(j=1; j<=(nlstate+ndeath);j++){
3824: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3825: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3826: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3827: }
3828: /* fprintf(ficresprob,"\n");
3829: fprintf(ficresprobcov,"\n");
3830: fprintf(ficresprobcor,"\n");
3831: */
1.131 brouard 3832: xp=vector(1,npar);
1.126 brouard 3833: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3834: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3835: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3836: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3837: first=1;
3838: fprintf(ficgp,"\n# Routine varprob");
3839: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3840: fprintf(fichtm,"\n");
3841:
3842: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3843: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3844: file %s<br>\n",optionfilehtmcov);
3845: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3846: and drawn. It helps understanding how is the covariance between two incidences.\
3847: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3848: 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. \
3849: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3850: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3851: standard deviations wide on each axis. <br>\
3852: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3853: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3854: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3855:
3856: cov[1]=1;
1.145 brouard 3857: /* tj=cptcoveff; */
3858: tj = (int) pow(2,cptcoveff);
1.126 brouard 3859: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3860: j1=0;
1.145 brouard 3861: for(j1=1; j1<=tj;j1++){
3862: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3863: /*j1++;*/
1.126 brouard 3864: if (cptcovn>0) {
3865: fprintf(ficresprob, "\n#********** Variable ");
3866: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3867: fprintf(ficresprob, "**********\n#\n");
3868: fprintf(ficresprobcov, "\n#********** Variable ");
3869: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3870: fprintf(ficresprobcov, "**********\n#\n");
3871:
3872: fprintf(ficgp, "\n#********** Variable ");
3873: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3874: fprintf(ficgp, "**********\n#\n");
3875:
3876:
3877: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3878: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3879: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3880:
3881: fprintf(ficresprobcor, "\n#********** Variable ");
3882: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3883: fprintf(ficresprobcor, "**********\n#");
3884: }
3885:
1.145 brouard 3886: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3887: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3888: gp=vector(1,(nlstate)*(nlstate+ndeath));
3889: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3890: for (age=bage; age<=fage; age ++){
3891: cov[2]=age;
3892: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3893: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3894: * 1 1 1 1 1
3895: * 2 2 1 1 1
3896: * 3 1 2 1 1
3897: */
3898: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3899: }
3900: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3901: for (k=1; k<=cptcovprod;k++)
3902: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3903:
3904:
3905: for(theta=1; theta <=npar; theta++){
3906: for(i=1; i<=npar; i++)
3907: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3908:
3909: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3910:
3911: k=0;
3912: for(i=1; i<= (nlstate); i++){
3913: for(j=1; j<=(nlstate+ndeath);j++){
3914: k=k+1;
3915: gp[k]=pmmij[i][j];
3916: }
3917: }
3918:
3919: for(i=1; i<=npar; i++)
3920: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3921:
3922: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3923: k=0;
3924: for(i=1; i<=(nlstate); i++){
3925: for(j=1; j<=(nlstate+ndeath);j++){
3926: k=k+1;
3927: gm[k]=pmmij[i][j];
3928: }
3929: }
3930:
3931: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3932: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3933: }
3934:
3935: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3936: for(theta=1; theta <=npar; theta++)
3937: trgradg[j][theta]=gradg[theta][j];
3938:
3939: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3940: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3941:
3942: pmij(pmmij,cov,ncovmodel,x,nlstate);
3943:
3944: k=0;
3945: for(i=1; i<=(nlstate); i++){
3946: for(j=1; j<=(nlstate+ndeath);j++){
3947: k=k+1;
3948: mu[k][(int) age]=pmmij[i][j];
3949: }
3950: }
3951: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3952: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3953: varpij[i][j][(int)age] = doldm[i][j];
3954:
3955: /*printf("\n%d ",(int)age);
3956: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3957: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3958: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3959: }*/
3960:
3961: fprintf(ficresprob,"\n%d ",(int)age);
3962: fprintf(ficresprobcov,"\n%d ",(int)age);
3963: fprintf(ficresprobcor,"\n%d ",(int)age);
3964:
3965: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3966: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3967: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3968: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3969: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3970: }
3971: i=0;
3972: for (k=1; k<=(nlstate);k++){
3973: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3974: i++;
1.126 brouard 3975: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3976: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3977: for (j=1; j<=i;j++){
1.145 brouard 3978: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3979: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3980: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3981: }
3982: }
3983: }/* end of loop for state */
3984: } /* end of loop for age */
1.145 brouard 3985: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3986: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3987: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3988: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3989:
1.126 brouard 3990: /* Confidence intervalle of pij */
3991: /*
1.131 brouard 3992: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3993: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3994: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3995: 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);
3996: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3997: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3998: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3999: */
4000:
4001: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4002: first1=1;first2=2;
1.126 brouard 4003: for (k2=1; k2<=(nlstate);k2++){
4004: for (l2=1; l2<=(nlstate+ndeath);l2++){
4005: if(l2==k2) continue;
4006: j=(k2-1)*(nlstate+ndeath)+l2;
4007: for (k1=1; k1<=(nlstate);k1++){
4008: for (l1=1; l1<=(nlstate+ndeath);l1++){
4009: if(l1==k1) continue;
4010: i=(k1-1)*(nlstate+ndeath)+l1;
4011: if(i<=j) continue;
4012: for (age=bage; age<=fage; age ++){
4013: if ((int)age %5==0){
4014: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4015: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4016: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4017: mu1=mu[i][(int) age]/stepm*YEARM ;
4018: mu2=mu[j][(int) age]/stepm*YEARM;
4019: c12=cv12/sqrt(v1*v2);
4020: /* Computing eigen value of matrix of covariance */
4021: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4022: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4023: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4024: if(first2==1){
4025: first1=0;
4026: 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);
4027: }
4028: 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);
4029: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4030: /* lc2=fabs(lc2); */
1.135 brouard 4031: }
4032:
1.126 brouard 4033: /* Eigen vectors */
4034: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4035: /*v21=sqrt(1.-v11*v11); *//* error */
4036: v21=(lc1-v1)/cv12*v11;
4037: v12=-v21;
4038: v22=v11;
4039: tnalp=v21/v11;
4040: if(first1==1){
4041: first1=0;
4042: 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);
4043: }
4044: 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);
4045: /*printf(fignu*/
4046: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4047: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4048: if(first==1){
4049: first=0;
4050: fprintf(ficgp,"\nset parametric;unset label");
4051: 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 4052: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4053: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4054: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4055: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4056: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4057: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4058: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4059: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4060: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4061: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4062: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4063: 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",\
4064: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4065: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4066: }else{
4067: first=0;
4068: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4069: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4070: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4071: 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",\
4072: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4073: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4074: }/* if first */
4075: } /* age mod 5 */
4076: } /* end loop age */
4077: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4078: first=1;
4079: } /*l12 */
4080: } /* k12 */
4081: } /*l1 */
4082: }/* k1 */
1.169 brouard 4083: /* } */ /* loop covariates */
1.126 brouard 4084: }
4085: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4086: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4087: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4088: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4089: free_vector(xp,1,npar);
4090: fclose(ficresprob);
4091: fclose(ficresprobcov);
4092: fclose(ficresprobcor);
4093: fflush(ficgp);
4094: fflush(fichtmcov);
4095: }
4096:
4097:
4098: /******************* Printing html file ***********/
4099: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4100: int lastpass, int stepm, int weightopt, char model[],\
4101: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4102: int popforecast, int estepm ,\
4103: double jprev1, double mprev1,double anprev1, \
4104: double jprev2, double mprev2,double anprev2){
4105: int jj1, k1, i1, cpt;
4106:
4107: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4108: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4109: </ul>");
4110: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4111: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4112: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4113: fprintf(fichtm,"\
4114: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4115: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4116: fprintf(fichtm,"\
4117: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4118: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4119: fprintf(fichtm,"\
1.128 brouard 4120: - (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 4121: <a href=\"%s\">%s</a> <br>\n",
4122: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4123: fprintf(fichtm,"\
4124: - Population projections by age and states: \
4125: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4126:
4127: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4128:
1.145 brouard 4129: m=pow(2,cptcoveff);
1.126 brouard 4130: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4131:
4132: jj1=0;
4133: for(k1=1; k1<=m;k1++){
4134: for(i1=1; i1<=ncodemax[k1];i1++){
4135: jj1++;
4136: if (cptcovn > 0) {
4137: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4138: for (cpt=1; cpt<=cptcoveff;cpt++)
4139: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4140: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4141: }
4142: /* Pij */
1.145 brouard 4143: 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> \
4144: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4145: /* Quasi-incidences */
4146: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4147: 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> \
4148: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4149: /* Period (stable) prevalence in each health state */
1.154 brouard 4150: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4151: 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> \
4152: <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 4153: }
4154: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4155: 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> \
4156: <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 4157: }
4158: } /* end i1 */
4159: }/* End k1 */
4160: fprintf(fichtm,"</ul>");
4161:
4162:
4163: fprintf(fichtm,"\
4164: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4165: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4166:
4167: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4168: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4169: fprintf(fichtm,"\
4170: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4171: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4172:
4173: fprintf(fichtm,"\
4174: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4175: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4176: fprintf(fichtm,"\
4177: - 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): \
4178: <a href=\"%s\">%s</a> <br>\n</li>",
4179: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4180: fprintf(fichtm,"\
4181: - (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): \
4182: <a href=\"%s\">%s</a> <br>\n</li>",
4183: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4184: fprintf(fichtm,"\
1.128 brouard 4185: - 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 4186: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4187: fprintf(fichtm,"\
1.128 brouard 4188: - 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",
4189: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4190: fprintf(fichtm,"\
4191: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4192: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4193:
4194: /* if(popforecast==1) fprintf(fichtm,"\n */
4195: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4196: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4197: /* <br>",fileres,fileres,fileres,fileres); */
4198: /* else */
4199: /* 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); */
4200: fflush(fichtm);
4201: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4202:
1.145 brouard 4203: m=pow(2,cptcoveff);
1.126 brouard 4204: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4205:
4206: jj1=0;
4207: for(k1=1; k1<=m;k1++){
4208: for(i1=1; i1<=ncodemax[k1];i1++){
4209: jj1++;
4210: if (cptcovn > 0) {
4211: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4212: for (cpt=1; cpt<=cptcoveff;cpt++)
4213: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4214: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4215: }
4216: for(cpt=1; cpt<=nlstate;cpt++) {
4217: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4218: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4219: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4220: }
4221: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4222: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4223: true period expectancies (those weighted with period prevalences are also\
4224: drawn in addition to the population based expectancies computed using\
4225: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4226: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4227: } /* end i1 */
4228: }/* End k1 */
4229: fprintf(fichtm,"</ul>");
4230: fflush(fichtm);
4231: }
4232:
4233: /******************* Gnuplot file **************/
4234: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4235:
4236: char dirfileres[132],optfileres[132];
1.164 brouard 4237: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4238: int ng=0;
1.126 brouard 4239: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4240: /* printf("Problem with file %s",optionfilegnuplot); */
4241: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4242: /* } */
4243:
4244: /*#ifdef windows */
4245: fprintf(ficgp,"cd \"%s\" \n",pathc);
4246: /*#endif */
4247: m=pow(2,cptcoveff);
4248:
4249: strcpy(dirfileres,optionfilefiname);
4250: strcpy(optfileres,"vpl");
4251: /* 1eme*/
1.153 brouard 4252: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4253: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4254: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4255: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4256: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4257: fprintf(ficgp,"set xlabel \"Age\" \n\
4258: set ylabel \"Probability\" \n\
1.145 brouard 4259: set ter png small size 320, 240\n\
1.170 brouard 4260: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4261:
4262: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4263: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4264: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4265: }
1.170 brouard 4266: 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 4267: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4268: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4269: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4270: }
1.170 brouard 4271: 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 4272: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4273: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4274: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4275: }
1.145 brouard 4276: 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 4277: }
4278: }
4279: /*2 eme*/
1.153 brouard 4280: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4281: for (k1=1; k1<= m ; k1 ++) {
4282: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4283: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4284:
4285: for (i=1; i<= nlstate+1 ; i ++) {
4286: k=2*i;
1.170 brouard 4287: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4288: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4289: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4290: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4291: }
4292: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4293: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4294: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4295: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4296: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4297: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4298: }
1.145 brouard 4299: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4300: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4301: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4302: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4303: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4304: }
1.145 brouard 4305: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4306: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4307: }
4308: }
4309:
4310: /*3eme*/
4311:
4312: for (k1=1; k1<= m ; k1 ++) {
4313: for (cpt=1; cpt<= nlstate ; cpt ++) {
4314: /* k=2+nlstate*(2*cpt-2); */
4315: k=2+(nlstate+1)*(cpt-1);
4316: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4317: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4318: 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);
4319: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4320: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4321: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4322: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4323: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4324: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4325:
4326: */
4327: for (i=1; i< nlstate ; i ++) {
4328: 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);
4329: /* 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);*/
4330:
4331: }
4332: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4333: }
4334: }
4335:
4336: /* CV preval stable (period) */
1.153 brouard 4337: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4338: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4339: k=3;
1.153 brouard 4340: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4341: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4342: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4343: set ter png small size 320, 240\n\
1.126 brouard 4344: unset log y\n\
1.153 brouard 4345: plot [%.f:%.f] ", ageminpar, agemaxpar);
4346: for (i=1; i<= nlstate ; i ++){
4347: if(i==1)
4348: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4349: else
4350: fprintf(ficgp,", '' ");
1.154 brouard 4351: l=(nlstate+ndeath)*(i-1)+1;
4352: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4353: for (j=1; j<= (nlstate-1) ; j ++)
4354: fprintf(ficgp,"+$%d",k+l+j);
4355: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4356: } /* nlstate */
4357: fprintf(ficgp,"\n");
4358: } /* end cpt state*/
4359: } /* end covariate */
1.126 brouard 4360:
4361: /* proba elementaires */
4362: for(i=1,jk=1; i <=nlstate; i++){
4363: for(k=1; k <=(nlstate+ndeath); k++){
4364: if (k != i) {
4365: for(j=1; j <=ncovmodel; j++){
4366: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4367: jk++;
4368: fprintf(ficgp,"\n");
4369: }
4370: }
4371: }
4372: }
1.145 brouard 4373: /*goto avoid;*/
1.126 brouard 4374: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4375: for(jk=1; jk <=m; jk++) {
1.145 brouard 4376: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4377: if (ng==2)
4378: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4379: else
4380: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4381: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4382: i=1;
4383: for(k2=1; k2<=nlstate; k2++) {
4384: k3=i;
4385: for(k=1; k<=(nlstate+ndeath); k++) {
4386: if (k != k2){
4387: if(ng==2)
4388: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4389: else
4390: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4391: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4392: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4393: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4394: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4395: /* ij++; */
4396: /* } */
4397: /* else */
1.126 brouard 4398: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4399: }
4400: fprintf(ficgp,")/(1");
4401:
4402: for(k1=1; k1 <=nlstate; k1++){
4403: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4404: ij=1;
4405: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4406: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4407: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4408: /* ij++; */
4409: /* } */
4410: /* else */
1.126 brouard 4411: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4412: }
4413: fprintf(ficgp,")");
4414: }
4415: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4416: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4417: i=i+ncovmodel;
4418: }
4419: } /* end k */
4420: } /* end k2 */
4421: } /* end jk */
4422: } /* end ng */
1.164 brouard 4423: /* avoid: */
1.126 brouard 4424: fflush(ficgp);
4425: } /* end gnuplot */
4426:
4427:
4428: /*************** Moving average **************/
4429: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4430:
4431: int i, cpt, cptcod;
4432: int modcovmax =1;
4433: int mobilavrange, mob;
4434: double age;
4435:
4436: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4437: a covariate has 2 modalities */
4438: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4439:
4440: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4441: if(mobilav==1) mobilavrange=5; /* default */
4442: else mobilavrange=mobilav;
4443: for (age=bage; age<=fage; age++)
4444: for (i=1; i<=nlstate;i++)
4445: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4446: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4447: /* We keep the original values on the extreme ages bage, fage and for
4448: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4449: we use a 5 terms etc. until the borders are no more concerned.
4450: */
4451: for (mob=3;mob <=mobilavrange;mob=mob+2){
4452: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4453: for (i=1; i<=nlstate;i++){
4454: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4455: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4456: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4457: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4458: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4459: }
4460: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4461: }
4462: }
4463: }/* end age */
4464: }/* end mob */
4465: }else return -1;
4466: return 0;
4467: }/* End movingaverage */
4468:
4469:
4470: /************** Forecasting ******************/
1.169 brouard 4471: 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 4472: /* proj1, year, month, day of starting projection
4473: agemin, agemax range of age
4474: dateprev1 dateprev2 range of dates during which prevalence is computed
4475: anproj2 year of en of projection (same day and month as proj1).
4476: */
1.164 brouard 4477: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4478: double agec; /* generic age */
4479: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4480: double *popeffectif,*popcount;
4481: double ***p3mat;
4482: double ***mobaverage;
4483: char fileresf[FILENAMELENGTH];
4484:
4485: agelim=AGESUP;
4486: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4487:
4488: strcpy(fileresf,"f");
4489: strcat(fileresf,fileres);
4490: if((ficresf=fopen(fileresf,"w"))==NULL) {
4491: printf("Problem with forecast resultfile: %s\n", fileresf);
4492: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4493: }
4494: printf("Computing forecasting: result on file '%s' \n", fileresf);
4495: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4496:
4497: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4498:
4499: if (mobilav!=0) {
4500: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4501: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4502: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4503: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4504: }
4505: }
4506:
4507: stepsize=(int) (stepm+YEARM-1)/YEARM;
4508: if (stepm<=12) stepsize=1;
4509: if(estepm < stepm){
4510: printf ("Problem %d lower than %d\n",estepm, stepm);
4511: }
4512: else hstepm=estepm;
4513:
4514: hstepm=hstepm/stepm;
4515: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4516: fractional in yp1 */
4517: anprojmean=yp;
4518: yp2=modf((yp1*12),&yp);
4519: mprojmean=yp;
4520: yp1=modf((yp2*30.5),&yp);
4521: jprojmean=yp;
4522: if(jprojmean==0) jprojmean=1;
4523: if(mprojmean==0) jprojmean=1;
4524:
4525: i1=cptcoveff;
4526: if (cptcovn < 1){i1=1;}
4527:
4528: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4529:
4530: fprintf(ficresf,"#****** Routine prevforecast **\n");
4531:
4532: /* if (h==(int)(YEARM*yearp)){ */
4533: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4534: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4535: k=k+1;
4536: fprintf(ficresf,"\n#******");
4537: for(j=1;j<=cptcoveff;j++) {
4538: 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]]);
4539: }
4540: fprintf(ficresf,"******\n");
4541: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4542: for(j=1; j<=nlstate+ndeath;j++){
4543: for(i=1; i<=nlstate;i++)
4544: fprintf(ficresf," p%d%d",i,j);
4545: fprintf(ficresf," p.%d",j);
4546: }
4547: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4548: fprintf(ficresf,"\n");
4549: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4550:
4551: for (agec=fage; agec>=(ageminpar-1); agec--){
4552: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4553: nhstepm = nhstepm/hstepm;
4554: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4555: oldm=oldms;savm=savms;
4556: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4557:
4558: for (h=0; h<=nhstepm; h++){
4559: if (h*hstepm/YEARM*stepm ==yearp) {
4560: fprintf(ficresf,"\n");
4561: for(j=1;j<=cptcoveff;j++)
4562: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4563: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4564: }
4565: for(j=1; j<=nlstate+ndeath;j++) {
4566: ppij=0.;
4567: for(i=1; i<=nlstate;i++) {
4568: if (mobilav==1)
4569: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4570: else {
4571: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4572: }
4573: if (h*hstepm/YEARM*stepm== yearp) {
4574: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4575: }
4576: } /* end i */
4577: if (h*hstepm/YEARM*stepm==yearp) {
4578: fprintf(ficresf," %.3f", ppij);
4579: }
4580: }/* end j */
4581: } /* end h */
4582: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4583: } /* end agec */
4584: } /* end yearp */
4585: } /* end cptcod */
4586: } /* end cptcov */
4587:
4588: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4589:
4590: fclose(ficresf);
4591: }
4592:
4593: /************** Forecasting *****not tested NB*************/
1.169 brouard 4594: 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 4595:
4596: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4597: int *popage;
4598: double calagedatem, agelim, kk1, kk2;
4599: double *popeffectif,*popcount;
4600: double ***p3mat,***tabpop,***tabpopprev;
4601: double ***mobaverage;
4602: char filerespop[FILENAMELENGTH];
4603:
4604: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4605: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4606: agelim=AGESUP;
4607: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4608:
4609: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4610:
4611:
4612: strcpy(filerespop,"pop");
4613: strcat(filerespop,fileres);
4614: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4615: printf("Problem with forecast resultfile: %s\n", filerespop);
4616: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4617: }
4618: printf("Computing forecasting: result on file '%s' \n", filerespop);
4619: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4620:
4621: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4622:
4623: if (mobilav!=0) {
4624: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4625: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4626: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4627: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4628: }
4629: }
4630:
4631: stepsize=(int) (stepm+YEARM-1)/YEARM;
4632: if (stepm<=12) stepsize=1;
4633:
4634: agelim=AGESUP;
4635:
4636: hstepm=1;
4637: hstepm=hstepm/stepm;
4638:
4639: if (popforecast==1) {
4640: if((ficpop=fopen(popfile,"r"))==NULL) {
4641: printf("Problem with population file : %s\n",popfile);exit(0);
4642: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4643: }
4644: popage=ivector(0,AGESUP);
4645: popeffectif=vector(0,AGESUP);
4646: popcount=vector(0,AGESUP);
4647:
4648: i=1;
4649: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4650:
4651: imx=i;
4652: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4653: }
4654:
4655: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4656: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4657: k=k+1;
4658: fprintf(ficrespop,"\n#******");
4659: for(j=1;j<=cptcoveff;j++) {
4660: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4661: }
4662: fprintf(ficrespop,"******\n");
4663: fprintf(ficrespop,"# Age");
4664: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4665: if (popforecast==1) fprintf(ficrespop," [Population]");
4666:
4667: for (cpt=0; cpt<=0;cpt++) {
4668: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4669:
4670: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4671: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4672: nhstepm = nhstepm/hstepm;
4673:
4674: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4675: oldm=oldms;savm=savms;
4676: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4677:
4678: for (h=0; h<=nhstepm; h++){
4679: if (h==(int) (calagedatem+YEARM*cpt)) {
4680: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4681: }
4682: for(j=1; j<=nlstate+ndeath;j++) {
4683: kk1=0.;kk2=0;
4684: for(i=1; i<=nlstate;i++) {
4685: if (mobilav==1)
4686: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4687: else {
4688: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4689: }
4690: }
4691: if (h==(int)(calagedatem+12*cpt)){
4692: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4693: /*fprintf(ficrespop," %.3f", kk1);
4694: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4695: }
4696: }
4697: for(i=1; i<=nlstate;i++){
4698: kk1=0.;
4699: for(j=1; j<=nlstate;j++){
4700: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4701: }
4702: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4703: }
4704:
4705: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4706: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4707: }
4708: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4709: }
4710: }
4711:
4712: /******/
4713:
4714: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4715: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4716: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4717: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4718: nhstepm = nhstepm/hstepm;
4719:
4720: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4721: oldm=oldms;savm=savms;
4722: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4723: for (h=0; h<=nhstepm; h++){
4724: if (h==(int) (calagedatem+YEARM*cpt)) {
4725: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4726: }
4727: for(j=1; j<=nlstate+ndeath;j++) {
4728: kk1=0.;kk2=0;
4729: for(i=1; i<=nlstate;i++) {
4730: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4731: }
4732: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4733: }
4734: }
4735: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4736: }
4737: }
4738: }
4739: }
4740:
4741: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4742:
4743: if (popforecast==1) {
4744: free_ivector(popage,0,AGESUP);
4745: free_vector(popeffectif,0,AGESUP);
4746: free_vector(popcount,0,AGESUP);
4747: }
4748: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4749: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4750: fclose(ficrespop);
4751: } /* End of popforecast */
4752:
4753: int fileappend(FILE *fichier, char *optionfich)
4754: {
4755: if((fichier=fopen(optionfich,"a"))==NULL) {
4756: printf("Problem with file: %s\n", optionfich);
4757: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4758: return (0);
4759: }
4760: fflush(fichier);
4761: return (1);
4762: }
4763:
4764:
4765: /**************** function prwizard **********************/
4766: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4767: {
4768:
4769: /* Wizard to print covariance matrix template */
4770:
1.164 brouard 4771: char ca[32], cb[32];
4772: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4773: int numlinepar;
4774:
4775: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4776: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4777: for(i=1; i <=nlstate; i++){
4778: jj=0;
4779: for(j=1; j <=nlstate+ndeath; j++){
4780: if(j==i) continue;
4781: jj++;
4782: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4783: printf("%1d%1d",i,j);
4784: fprintf(ficparo,"%1d%1d",i,j);
4785: for(k=1; k<=ncovmodel;k++){
4786: /* printf(" %lf",param[i][j][k]); */
4787: /* fprintf(ficparo," %lf",param[i][j][k]); */
4788: printf(" 0.");
4789: fprintf(ficparo," 0.");
4790: }
4791: printf("\n");
4792: fprintf(ficparo,"\n");
4793: }
4794: }
4795: printf("# Scales (for hessian or gradient estimation)\n");
4796: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4797: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
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: fprintf(ficparo,"%1d%1d",i,j);
4804: printf("%1d%1d",i,j);
4805: fflush(stdout);
4806: for(k=1; k<=ncovmodel;k++){
4807: /* printf(" %le",delti3[i][j][k]); */
4808: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4809: printf(" 0.");
4810: fprintf(ficparo," 0.");
4811: }
4812: numlinepar++;
4813: printf("\n");
4814: fprintf(ficparo,"\n");
4815: }
4816: }
4817: printf("# Covariance matrix\n");
4818: /* # 121 Var(a12)\n\ */
4819: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4820: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4821: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4822: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4823: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4824: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4825: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4826: fflush(stdout);
4827: fprintf(ficparo,"# Covariance matrix\n");
4828: /* # 121 Var(a12)\n\ */
4829: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4830: /* # ...\n\ */
4831: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4832:
4833: for(itimes=1;itimes<=2;itimes++){
4834: jj=0;
4835: for(i=1; i <=nlstate; i++){
4836: for(j=1; j <=nlstate+ndeath; j++){
4837: if(j==i) continue;
4838: for(k=1; k<=ncovmodel;k++){
4839: jj++;
4840: ca[0]= k+'a'-1;ca[1]='\0';
4841: if(itimes==1){
4842: printf("#%1d%1d%d",i,j,k);
4843: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4844: }else{
4845: printf("%1d%1d%d",i,j,k);
4846: fprintf(ficparo,"%1d%1d%d",i,j,k);
4847: /* printf(" %.5le",matcov[i][j]); */
4848: }
4849: ll=0;
4850: for(li=1;li <=nlstate; li++){
4851: for(lj=1;lj <=nlstate+ndeath; lj++){
4852: if(lj==li) continue;
4853: for(lk=1;lk<=ncovmodel;lk++){
4854: ll++;
4855: if(ll<=jj){
4856: cb[0]= lk +'a'-1;cb[1]='\0';
4857: if(ll<jj){
4858: if(itimes==1){
4859: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4860: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4861: }else{
4862: printf(" 0.");
4863: fprintf(ficparo," 0.");
4864: }
4865: }else{
4866: if(itimes==1){
4867: printf(" Var(%s%1d%1d)",ca,i,j);
4868: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4869: }else{
4870: printf(" 0.");
4871: fprintf(ficparo," 0.");
4872: }
4873: }
4874: }
4875: } /* end lk */
4876: } /* end lj */
4877: } /* end li */
4878: printf("\n");
4879: fprintf(ficparo,"\n");
4880: numlinepar++;
4881: } /* end k*/
4882: } /*end j */
4883: } /* end i */
4884: } /* end itimes */
4885:
4886: } /* end of prwizard */
4887: /******************* Gompertz Likelihood ******************************/
4888: double gompertz(double x[])
4889: {
4890: double A,B,L=0.0,sump=0.,num=0.;
4891: int i,n=0; /* n is the size of the sample */
4892:
4893: for (i=0;i<=imx-1 ; i++) {
4894: sump=sump+weight[i];
4895: /* sump=sump+1;*/
4896: num=num+1;
4897: }
4898:
4899:
4900: /* for (i=0; i<=imx; i++)
4901: 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]);*/
4902:
4903: for (i=1;i<=imx ; i++)
4904: {
4905: if (cens[i] == 1 && wav[i]>1)
4906: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4907:
4908: if (cens[i] == 0 && wav[i]>1)
4909: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4910: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4911:
4912: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4913: if (wav[i] > 1 ) { /* ??? */
4914: L=L+A*weight[i];
4915: /* 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]);*/
4916: }
4917: }
4918:
4919: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4920:
4921: return -2*L*num/sump;
4922: }
4923:
1.136 brouard 4924: #ifdef GSL
4925: /******************* Gompertz_f Likelihood ******************************/
4926: double gompertz_f(const gsl_vector *v, void *params)
4927: {
4928: double A,B,LL=0.0,sump=0.,num=0.;
4929: double *x= (double *) v->data;
4930: int i,n=0; /* n is the size of the sample */
4931:
4932: for (i=0;i<=imx-1 ; i++) {
4933: sump=sump+weight[i];
4934: /* sump=sump+1;*/
4935: num=num+1;
4936: }
4937:
4938:
4939: /* for (i=0; i<=imx; i++)
4940: 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]);*/
4941: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4942: for (i=1;i<=imx ; i++)
4943: {
4944: if (cens[i] == 1 && wav[i]>1)
4945: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4946:
4947: if (cens[i] == 0 && wav[i]>1)
4948: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4949: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4950:
4951: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4952: if (wav[i] > 1 ) { /* ??? */
4953: LL=LL+A*weight[i];
4954: /* 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]);*/
4955: }
4956: }
4957:
4958: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4959: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4960:
4961: return -2*LL*num/sump;
4962: }
4963: #endif
4964:
1.126 brouard 4965: /******************* Printing html file ***********/
4966: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4967: int lastpass, int stepm, int weightopt, char model[],\
4968: int imx, double p[],double **matcov,double agemortsup){
4969: int i,k;
4970:
4971: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4972: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4973: for (i=1;i<=2;i++)
4974: 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]));
4975: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4976: fprintf(fichtm,"</ul>");
4977:
4978: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4979:
4980: 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>");
4981:
4982: for (k=agegomp;k<(agemortsup-2);k++)
4983: 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]);
4984:
4985:
4986: fflush(fichtm);
4987: }
4988:
4989: /******************* Gnuplot file **************/
4990: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4991:
4992: char dirfileres[132],optfileres[132];
1.164 brouard 4993:
1.126 brouard 4994: int ng;
4995:
4996:
4997: /*#ifdef windows */
4998: fprintf(ficgp,"cd \"%s\" \n",pathc);
4999: /*#endif */
5000:
5001:
5002: strcpy(dirfileres,optionfilefiname);
5003: strcpy(optfileres,"vpl");
5004: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5005: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5006: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5007: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5008: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5009:
5010: }
5011:
1.136 brouard 5012: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5013: {
1.126 brouard 5014:
1.136 brouard 5015: /*-------- data file ----------*/
5016: FILE *fic;
5017: char dummy[]=" ";
1.164 brouard 5018: int i=0, j=0, n=0;
1.136 brouard 5019: int linei, month, year,iout;
5020: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5021: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5022: char *stratrunc;
5023: int lstra;
1.126 brouard 5024:
5025:
1.136 brouard 5026: if((fic=fopen(datafile,"r"))==NULL) {
5027: printf("Problem while opening datafile: %s\n", datafile);return 1;
5028: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5029: }
1.126 brouard 5030:
1.136 brouard 5031: i=1;
5032: linei=0;
5033: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5034: linei=linei+1;
5035: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5036: if(line[j] == '\t')
5037: line[j] = ' ';
5038: }
5039: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5040: ;
5041: };
5042: line[j+1]=0; /* Trims blanks at end of line */
5043: if(line[0]=='#'){
5044: fprintf(ficlog,"Comment line\n%s\n",line);
5045: printf("Comment line\n%s\n",line);
5046: continue;
5047: }
5048: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5049: strcpy(line, linetmp);
1.136 brouard 5050:
1.126 brouard 5051:
1.136 brouard 5052: for (j=maxwav;j>=1;j--){
1.137 brouard 5053: cutv(stra, strb, line, ' ');
1.136 brouard 5054: if(strb[0]=='.') { /* Missing status */
5055: lval=-1;
5056: }else{
5057: errno=0;
5058: lval=strtol(strb,&endptr,10);
5059: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5060: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5061: 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);
5062: 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 5063: return 1;
5064: }
5065: }
5066: s[j][i]=lval;
5067:
5068: strcpy(line,stra);
5069: cutv(stra, strb,line,' ');
1.169 brouard 5070: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5071: }
1.169 brouard 5072: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5073: month=99;
5074: year=9999;
5075: }else{
1.141 brouard 5076: 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);
5077: 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 5078: return 1;
5079: }
5080: anint[j][i]= (double) year;
5081: mint[j][i]= (double)month;
5082: strcpy(line,stra);
5083: } /* ENd Waves */
5084:
5085: cutv(stra, strb,line,' ');
1.169 brouard 5086: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5087: }
1.169 brouard 5088: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5089: month=99;
5090: year=9999;
5091: }else{
1.141 brouard 5092: 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);
5093: 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 5094: return 1;
5095: }
5096: andc[i]=(double) year;
5097: moisdc[i]=(double) month;
5098: strcpy(line,stra);
5099:
5100: cutv(stra, strb,line,' ');
1.169 brouard 5101: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5102: }
1.169 brouard 5103: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5104: month=99;
5105: year=9999;
5106: }else{
1.141 brouard 5107: 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);
5108: 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 5109: return 1;
5110: }
5111: if (year==9999) {
1.141 brouard 5112: 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);
5113: 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 5114: return 1;
1.126 brouard 5115:
1.136 brouard 5116: }
5117: annais[i]=(double)(year);
5118: moisnais[i]=(double)(month);
5119: strcpy(line,stra);
5120:
5121: cutv(stra, strb,line,' ');
5122: errno=0;
5123: dval=strtod(strb,&endptr);
5124: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5125: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5126: 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 5127: fflush(ficlog);
5128: return 1;
5129: }
5130: weight[i]=dval;
5131: strcpy(line,stra);
5132:
5133: for (j=ncovcol;j>=1;j--){
5134: cutv(stra, strb,line,' ');
5135: if(strb[0]=='.') { /* Missing status */
5136: lval=-1;
5137: }else{
5138: errno=0;
5139: lval=strtol(strb,&endptr,10);
5140: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5141: 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);
5142: 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 5143: return 1;
5144: }
5145: }
5146: if(lval <-1 || lval >1){
1.141 brouard 5147: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5148: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5149: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5150: For example, for multinomial values like 1, 2 and 3,\n \
5151: build V1=0 V2=0 for the reference value (1),\n \
5152: V1=1 V2=0 for (2) \n \
5153: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5154: output of IMaCh is often meaningless.\n \
5155: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5156: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5157: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5158: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5159: For example, for multinomial values like 1, 2 and 3,\n \
5160: build V1=0 V2=0 for the reference value (1),\n \
5161: V1=1 V2=0 for (2) \n \
5162: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5163: output of IMaCh is often meaningless.\n \
5164: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5165: return 1;
5166: }
5167: covar[j][i]=(double)(lval);
5168: strcpy(line,stra);
5169: }
5170: lstra=strlen(stra);
5171:
5172: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5173: stratrunc = &(stra[lstra-9]);
5174: num[i]=atol(stratrunc);
5175: }
5176: else
5177: num[i]=atol(stra);
5178: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5179: 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;}*/
5180:
5181: i=i+1;
5182: } /* End loop reading data */
1.126 brouard 5183:
1.136 brouard 5184: *imax=i-1; /* Number of individuals */
5185: fclose(fic);
5186:
5187: return (0);
1.164 brouard 5188: /* endread: */
1.136 brouard 5189: printf("Exiting readdata: ");
5190: fclose(fic);
5191: return (1);
1.126 brouard 5192:
5193:
5194:
1.136 brouard 5195: }
1.145 brouard 5196: void removespace(char *str) {
5197: char *p1 = str, *p2 = str;
5198: do
5199: while (*p2 == ' ')
5200: p2++;
1.169 brouard 5201: while (*p1++ == *p2++);
1.145 brouard 5202: }
5203:
5204: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5205: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5206: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5207: * - cptcovn or number of covariates k of the models excluding age*products =6
5208: * - cptcovage number of covariates with age*products =2
5209: * - cptcovs number of simple covariates
5210: * - 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
5211: * which is a new column after the 9 (ncovcol) variables.
5212: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5213: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5214: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5215: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5216: */
1.136 brouard 5217: {
1.145 brouard 5218: int i, j, k, ks;
1.164 brouard 5219: int j1, k1, k2;
1.136 brouard 5220: char modelsav[80];
1.145 brouard 5221: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5222:
1.145 brouard 5223: /*removespace(model);*/
1.136 brouard 5224: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5225: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5226: j=nbocc(model,'+'); /**< j=Number of '+' */
5227: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5228: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5229: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5230: /* including age products which are counted in cptcovage.
1.169 brouard 5231: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5232: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5233: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5234: strcpy(modelsav,model);
1.137 brouard 5235: if (strstr(model,"AGE") !=0){
5236: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5237: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5238: return 1;
5239: }
1.141 brouard 5240: if (strstr(model,"v") !=0){
5241: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5242: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5243: return 1;
5244: }
1.136 brouard 5245:
1.145 brouard 5246: /* Design
5247: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5248: * < ncovcol=8 >
5249: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5250: * k= 1 2 3 4 5 6 7 8
5251: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5252: * covar[k,i], value of kth covariate if not including age for individual i:
5253: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5254: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5255: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5256: * Tage[++cptcovage]=k
5257: * if products, new covar are created after ncovcol with k1
5258: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5259: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5260: * 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
5261: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5262: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5263: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5264: * < ncovcol=8 >
5265: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5266: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5267: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5268: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5269: * p Tprod[1]@2={ 6, 5}
5270: *p Tvard[1][1]@4= {7, 8, 5, 6}
5271: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5272: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5273: *How to reorganize?
5274: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5275: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5276: * {2, 1, 4, 8, 5, 6, 3, 7}
5277: * Struct []
5278: */
5279:
1.136 brouard 5280: /* This loop fills the array Tvar from the string 'model'.*/
5281: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5282: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5283: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5284: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5285: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5286: /* k=1 Tvar[1]=2 (from V2) */
5287: /* k=5 Tvar[5] */
5288: /* for (k=1; k<=cptcovn;k++) { */
5289: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5290: /* } */
5291: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5292: /*
5293: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5294: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5295: Tvar[k]=0;
5296: cptcovage=0;
5297: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5298: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5299: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5300: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5301: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5302: /*scanf("%d",i);*/
1.145 brouard 5303: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5304: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5305: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5306: /* covar is not filled and then is empty */
1.136 brouard 5307: cptcovprod--;
1.145 brouard 5308: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5309: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5310: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5311: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5312: /*printf("stre=%s ", stre);*/
1.137 brouard 5313: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5314: cptcovprod--;
1.145 brouard 5315: cutl(stre,strb,strc,'V');
1.136 brouard 5316: Tvar[k]=atoi(stre);
5317: cptcovage++;
5318: Tage[cptcovage]=k;
1.137 brouard 5319: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5320: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5321: cptcovn++;
5322: cptcovprodnoage++;k1++;
5323: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5324: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5325: because this model-covariate is a construction we invent a new column
5326: ncovcol + k1
5327: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5328: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5329: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5330: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5331: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5332: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5333: k2=k2+2;
5334: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5335: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5336: for (i=1; i<=lastobs;i++){
5337: /* Computes the new covariate which is a product of
1.145 brouard 5338: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5339: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5340: }
5341: } /* End age is not in the model */
5342: } /* End if model includes a product */
1.136 brouard 5343: else { /* no more sum */
5344: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5345: /* scanf("%d",i);*/
1.145 brouard 5346: cutl(strd,strc,strb,'V');
5347: ks++; /**< Number of simple covariates */
5348: cptcovn++;
5349: Tvar[k]=atoi(strd);
1.136 brouard 5350: }
1.137 brouard 5351: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5352: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5353: scanf("%d",i);*/
5354: } /* end of loop + */
5355: } /* end model */
5356:
5357: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5358: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5359:
5360: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5361: printf("cptcovprod=%d ", cptcovprod);
5362: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5363:
5364: scanf("%d ",i);*/
5365:
5366:
1.137 brouard 5367: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5368: /*endread:*/
1.136 brouard 5369: printf("Exiting decodemodel: ");
5370: return (1);
5371: }
5372:
1.169 brouard 5373: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5374: {
5375: int i, m;
5376:
5377: for (i=1; i<=imx; i++) {
5378: for(m=2; (m<= maxwav); m++) {
5379: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5380: anint[m][i]=9999;
5381: s[m][i]=-1;
5382: }
5383: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5384: *nberr = *nberr + 1;
5385: 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);
5386: 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 5387: s[m][i]=-1;
5388: }
5389: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5390: (*nberr)++;
1.136 brouard 5391: 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]);
5392: 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]);
5393: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5394: }
5395: }
5396: }
5397:
5398: for (i=1; i<=imx; i++) {
5399: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5400: for(m=firstpass; (m<= lastpass); m++){
5401: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5402: if (s[m][i] >= nlstate+1) {
1.169 brouard 5403: if(agedc[i]>0){
5404: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5405: agev[m][i]=agedc[i];
5406: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5407: }else {
1.136 brouard 5408: if ((int)andc[i]!=9999){
5409: nbwarn++;
5410: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5411: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5412: agev[m][i]=-1;
5413: }
5414: }
1.169 brouard 5415: } /* agedc > 0 */
1.136 brouard 5416: }
5417: else if(s[m][i] !=9){ /* Standard case, age in fractional
5418: years but with the precision of a month */
5419: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5420: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5421: agev[m][i]=1;
5422: else if(agev[m][i] < *agemin){
5423: *agemin=agev[m][i];
5424: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5425: }
5426: else if(agev[m][i] >*agemax){
5427: *agemax=agev[m][i];
1.156 brouard 5428: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5429: }
5430: /*agev[m][i]=anint[m][i]-annais[i];*/
5431: /* agev[m][i] = age[i]+2*m;*/
5432: }
5433: else { /* =9 */
5434: agev[m][i]=1;
5435: s[m][i]=-1;
5436: }
5437: }
5438: else /*= 0 Unknown */
5439: agev[m][i]=1;
5440: }
5441:
5442: }
5443: for (i=1; i<=imx; i++) {
5444: for(m=firstpass; (m<=lastpass); m++){
5445: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5446: (*nberr)++;
1.136 brouard 5447: 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);
5448: 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);
5449: return 1;
5450: }
5451: }
5452: }
5453:
5454: /*for (i=1; i<=imx; i++){
5455: for (m=firstpass; (m<lastpass); m++){
5456: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5457: }
5458:
5459: }*/
5460:
5461:
1.139 brouard 5462: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5463: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5464:
5465: return (0);
1.164 brouard 5466: /* endread:*/
1.136 brouard 5467: printf("Exiting calandcheckages: ");
5468: return (1);
5469: }
5470:
1.172 brouard 5471: #if defined(_MSC_VER)
5472: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5473: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5474: //#include "stdafx.h"
5475: //#include <stdio.h>
5476: //#include <tchar.h>
5477: //#include <windows.h>
5478: //#include <iostream>
5479: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5480:
5481: LPFN_ISWOW64PROCESS fnIsWow64Process;
5482:
5483: BOOL IsWow64()
5484: {
5485: BOOL bIsWow64 = FALSE;
5486:
5487: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5488: // (HANDLE, PBOOL);
5489:
5490: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5491:
5492: HMODULE module = GetModuleHandle(_T("kernel32"));
5493: const char funcName[] = "IsWow64Process";
5494: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5495: GetProcAddress(module, funcName);
5496:
5497: if (NULL != fnIsWow64Process)
5498: {
5499: if (!fnIsWow64Process(GetCurrentProcess(),
5500: &bIsWow64))
5501: //throw std::exception("Unknown error");
5502: printf("Unknown error\n");
5503: }
5504: return bIsWow64 != FALSE;
5505: }
5506: #endif
1.177 ! brouard 5507:
1.169 brouard 5508: void syscompilerinfo()
1.167 brouard 5509: {
5510: /* #include "syscompilerinfo.h"*/
1.177 ! brouard 5511:
! 5512: #if defined __INTEL_COMPILER
! 5513: struct utsname sysInfo;
! 5514: #elif defined(__GNUC__)
1.174 brouard 5515: #include <gnu/libc-version.h> /* Only on gnu */
1.177 ! brouard 5516: struct utsname sysInfo;
1.174 brouard 5517: #endif
5518:
1.171 brouard 5519: #include <stdint.h>
1.175 brouard 5520: int cross = CROSS;
5521: if (cross){
5522: printf("Cross-");
5523: fprintf(ficlog,"Cross-");
5524: }
1.169 brouard 5525: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5526: #if defined(__clang__)
5527: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5528: #endif
5529: #if defined(__ICC) || defined(__INTEL_COMPILER)
5530: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5531: #endif
5532: #if defined(__GNUC__) || defined(__GNUG__)
5533: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5534: #endif
5535: #if defined(__HP_cc) || defined(__HP_aCC)
5536: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5537: #endif
5538: #if defined(__IBMC__) || defined(__IBMCPP__)
5539: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5540: #endif
5541: #if defined(_MSC_VER)
5542: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5543: #endif
5544: #if defined(__PGI)
5545: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5546: #endif
5547: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5548: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5549: #endif
1.174 brouard 5550: printf(" for ");fprintf(ficlog," for ");
1.169 brouard 5551:
1.167 brouard 5552: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5553: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5554: // Windows (x64 and x86)
1.174 brouard 5555: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 5556: #elif __unix__ // all unices, not all compilers
5557: // Unix
1.174 brouard 5558: printf("Unix ");fprintf(ficlog,"Unix ");
1.167 brouard 5559: #elif __linux__
5560: // linux
1.174 brouard 5561: printf("linux ");fprintf(ficlog,"linux ");
1.167 brouard 5562: #elif __APPLE__
1.174 brouard 5563: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5564: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167 brouard 5565: #endif
5566:
5567: /* __MINGW32__ */
5568: /* __CYGWIN__ */
5569: /* __MINGW64__ */
5570: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5571: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5572: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5573: /* _WIN64 // Defined for applications for Win64. */
5574: /* _M_X64 // Defined for compilations that target x64 processors. */
5575: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5576:
1.167 brouard 5577: #if UINTPTR_MAX == 0xffffffff
1.174 brouard 5578: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 5579: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174 brouard 5580: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 5581: #else
1.174 brouard 5582: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 5583: #endif
5584:
1.169 brouard 5585: #if defined(__GNUC__)
5586: # if defined(__GNUC_PATCHLEVEL__)
5587: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5588: + __GNUC_MINOR__ * 100 \
5589: + __GNUC_PATCHLEVEL__)
5590: # else
5591: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5592: + __GNUC_MINOR__ * 100)
5593: # endif
1.174 brouard 5594: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5595: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 5596:
5597: if (uname(&sysInfo) != -1) {
5598: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5599: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5600: }
5601: else
5602: perror("uname() error");
1.177 ! brouard 5603: #ifndef __INTEL_COMPILER
1.174 brouard 5604: printf("GNU libc version: %s\n", gnu_get_libc_version());
5605: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 ! brouard 5606: #endif
1.169 brouard 5607: #endif
1.172 brouard 5608:
5609: // void main()
5610: // {
1.169 brouard 5611: #if defined(_MSC_VER)
1.174 brouard 5612: if (IsWow64()){
1.176 brouard 5613: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5614: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 5615: }
5616: else{
1.176 brouard 5617: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5618: frintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 5619: }
1.172 brouard 5620: // printf("\nPress Enter to continue...");
5621: // getchar();
5622: // }
5623:
1.169 brouard 5624: #endif
5625:
1.167 brouard 5626:
5627: }
1.136 brouard 5628:
5629: /***********************************************/
5630: /**************** Main Program *****************/
5631: /***********************************************/
5632:
5633: int main(int argc, char *argv[])
5634: {
5635: #ifdef GSL
5636: const gsl_multimin_fminimizer_type *T;
5637: size_t iteri = 0, it;
5638: int rval = GSL_CONTINUE;
5639: int status = GSL_SUCCESS;
5640: double ssval;
5641: #endif
5642: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5643: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5644:
5645: int jj, ll, li, lj, lk;
1.136 brouard 5646: int numlinepar=0; /* Current linenumber of parameter file */
5647: int itimes;
5648: int NDIM=2;
5649: int vpopbased=0;
5650:
1.164 brouard 5651: char ca[32], cb[32];
1.136 brouard 5652: /* FILE *fichtm; *//* Html File */
5653: /* FILE *ficgp;*/ /*Gnuplot File */
5654: struct stat info;
1.164 brouard 5655: double agedeb;
1.136 brouard 5656: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5657:
1.165 brouard 5658: double fret;
1.136 brouard 5659: double dum; /* Dummy variable */
5660: double ***p3mat;
5661: double ***mobaverage;
1.164 brouard 5662:
5663: char line[MAXLINE];
1.136 brouard 5664: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5665: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5666: char *tok, *val; /* pathtot */
1.136 brouard 5667: int firstobs=1, lastobs=10;
1.164 brouard 5668: int c, h , cpt;
5669: int jl;
5670: int i1, j1, jk, stepsize;
5671: int *tab;
1.136 brouard 5672: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5673: int mobilav=0,popforecast=0;
5674: int hstepm, nhstepm;
5675: int agemortsup;
5676: float sumlpop=0.;
5677: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5678: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5679:
1.164 brouard 5680: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5681: double ftolpl=FTOL;
5682: double **prlim;
5683: double ***param; /* Matrix of parameters */
5684: double *p;
5685: double **matcov; /* Matrix of covariance */
5686: double ***delti3; /* Scale */
5687: double *delti; /* Scale */
5688: double ***eij, ***vareij;
5689: double **varpl; /* Variances of prevalence limits by age */
5690: double *epj, vepp;
1.164 brouard 5691:
1.136 brouard 5692: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5693: double **ximort;
1.145 brouard 5694: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5695: int *dcwave;
5696:
1.164 brouard 5697: char z[1]="c";
1.136 brouard 5698:
5699: /*char *strt;*/
5700: char strtend[80];
1.126 brouard 5701:
1.164 brouard 5702:
1.126 brouard 5703: /* setlocale (LC_ALL, ""); */
5704: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5705: /* textdomain (PACKAGE); */
5706: /* setlocale (LC_CTYPE, ""); */
5707: /* setlocale (LC_MESSAGES, ""); */
5708:
5709: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5710: rstart_time = time(NULL);
5711: /* (void) gettimeofday(&start_time,&tzp);*/
5712: start_time = *localtime(&rstart_time);
1.126 brouard 5713: curr_time=start_time;
1.157 brouard 5714: /*tml = *localtime(&start_time.tm_sec);*/
5715: /* strcpy(strstart,asctime(&tml)); */
5716: strcpy(strstart,asctime(&start_time));
1.126 brouard 5717:
5718: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5719: /* tp.tm_sec = tp.tm_sec +86400; */
5720: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5721: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5722: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5723: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5724: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5725: /* strt=asctime(&tmg); */
5726: /* printf("Time(after) =%s",strstart); */
5727: /* (void) time (&time_value);
5728: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5729: * tm = *localtime(&time_value);
5730: * strstart=asctime(&tm);
5731: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5732: */
5733:
5734: nberr=0; /* Number of errors and warnings */
5735: nbwarn=0;
5736: getcwd(pathcd, size);
5737:
5738: printf("\n%s\n%s",version,fullversion);
5739: if(argc <=1){
5740: printf("\nEnter the parameter file name: ");
5741: fgets(pathr,FILENAMELENGTH,stdin);
5742: i=strlen(pathr);
5743: if(pathr[i-1]=='\n')
5744: pathr[i-1]='\0';
1.156 brouard 5745: i=strlen(pathr);
5746: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5747: pathr[i-1]='\0';
1.126 brouard 5748: for (tok = pathr; tok != NULL; ){
5749: printf("Pathr |%s|\n",pathr);
5750: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5751: printf("val= |%s| pathr=%s\n",val,pathr);
5752: strcpy (pathtot, val);
5753: if(pathr[0] == '\0') break; /* Dirty */
5754: }
5755: }
5756: else{
5757: strcpy(pathtot,argv[1]);
5758: }
5759: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5760: /*cygwin_split_path(pathtot,path,optionfile);
5761: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5762: /* cutv(path,optionfile,pathtot,'\\');*/
5763:
5764: /* Split argv[0], imach program to get pathimach */
5765: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5766: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5767: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5768: /* strcpy(pathimach,argv[0]); */
5769: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5770: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5771: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5772: chdir(path); /* Can be a relative path */
5773: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5774: printf("Current directory %s!\n",pathcd);
5775: strcpy(command,"mkdir ");
5776: strcat(command,optionfilefiname);
5777: if((outcmd=system(command)) != 0){
1.169 brouard 5778: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 5779: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5780: /* fclose(ficlog); */
5781: /* exit(1); */
5782: }
5783: /* if((imk=mkdir(optionfilefiname))<0){ */
5784: /* perror("mkdir"); */
5785: /* } */
5786:
5787: /*-------- arguments in the command line --------*/
5788:
5789: /* Log file */
5790: strcat(filelog, optionfilefiname);
5791: strcat(filelog,".log"); /* */
5792: if((ficlog=fopen(filelog,"w"))==NULL) {
5793: printf("Problem with logfile %s\n",filelog);
5794: goto end;
5795: }
5796: fprintf(ficlog,"Log filename:%s\n",filelog);
5797: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5798: fprintf(ficlog,"\nEnter the parameter file name: \n");
5799: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5800: path=%s \n\
5801: optionfile=%s\n\
5802: optionfilext=%s\n\
1.156 brouard 5803: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5804:
1.167 brouard 5805: syscompilerinfo();
5806:
1.126 brouard 5807: printf("Local time (at start):%s",strstart);
5808: fprintf(ficlog,"Local time (at start): %s",strstart);
5809: fflush(ficlog);
5810: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5811: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5812:
5813: /* */
5814: strcpy(fileres,"r");
5815: strcat(fileres, optionfilefiname);
5816: strcat(fileres,".txt"); /* Other files have txt extension */
5817:
5818: /*---------arguments file --------*/
5819:
5820: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5821: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5822: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5823: fflush(ficlog);
1.149 brouard 5824: /* goto end; */
5825: exit(70);
1.126 brouard 5826: }
5827:
5828:
5829:
5830: strcpy(filereso,"o");
5831: strcat(filereso,fileres);
5832: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5833: printf("Problem with Output resultfile: %s\n", filereso);
5834: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5835: fflush(ficlog);
5836: goto end;
5837: }
5838:
5839: /* Reads comments: lines beginning with '#' */
5840: numlinepar=0;
5841: while((c=getc(ficpar))=='#' && c!= EOF){
5842: ungetc(c,ficpar);
5843: fgets(line, MAXLINE, ficpar);
5844: numlinepar++;
1.141 brouard 5845: fputs(line,stdout);
1.126 brouard 5846: fputs(line,ficparo);
5847: fputs(line,ficlog);
5848: }
5849: ungetc(c,ficpar);
5850:
5851: 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);
5852: numlinepar++;
5853: 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);
5854: 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);
5855: 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);
5856: fflush(ficlog);
5857: while((c=getc(ficpar))=='#' && c!= EOF){
5858: ungetc(c,ficpar);
5859: fgets(line, MAXLINE, ficpar);
5860: numlinepar++;
1.141 brouard 5861: fputs(line, stdout);
5862: //puts(line);
1.126 brouard 5863: fputs(line,ficparo);
5864: fputs(line,ficlog);
5865: }
5866: ungetc(c,ficpar);
5867:
5868:
1.145 brouard 5869: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5870: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5871: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5872: v1+v2*age+v2*v3 makes cptcovn = 3
5873: */
5874: if (strlen(model)>1)
1.145 brouard 5875: 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*/
5876: else
5877: ncovmodel=2;
1.126 brouard 5878: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5879: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5880: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5881: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5882: 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);
5883: 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);
5884: fflush(stdout);
5885: fclose (ficlog);
5886: goto end;
5887: }
1.126 brouard 5888: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5889: delti=delti3[1][1];
5890: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5891: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5892: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5893: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5894: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5895: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5896: fclose (ficparo);
5897: fclose (ficlog);
5898: goto end;
5899: exit(0);
5900: }
5901: else if(mle==-3) {
5902: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5903: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5904: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5905: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5906: matcov=matrix(1,npar,1,npar);
5907: }
5908: else{
1.145 brouard 5909: /* Read guessed parameters */
1.126 brouard 5910: /* Reads comments: lines beginning with '#' */
5911: while((c=getc(ficpar))=='#' && c!= EOF){
5912: ungetc(c,ficpar);
5913: fgets(line, MAXLINE, ficpar);
5914: numlinepar++;
1.141 brouard 5915: fputs(line,stdout);
1.126 brouard 5916: fputs(line,ficparo);
5917: fputs(line,ficlog);
5918: }
5919: ungetc(c,ficpar);
5920:
5921: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5922: for(i=1; i <=nlstate; i++){
5923: j=0;
5924: for(jj=1; jj <=nlstate+ndeath; jj++){
5925: if(jj==i) continue;
5926: j++;
5927: fscanf(ficpar,"%1d%1d",&i1,&j1);
5928: if ((i1 != i) && (j1 != j)){
5929: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5930: It might be a problem of design; if ncovcol and the model are correct\n \
5931: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5932: exit(1);
5933: }
5934: fprintf(ficparo,"%1d%1d",i1,j1);
5935: if(mle==1)
5936: printf("%1d%1d",i,j);
5937: fprintf(ficlog,"%1d%1d",i,j);
5938: for(k=1; k<=ncovmodel;k++){
5939: fscanf(ficpar," %lf",¶m[i][j][k]);
5940: if(mle==1){
5941: printf(" %lf",param[i][j][k]);
5942: fprintf(ficlog," %lf",param[i][j][k]);
5943: }
5944: else
5945: fprintf(ficlog," %lf",param[i][j][k]);
5946: fprintf(ficparo," %lf",param[i][j][k]);
5947: }
5948: fscanf(ficpar,"\n");
5949: numlinepar++;
5950: if(mle==1)
5951: printf("\n");
5952: fprintf(ficlog,"\n");
5953: fprintf(ficparo,"\n");
5954: }
5955: }
5956: fflush(ficlog);
5957:
1.145 brouard 5958: /* Reads scales values */
1.126 brouard 5959: p=param[1][1];
5960:
5961: /* Reads comments: lines beginning with '#' */
5962: while((c=getc(ficpar))=='#' && c!= EOF){
5963: ungetc(c,ficpar);
5964: fgets(line, MAXLINE, ficpar);
5965: numlinepar++;
1.141 brouard 5966: fputs(line,stdout);
1.126 brouard 5967: fputs(line,ficparo);
5968: fputs(line,ficlog);
5969: }
5970: ungetc(c,ficpar);
5971:
5972: for(i=1; i <=nlstate; i++){
5973: for(j=1; j <=nlstate+ndeath-1; j++){
5974: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 5975: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5976: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5977: exit(1);
5978: }
5979: printf("%1d%1d",i,j);
5980: fprintf(ficparo,"%1d%1d",i1,j1);
5981: fprintf(ficlog,"%1d%1d",i1,j1);
5982: for(k=1; k<=ncovmodel;k++){
5983: fscanf(ficpar,"%le",&delti3[i][j][k]);
5984: printf(" %le",delti3[i][j][k]);
5985: fprintf(ficparo," %le",delti3[i][j][k]);
5986: fprintf(ficlog," %le",delti3[i][j][k]);
5987: }
5988: fscanf(ficpar,"\n");
5989: numlinepar++;
5990: printf("\n");
5991: fprintf(ficparo,"\n");
5992: fprintf(ficlog,"\n");
5993: }
5994: }
5995: fflush(ficlog);
5996:
1.145 brouard 5997: /* Reads covariance matrix */
1.126 brouard 5998: delti=delti3[1][1];
5999:
6000:
6001: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6002:
6003: /* Reads comments: lines beginning with '#' */
6004: while((c=getc(ficpar))=='#' && c!= EOF){
6005: ungetc(c,ficpar);
6006: fgets(line, MAXLINE, ficpar);
6007: numlinepar++;
1.141 brouard 6008: fputs(line,stdout);
1.126 brouard 6009: fputs(line,ficparo);
6010: fputs(line,ficlog);
6011: }
6012: ungetc(c,ficpar);
6013:
6014: matcov=matrix(1,npar,1,npar);
1.131 brouard 6015: for(i=1; i <=npar; i++)
6016: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6017:
1.126 brouard 6018: for(i=1; i <=npar; i++){
1.145 brouard 6019: fscanf(ficpar,"%s",str);
1.126 brouard 6020: if(mle==1)
6021: printf("%s",str);
6022: fprintf(ficlog,"%s",str);
6023: fprintf(ficparo,"%s",str);
6024: for(j=1; j <=i; j++){
6025: fscanf(ficpar," %le",&matcov[i][j]);
6026: if(mle==1){
6027: printf(" %.5le",matcov[i][j]);
6028: }
6029: fprintf(ficlog," %.5le",matcov[i][j]);
6030: fprintf(ficparo," %.5le",matcov[i][j]);
6031: }
6032: fscanf(ficpar,"\n");
6033: numlinepar++;
6034: if(mle==1)
6035: printf("\n");
6036: fprintf(ficlog,"\n");
6037: fprintf(ficparo,"\n");
6038: }
6039: for(i=1; i <=npar; i++)
6040: for(j=i+1;j<=npar;j++)
6041: matcov[i][j]=matcov[j][i];
6042:
6043: if(mle==1)
6044: printf("\n");
6045: fprintf(ficlog,"\n");
6046:
6047: fflush(ficlog);
6048:
6049: /*-------- Rewriting parameter file ----------*/
6050: strcpy(rfileres,"r"); /* "Rparameterfile */
6051: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6052: strcat(rfileres,"."); /* */
6053: strcat(rfileres,optionfilext); /* Other files have txt extension */
6054: if((ficres =fopen(rfileres,"w"))==NULL) {
6055: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6056: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6057: }
6058: fprintf(ficres,"#%s\n",version);
6059: } /* End of mle != -3 */
6060:
6061:
6062: n= lastobs;
6063: num=lvector(1,n);
6064: moisnais=vector(1,n);
6065: annais=vector(1,n);
6066: moisdc=vector(1,n);
6067: andc=vector(1,n);
6068: agedc=vector(1,n);
6069: cod=ivector(1,n);
6070: weight=vector(1,n);
6071: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6072: mint=matrix(1,maxwav,1,n);
6073: anint=matrix(1,maxwav,1,n);
1.131 brouard 6074: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6075: tab=ivector(1,NCOVMAX);
1.144 brouard 6076: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6077:
1.136 brouard 6078: /* Reads data from file datafile */
6079: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6080: goto end;
6081:
6082: /* Calculation of the number of parameters from char model */
1.137 brouard 6083: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6084: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6085: k=3 V4 Tvar[k=3]= 4 (from V4)
6086: k=2 V1 Tvar[k=2]= 1 (from V1)
6087: k=1 Tvar[1]=2 (from V2)
6088: */
6089: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6090: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6091: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6092: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6093: */
6094: /* For model-covariate k tells which data-covariate to use but
6095: because this model-covariate is a construction we invent a new column
6096: ncovcol + k1
6097: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6098: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6099: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6100: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6101: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6102: */
1.145 brouard 6103: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6104: 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 6105: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6106: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6107: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6108: 4 covariates (3 plus signs)
6109: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6110: */
1.136 brouard 6111:
6112: if(decodemodel(model, lastobs) == 1)
6113: goto end;
6114:
1.137 brouard 6115: if((double)(lastobs-imx)/(double)imx > 1.10){
6116: nbwarn++;
6117: 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);
6118: 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);
6119: }
1.136 brouard 6120: /* if(mle==1){*/
1.137 brouard 6121: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6122: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6123: }
6124:
6125: /*-calculation of age at interview from date of interview and age at death -*/
6126: agev=matrix(1,maxwav,1,imx);
6127:
6128: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6129: goto end;
6130:
1.126 brouard 6131:
1.136 brouard 6132: agegomp=(int)agemin;
6133: free_vector(moisnais,1,n);
6134: free_vector(annais,1,n);
1.126 brouard 6135: /* free_matrix(mint,1,maxwav,1,n);
6136: free_matrix(anint,1,maxwav,1,n);*/
6137: free_vector(moisdc,1,n);
6138: free_vector(andc,1,n);
1.145 brouard 6139: /* */
6140:
1.126 brouard 6141: wav=ivector(1,imx);
6142: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6143: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6144: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6145:
6146: /* Concatenates waves */
6147: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6148: /* */
6149:
1.126 brouard 6150: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6151:
6152: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6153: ncodemax[1]=1;
1.145 brouard 6154: Ndum =ivector(-1,NCOVMAX);
6155: if (ncovmodel > 2)
6156: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6157:
6158: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6159: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6160: h=0;
6161:
6162:
6163: /*if (cptcovn > 0) */
1.126 brouard 6164:
1.145 brouard 6165:
1.126 brouard 6166: m=pow(2,cptcoveff);
6167:
1.131 brouard 6168: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6169: 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 */
6170: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6171: 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 6172: h++;
1.141 brouard 6173: if (h>m)
1.136 brouard 6174: h=1;
1.144 brouard 6175: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6176: * h 1 2 3 4
6177: *______________________________
6178: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6179: * 2 2 1 1 1
6180: * 3 i=2 1 2 1 1
6181: * 4 2 2 1 1
6182: * 5 i=3 1 i=2 1 2 1
6183: * 6 2 1 2 1
6184: * 7 i=4 1 2 2 1
6185: * 8 2 2 2 1
6186: * 9 i=5 1 i=3 1 i=2 1 1
6187: * 10 2 1 1 1
6188: * 11 i=6 1 2 1 1
6189: * 12 2 2 1 1
6190: * 13 i=7 1 i=4 1 2 1
6191: * 14 2 1 2 1
6192: * 15 i=8 1 2 2 1
6193: * 16 2 2 2 1
6194: */
1.141 brouard 6195: codtab[h][k]=j;
1.145 brouard 6196: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6197: 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 6198: }
6199: }
6200: }
6201: }
6202: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6203: codtab[1][2]=1;codtab[2][2]=2; */
6204: /* for(i=1; i <=m ;i++){
6205: for(k=1; k <=cptcovn; k++){
1.131 brouard 6206: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6207: }
6208: printf("\n");
6209: }
6210: scanf("%d",i);*/
1.145 brouard 6211:
6212: free_ivector(Ndum,-1,NCOVMAX);
6213:
6214:
1.126 brouard 6215:
6216: /*------------ gnuplot -------------*/
6217: strcpy(optionfilegnuplot,optionfilefiname);
6218: if(mle==-3)
6219: strcat(optionfilegnuplot,"-mort");
6220: strcat(optionfilegnuplot,".gp");
6221:
6222: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6223: printf("Problem with file %s",optionfilegnuplot);
6224: }
6225: else{
6226: fprintf(ficgp,"\n# %s\n", version);
6227: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6228: //fprintf(ficgp,"set missing 'NaNq'\n");
6229: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6230: }
6231: /* fclose(ficgp);*/
6232: /*--------- index.htm --------*/
6233:
6234: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6235: if(mle==-3)
6236: strcat(optionfilehtm,"-mort");
6237: strcat(optionfilehtm,".htm");
6238: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6239: printf("Problem with %s \n",optionfilehtm);
6240: exit(0);
1.126 brouard 6241: }
6242:
6243: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6244: strcat(optionfilehtmcov,"-cov.htm");
6245: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6246: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6247: }
6248: else{
6249: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6250: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6251: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6252: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6253: }
6254:
6255: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6256: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6257: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6258: \n\
6259: <hr size=\"2\" color=\"#EC5E5E\">\
6260: <ul><li><h4>Parameter files</h4>\n\
6261: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6262: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6263: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6264: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6265: - Date and time at start: %s</ul>\n",\
6266: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6267: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6268: fileres,fileres,\
6269: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6270: fflush(fichtm);
6271:
6272: strcpy(pathr,path);
6273: strcat(pathr,optionfilefiname);
6274: chdir(optionfilefiname); /* Move to directory named optionfile */
6275:
6276: /* Calculates basic frequencies. Computes observed prevalence at single age
6277: and prints on file fileres'p'. */
6278: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6279:
6280: fprintf(fichtm,"\n");
6281: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6282: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6283: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6284: imx,agemin,agemax,jmin,jmax,jmean);
6285: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6286: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6287: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6288: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6289: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6290:
6291:
6292: /* For Powell, parameters are in a vector p[] starting at p[1]
6293: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6294: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6295:
6296: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6297:
6298: if (mle==-3){
1.136 brouard 6299: ximort=matrix(1,NDIM,1,NDIM);
6300: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6301: cens=ivector(1,n);
6302: ageexmed=vector(1,n);
6303: agecens=vector(1,n);
6304: dcwave=ivector(1,n);
6305:
6306: for (i=1; i<=imx; i++){
6307: dcwave[i]=-1;
6308: for (m=firstpass; m<=lastpass; m++)
6309: if (s[m][i]>nlstate) {
6310: dcwave[i]=m;
6311: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6312: break;
6313: }
6314: }
6315:
6316: for (i=1; i<=imx; i++) {
6317: if (wav[i]>0){
6318: ageexmed[i]=agev[mw[1][i]][i];
6319: j=wav[i];
6320: agecens[i]=1.;
6321:
6322: if (ageexmed[i]> 1 && wav[i] > 0){
6323: agecens[i]=agev[mw[j][i]][i];
6324: cens[i]= 1;
6325: }else if (ageexmed[i]< 1)
6326: cens[i]= -1;
6327: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6328: cens[i]=0 ;
6329: }
6330: else cens[i]=-1;
6331: }
6332:
6333: for (i=1;i<=NDIM;i++) {
6334: for (j=1;j<=NDIM;j++)
6335: ximort[i][j]=(i == j ? 1.0 : 0.0);
6336: }
6337:
1.145 brouard 6338: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6339: /*printf("%lf %lf", p[1], p[2]);*/
6340:
6341:
1.136 brouard 6342: #ifdef GSL
6343: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6344: #else
1.126 brouard 6345: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6346: #endif
1.126 brouard 6347: strcpy(filerespow,"pow-mort");
6348: strcat(filerespow,fileres);
6349: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6350: printf("Problem with resultfile: %s\n", filerespow);
6351: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6352: }
1.136 brouard 6353: #ifdef GSL
6354: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6355: #else
1.126 brouard 6356: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6357: #endif
1.126 brouard 6358: /* for (i=1;i<=nlstate;i++)
6359: for(j=1;j<=nlstate+ndeath;j++)
6360: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6361: */
6362: fprintf(ficrespow,"\n");
1.136 brouard 6363: #ifdef GSL
6364: /* gsl starts here */
6365: T = gsl_multimin_fminimizer_nmsimplex;
6366: gsl_multimin_fminimizer *sfm = NULL;
6367: gsl_vector *ss, *x;
6368: gsl_multimin_function minex_func;
6369:
6370: /* Initial vertex size vector */
6371: ss = gsl_vector_alloc (NDIM);
6372:
6373: if (ss == NULL){
6374: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6375: }
6376: /* Set all step sizes to 1 */
6377: gsl_vector_set_all (ss, 0.001);
6378:
6379: /* Starting point */
1.126 brouard 6380:
1.136 brouard 6381: x = gsl_vector_alloc (NDIM);
6382:
6383: if (x == NULL){
6384: gsl_vector_free(ss);
6385: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6386: }
6387:
6388: /* Initialize method and iterate */
6389: /* p[1]=0.0268; p[NDIM]=0.083; */
6390: /* gsl_vector_set(x, 0, 0.0268); */
6391: /* gsl_vector_set(x, 1, 0.083); */
6392: gsl_vector_set(x, 0, p[1]);
6393: gsl_vector_set(x, 1, p[2]);
6394:
6395: minex_func.f = &gompertz_f;
6396: minex_func.n = NDIM;
6397: minex_func.params = (void *)&p; /* ??? */
6398:
6399: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6400: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6401:
6402: printf("Iterations beginning .....\n\n");
6403: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6404:
6405: iteri=0;
6406: while (rval == GSL_CONTINUE){
6407: iteri++;
6408: status = gsl_multimin_fminimizer_iterate(sfm);
6409:
6410: if (status) printf("error: %s\n", gsl_strerror (status));
6411: fflush(0);
6412:
6413: if (status)
6414: break;
6415:
6416: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6417: ssval = gsl_multimin_fminimizer_size (sfm);
6418:
6419: if (rval == GSL_SUCCESS)
6420: printf ("converged to a local maximum at\n");
6421:
6422: printf("%5d ", iteri);
6423: for (it = 0; it < NDIM; it++){
6424: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6425: }
6426: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6427: }
6428:
6429: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6430:
6431: gsl_vector_free(x); /* initial values */
6432: gsl_vector_free(ss); /* inital step size */
6433: for (it=0; it<NDIM; it++){
6434: p[it+1]=gsl_vector_get(sfm->x,it);
6435: fprintf(ficrespow," %.12lf", p[it]);
6436: }
6437: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6438: #endif
6439: #ifdef POWELL
6440: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6441: #endif
1.126 brouard 6442: fclose(ficrespow);
6443:
6444: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6445:
6446: for(i=1; i <=NDIM; i++)
6447: for(j=i+1;j<=NDIM;j++)
6448: matcov[i][j]=matcov[j][i];
6449:
6450: printf("\nCovariance matrix\n ");
6451: for(i=1; i <=NDIM; i++) {
6452: for(j=1;j<=NDIM;j++){
6453: printf("%f ",matcov[i][j]);
6454: }
6455: printf("\n ");
6456: }
6457:
6458: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6459: for (i=1;i<=NDIM;i++)
6460: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6461:
6462: lsurv=vector(1,AGESUP);
6463: lpop=vector(1,AGESUP);
6464: tpop=vector(1,AGESUP);
6465: lsurv[agegomp]=100000;
6466:
6467: for (k=agegomp;k<=AGESUP;k++) {
6468: agemortsup=k;
6469: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6470: }
6471:
6472: for (k=agegomp;k<agemortsup;k++)
6473: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6474:
6475: for (k=agegomp;k<agemortsup;k++){
6476: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6477: sumlpop=sumlpop+lpop[k];
6478: }
6479:
6480: tpop[agegomp]=sumlpop;
6481: for (k=agegomp;k<(agemortsup-3);k++){
6482: /* tpop[k+1]=2;*/
6483: tpop[k+1]=tpop[k]-lpop[k];
6484: }
6485:
6486:
6487: printf("\nAge lx qx dx Lx Tx e(x)\n");
6488: for (k=agegomp;k<(agemortsup-2);k++)
6489: 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]);
6490:
6491:
6492: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6493: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6494:
6495: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6496: stepm, weightopt,\
6497: model,imx,p,matcov,agemortsup);
6498:
6499: free_vector(lsurv,1,AGESUP);
6500: free_vector(lpop,1,AGESUP);
6501: free_vector(tpop,1,AGESUP);
1.136 brouard 6502: #ifdef GSL
6503: free_ivector(cens,1,n);
6504: free_vector(agecens,1,n);
6505: free_ivector(dcwave,1,n);
6506: free_matrix(ximort,1,NDIM,1,NDIM);
6507: #endif
1.126 brouard 6508: } /* Endof if mle==-3 */
6509:
6510: else{ /* For mle >=1 */
1.132 brouard 6511: globpr=0;/* debug */
6512: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6513: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6514: for (k=1; k<=npar;k++)
6515: printf(" %d %8.5f",k,p[k]);
6516: printf("\n");
6517: globpr=1; /* to print the contributions */
6518: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6519: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6520: for (k=1; k<=npar;k++)
6521: printf(" %d %8.5f",k,p[k]);
6522: printf("\n");
6523: if(mle>=1){ /* Could be 1 or 2 */
6524: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6525: }
6526:
6527: /*--------- results files --------------*/
6528: 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);
6529:
6530:
6531: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6532: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6533: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6534: for(i=1,jk=1; i <=nlstate; i++){
6535: for(k=1; k <=(nlstate+ndeath); k++){
6536: if (k != i) {
6537: printf("%d%d ",i,k);
6538: fprintf(ficlog,"%d%d ",i,k);
6539: fprintf(ficres,"%1d%1d ",i,k);
6540: for(j=1; j <=ncovmodel; j++){
6541: printf("%lf ",p[jk]);
6542: fprintf(ficlog,"%lf ",p[jk]);
6543: fprintf(ficres,"%lf ",p[jk]);
6544: jk++;
6545: }
6546: printf("\n");
6547: fprintf(ficlog,"\n");
6548: fprintf(ficres,"\n");
6549: }
6550: }
6551: }
6552: if(mle!=0){
6553: /* Computing hessian and covariance matrix */
6554: ftolhess=ftol; /* Usually correct */
6555: hesscov(matcov, p, npar, delti, ftolhess, func);
6556: }
6557: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6558: printf("# Scales (for hessian or gradient estimation)\n");
6559: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6560: for(i=1,jk=1; i <=nlstate; i++){
6561: for(j=1; j <=nlstate+ndeath; j++){
6562: if (j!=i) {
6563: fprintf(ficres,"%1d%1d",i,j);
6564: printf("%1d%1d",i,j);
6565: fprintf(ficlog,"%1d%1d",i,j);
6566: for(k=1; k<=ncovmodel;k++){
6567: printf(" %.5e",delti[jk]);
6568: fprintf(ficlog," %.5e",delti[jk]);
6569: fprintf(ficres," %.5e",delti[jk]);
6570: jk++;
6571: }
6572: printf("\n");
6573: fprintf(ficlog,"\n");
6574: fprintf(ficres,"\n");
6575: }
6576: }
6577: }
6578:
6579: 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");
6580: if(mle>=1)
6581: 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");
6582: 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");
6583: /* # 121 Var(a12)\n\ */
6584: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6585: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6586: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6587: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6588: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6589: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6590: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6591:
6592:
6593: /* Just to have a covariance matrix which will be more understandable
6594: even is we still don't want to manage dictionary of variables
6595: */
6596: for(itimes=1;itimes<=2;itimes++){
6597: jj=0;
6598: for(i=1; i <=nlstate; i++){
6599: for(j=1; j <=nlstate+ndeath; j++){
6600: if(j==i) continue;
6601: for(k=1; k<=ncovmodel;k++){
6602: jj++;
6603: ca[0]= k+'a'-1;ca[1]='\0';
6604: if(itimes==1){
6605: if(mle>=1)
6606: printf("#%1d%1d%d",i,j,k);
6607: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6608: fprintf(ficres,"#%1d%1d%d",i,j,k);
6609: }else{
6610: if(mle>=1)
6611: printf("%1d%1d%d",i,j,k);
6612: fprintf(ficlog,"%1d%1d%d",i,j,k);
6613: fprintf(ficres,"%1d%1d%d",i,j,k);
6614: }
6615: ll=0;
6616: for(li=1;li <=nlstate; li++){
6617: for(lj=1;lj <=nlstate+ndeath; lj++){
6618: if(lj==li) continue;
6619: for(lk=1;lk<=ncovmodel;lk++){
6620: ll++;
6621: if(ll<=jj){
6622: cb[0]= lk +'a'-1;cb[1]='\0';
6623: if(ll<jj){
6624: if(itimes==1){
6625: if(mle>=1)
6626: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6627: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6628: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6629: }else{
6630: if(mle>=1)
6631: printf(" %.5e",matcov[jj][ll]);
6632: fprintf(ficlog," %.5e",matcov[jj][ll]);
6633: fprintf(ficres," %.5e",matcov[jj][ll]);
6634: }
6635: }else{
6636: if(itimes==1){
6637: if(mle>=1)
6638: printf(" Var(%s%1d%1d)",ca,i,j);
6639: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6640: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6641: }else{
6642: if(mle>=1)
6643: printf(" %.5e",matcov[jj][ll]);
6644: fprintf(ficlog," %.5e",matcov[jj][ll]);
6645: fprintf(ficres," %.5e",matcov[jj][ll]);
6646: }
6647: }
6648: }
6649: } /* end lk */
6650: } /* end lj */
6651: } /* end li */
6652: if(mle>=1)
6653: printf("\n");
6654: fprintf(ficlog,"\n");
6655: fprintf(ficres,"\n");
6656: numlinepar++;
6657: } /* end k*/
6658: } /*end j */
6659: } /* end i */
6660: } /* end itimes */
6661:
6662: fflush(ficlog);
6663: fflush(ficres);
6664:
6665: while((c=getc(ficpar))=='#' && c!= EOF){
6666: ungetc(c,ficpar);
6667: fgets(line, MAXLINE, ficpar);
1.141 brouard 6668: fputs(line,stdout);
1.126 brouard 6669: fputs(line,ficparo);
6670: }
6671: ungetc(c,ficpar);
6672:
6673: estepm=0;
6674: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6675: if (estepm==0 || estepm < stepm) estepm=stepm;
6676: if (fage <= 2) {
6677: bage = ageminpar;
6678: fage = agemaxpar;
6679: }
6680:
6681: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6682: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6683: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6684:
6685: while((c=getc(ficpar))=='#' && c!= EOF){
6686: ungetc(c,ficpar);
6687: fgets(line, MAXLINE, ficpar);
1.141 brouard 6688: fputs(line,stdout);
1.126 brouard 6689: fputs(line,ficparo);
6690: }
6691: ungetc(c,ficpar);
6692:
6693: 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);
6694: 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);
6695: 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);
6696: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6697: 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);
6698:
6699: while((c=getc(ficpar))=='#' && c!= EOF){
6700: ungetc(c,ficpar);
6701: fgets(line, MAXLINE, ficpar);
1.141 brouard 6702: fputs(line,stdout);
1.126 brouard 6703: fputs(line,ficparo);
6704: }
6705: ungetc(c,ficpar);
6706:
6707:
6708: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6709: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6710:
6711: fscanf(ficpar,"pop_based=%d\n",&popbased);
6712: fprintf(ficparo,"pop_based=%d\n",popbased);
6713: fprintf(ficres,"pop_based=%d\n",popbased);
6714:
6715: while((c=getc(ficpar))=='#' && c!= EOF){
6716: ungetc(c,ficpar);
6717: fgets(line, MAXLINE, ficpar);
1.141 brouard 6718: fputs(line,stdout);
1.126 brouard 6719: fputs(line,ficparo);
6720: }
6721: ungetc(c,ficpar);
6722:
6723: 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);
6724: 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);
6725: 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);
6726: 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);
6727: 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);
6728: /* day and month of proj2 are not used but only year anproj2.*/
6729:
6730:
6731:
1.145 brouard 6732: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6733: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6734:
6735: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6736: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6737:
6738: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6739: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6740: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6741:
6742: /*------------ free_vector -------------*/
6743: /* chdir(path); */
6744:
6745: free_ivector(wav,1,imx);
6746: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6747: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6748: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6749: free_lvector(num,1,n);
6750: free_vector(agedc,1,n);
6751: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6752: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6753: fclose(ficparo);
6754: fclose(ficres);
6755:
6756:
6757: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6758: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6759: fclose(ficrespl);
6760:
1.145 brouard 6761: #ifdef FREEEXIT2
6762: #include "freeexit2.h"
6763: #endif
6764:
1.126 brouard 6765: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6766: #include "hpijx.h"
6767: fclose(ficrespij);
1.126 brouard 6768:
1.145 brouard 6769: /*-------------- Variance of one-step probabilities---*/
6770: k=1;
1.126 brouard 6771: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6772:
6773:
6774: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6775: for(i=1;i<=AGESUP;i++)
6776: for(j=1;j<=NCOVMAX;j++)
6777: for(k=1;k<=NCOVMAX;k++)
6778: probs[i][j][k]=0.;
6779:
6780: /*---------- Forecasting ------------------*/
6781: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6782: if(prevfcast==1){
6783: /* if(stepm ==1){*/
6784: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6785: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6786: /* } */
6787: /* else{ */
6788: /* erreur=108; */
6789: /* 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); */
6790: /* 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); */
6791: /* } */
6792: }
6793:
6794:
1.127 brouard 6795: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6796:
6797: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6798: /* 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",\
6799: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6800: */
1.126 brouard 6801:
1.127 brouard 6802: if (mobilav!=0) {
6803: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6804: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6805: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6806: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6807: }
1.126 brouard 6808: }
6809:
6810:
1.127 brouard 6811: /*---------- Health expectancies, no variances ------------*/
6812:
1.126 brouard 6813: strcpy(filerese,"e");
6814: strcat(filerese,fileres);
6815: if((ficreseij=fopen(filerese,"w"))==NULL) {
6816: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6817: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6818: }
6819: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6820: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6821: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6822: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6823:
6824: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6825: fprintf(ficreseij,"\n#****** ");
6826: for(j=1;j<=cptcoveff;j++) {
6827: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6828: }
6829: fprintf(ficreseij,"******\n");
6830:
6831: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6832: oldm=oldms;savm=savms;
6833: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6834:
6835: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6836: /*}*/
1.127 brouard 6837: }
6838: fclose(ficreseij);
6839:
6840:
6841: /*---------- Health expectancies and variances ------------*/
6842:
6843:
6844: strcpy(filerest,"t");
6845: strcat(filerest,fileres);
6846: if((ficrest=fopen(filerest,"w"))==NULL) {
6847: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6848: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6849: }
6850: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6851: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6852:
1.126 brouard 6853:
6854: strcpy(fileresstde,"stde");
6855: strcat(fileresstde,fileres);
6856: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6857: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6858: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6859: }
6860: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6861: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6862:
6863: strcpy(filerescve,"cve");
6864: strcat(filerescve,fileres);
6865: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6866: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6867: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6868: }
6869: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6870: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6871:
6872: strcpy(fileresv,"v");
6873: strcat(fileresv,fileres);
6874: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6875: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6876: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6877: }
6878: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6879: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6880:
1.145 brouard 6881: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6882: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6883:
6884: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6885: fprintf(ficrest,"\n#****** ");
1.126 brouard 6886: for(j=1;j<=cptcoveff;j++)
6887: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6888: fprintf(ficrest,"******\n");
6889:
6890: fprintf(ficresstdeij,"\n#****** ");
6891: fprintf(ficrescveij,"\n#****** ");
6892: for(j=1;j<=cptcoveff;j++) {
6893: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6894: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6895: }
6896: fprintf(ficresstdeij,"******\n");
6897: fprintf(ficrescveij,"******\n");
6898:
6899: fprintf(ficresvij,"\n#****** ");
6900: for(j=1;j<=cptcoveff;j++)
6901: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6902: fprintf(ficresvij,"******\n");
6903:
6904: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6905: oldm=oldms;savm=savms;
1.127 brouard 6906: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6907: /*
6908: */
6909: /* goto endfree; */
1.126 brouard 6910:
6911: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6912: pstamp(ficrest);
1.145 brouard 6913:
6914:
1.128 brouard 6915: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6916: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6917: cptcod= 0; /* To be deleted */
6918: 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 6919: 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 6920: if(vpopbased==1)
6921: 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);
6922: else
6923: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6924: fprintf(ficrest,"# Age e.. (std) ");
6925: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6926: fprintf(ficrest,"\n");
1.126 brouard 6927:
1.128 brouard 6928: epj=vector(1,nlstate+1);
6929: for(age=bage; age <=fage ;age++){
6930: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6931: if (vpopbased==1) {
6932: if(mobilav ==0){
6933: for(i=1; i<=nlstate;i++)
6934: prlim[i][i]=probs[(int)age][i][k];
6935: }else{ /* mobilav */
6936: for(i=1; i<=nlstate;i++)
6937: prlim[i][i]=mobaverage[(int)age][i][k];
6938: }
1.126 brouard 6939: }
6940:
1.128 brouard 6941: fprintf(ficrest," %4.0f",age);
6942: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6943: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6944: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6945: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6946: }
6947: epj[nlstate+1] +=epj[j];
1.126 brouard 6948: }
6949:
1.128 brouard 6950: for(i=1, vepp=0.;i <=nlstate;i++)
6951: for(j=1;j <=nlstate;j++)
6952: vepp += vareij[i][j][(int)age];
6953: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6954: for(j=1;j <=nlstate;j++){
6955: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6956: }
6957: fprintf(ficrest,"\n");
1.126 brouard 6958: }
6959: }
6960: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6961: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6962: free_vector(epj,1,nlstate+1);
1.145 brouard 6963: /*}*/
1.126 brouard 6964: }
6965: free_vector(weight,1,n);
1.145 brouard 6966: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6967: free_imatrix(s,1,maxwav+1,1,n);
6968: free_matrix(anint,1,maxwav,1,n);
6969: free_matrix(mint,1,maxwav,1,n);
6970: free_ivector(cod,1,n);
6971: free_ivector(tab,1,NCOVMAX);
6972: fclose(ficresstdeij);
6973: fclose(ficrescveij);
6974: fclose(ficresvij);
6975: fclose(ficrest);
6976: fclose(ficpar);
6977:
6978: /*------- Variance of period (stable) prevalence------*/
6979:
6980: strcpy(fileresvpl,"vpl");
6981: strcat(fileresvpl,fileres);
6982: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6983: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6984: exit(0);
6985: }
6986: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6987:
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++){
6992: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6993: for(j=1;j<=cptcoveff;j++)
6994: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6995: fprintf(ficresvpl,"******\n");
6996:
6997: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6998: oldm=oldms;savm=savms;
6999: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7000: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7001: /*}*/
1.126 brouard 7002: }
7003:
7004: fclose(ficresvpl);
7005:
7006: /*---------- End : free ----------------*/
7007: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7008: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7009: } /* mle==-3 arrives here for freeing */
1.164 brouard 7010: /* endfree:*/
1.141 brouard 7011: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7012: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7013: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7014: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7015: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7016: free_matrix(covar,0,NCOVMAX,1,n);
7017: free_matrix(matcov,1,npar,1,npar);
7018: /*free_vector(delti,1,npar);*/
7019: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7020: free_matrix(agev,1,maxwav,1,imx);
7021: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7022:
1.145 brouard 7023: free_ivector(ncodemax,1,NCOVMAX);
7024: free_ivector(Tvar,1,NCOVMAX);
7025: free_ivector(Tprod,1,NCOVMAX);
7026: free_ivector(Tvaraff,1,NCOVMAX);
7027: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7028:
7029: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7030: free_imatrix(codtab,1,100,1,10);
7031: fflush(fichtm);
7032: fflush(ficgp);
7033:
7034:
7035: if((nberr >0) || (nbwarn>0)){
7036: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7037: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7038: }else{
7039: printf("End of Imach\n");
7040: fprintf(ficlog,"End of Imach\n");
7041: }
7042: printf("See log file on %s\n",filelog);
7043: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7044: /*(void) gettimeofday(&end_time,&tzp);*/
7045: rend_time = time(NULL);
7046: end_time = *localtime(&rend_time);
7047: /* tml = *localtime(&end_time.tm_sec); */
7048: strcpy(strtend,asctime(&end_time));
1.126 brouard 7049: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7050: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7051: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7052:
1.157 brouard 7053: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7054: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7055: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7056: /* printf("Total time was %d uSec.\n", total_usecs);*/
7057: /* if(fileappend(fichtm,optionfilehtm)){ */
7058: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7059: fclose(fichtm);
7060: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7061: fclose(fichtmcov);
7062: fclose(ficgp);
7063: fclose(ficlog);
7064: /*------ End -----------*/
7065:
7066:
7067: printf("Before Current directory %s!\n",pathcd);
7068: if(chdir(pathcd) != 0)
7069: printf("Can't move to directory %s!\n",path);
7070: if(getcwd(pathcd,MAXLINE) > 0)
7071: printf("Current directory %s!\n",pathcd);
7072: /*strcat(plotcmd,CHARSEPARATOR);*/
7073: sprintf(plotcmd,"gnuplot");
1.157 brouard 7074: #ifdef _WIN32
1.126 brouard 7075: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7076: #endif
7077: if(!stat(plotcmd,&info)){
1.158 brouard 7078: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7079: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7080: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7081: }else
7082: strcpy(pplotcmd,plotcmd);
1.157 brouard 7083: #ifdef __unix
1.126 brouard 7084: strcpy(plotcmd,GNUPLOTPROGRAM);
7085: if(!stat(plotcmd,&info)){
1.158 brouard 7086: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7087: }else
7088: strcpy(pplotcmd,plotcmd);
7089: #endif
7090: }else
7091: strcpy(pplotcmd,plotcmd);
7092:
7093: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7094: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7095:
7096: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7097: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7098: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7099: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7100: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7101: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7102: }
1.158 brouard 7103: printf(" Successful, please wait...");
1.126 brouard 7104: while (z[0] != 'q') {
7105: /* chdir(path); */
1.154 brouard 7106: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7107: scanf("%s",z);
7108: /* if (z[0] == 'c') system("./imach"); */
7109: if (z[0] == 'e') {
1.158 brouard 7110: #ifdef __APPLE__
1.152 brouard 7111: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7112: #elif __linux
7113: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7114: #else
1.152 brouard 7115: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7116: #endif
7117: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7118: system(pplotcmd);
1.126 brouard 7119: }
7120: else if (z[0] == 'g') system(plotcmd);
7121: else if (z[0] == 'q') exit(0);
7122: }
7123: end:
7124: while (z[0] != 'q') {
7125: printf("\nType q for exiting: ");
7126: scanf("%s",z);
7127: }
7128: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>