Annotation of imach/src/imach.c, revision 1.183
1.183 ! brouard 1: /* $Id: imach.c,v 1.182 2015/02/12 08:19:57 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.183 ! brouard 4: Revision 1.182 2015/02/12 08:19:57 brouard
! 5: Summary: Trying to keep directest which seems simpler and more general
! 6: Author: Nicolas Brouard
! 7:
1.182 brouard 8: Revision 1.181 2015/02/11 23:22:24 brouard
9: Summary: Comments on Powell added
10:
11: Author:
12:
1.181 brouard 13: Revision 1.180 2015/02/11 17:33:45 brouard
14: Summary: Finishing move from main to function (hpijx and prevalence_limit)
15:
1.180 brouard 16: Revision 1.179 2015/01/04 09:57:06 brouard
17: Summary: back to OS/X
18:
1.179 brouard 19: Revision 1.178 2015/01/04 09:35:48 brouard
20: *** empty log message ***
21:
1.178 brouard 22: Revision 1.177 2015/01/03 18:40:56 brouard
23: Summary: Still testing ilc32 on OSX
24:
1.177 brouard 25: Revision 1.176 2015/01/03 16:45:04 brouard
26: *** empty log message ***
27:
1.176 brouard 28: Revision 1.175 2015/01/03 16:33:42 brouard
29: *** empty log message ***
30:
1.175 brouard 31: Revision 1.174 2015/01/03 16:15:49 brouard
32: Summary: Still in cross-compilation
33:
1.174 brouard 34: Revision 1.173 2015/01/03 12:06:26 brouard
35: Summary: trying to detect cross-compilation
36:
1.173 brouard 37: Revision 1.172 2014/12/27 12:07:47 brouard
38: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
39:
1.172 brouard 40: Revision 1.171 2014/12/23 13:26:59 brouard
41: Summary: Back from Visual C
42:
43: Still problem with utsname.h on Windows
44:
1.171 brouard 45: Revision 1.170 2014/12/23 11:17:12 brouard
46: Summary: Cleaning some \%% back to %%
47:
48: The escape was mandatory for a specific compiler (which one?), but too many warnings.
49:
1.170 brouard 50: Revision 1.169 2014/12/22 23:08:31 brouard
51: Summary: 0.98p
52:
53: Outputs some informations on compiler used, OS etc. Testing on different platforms.
54:
1.169 brouard 55: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 56: Summary: update
1.169 brouard 57:
1.168 brouard 58: Revision 1.167 2014/12/22 13:50:56 brouard
59: Summary: Testing uname and compiler version and if compiled 32 or 64
60:
61: Testing on Linux 64
62:
1.167 brouard 63: Revision 1.166 2014/12/22 11:40:47 brouard
64: *** empty log message ***
65:
1.166 brouard 66: Revision 1.165 2014/12/16 11:20:36 brouard
67: Summary: After compiling on Visual C
68:
69: * imach.c (Module): Merging 1.61 to 1.162
70:
1.165 brouard 71: Revision 1.164 2014/12/16 10:52:11 brouard
72: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
73:
74: * imach.c (Module): Merging 1.61 to 1.162
75:
1.164 brouard 76: Revision 1.163 2014/12/16 10:30:11 brouard
77: * imach.c (Module): Merging 1.61 to 1.162
78:
1.163 brouard 79: Revision 1.162 2014/09/25 11:43:39 brouard
80: Summary: temporary backup 0.99!
81:
1.162 brouard 82: Revision 1.1 2014/09/16 11:06:58 brouard
83: Summary: With some code (wrong) for nlopt
84:
85: Author:
86:
87: Revision 1.161 2014/09/15 20:41:41 brouard
88: Summary: Problem with macro SQR on Intel compiler
89:
1.161 brouard 90: Revision 1.160 2014/09/02 09:24:05 brouard
91: *** empty log message ***
92:
1.160 brouard 93: Revision 1.159 2014/09/01 10:34:10 brouard
94: Summary: WIN32
95: Author: Brouard
96:
1.159 brouard 97: Revision 1.158 2014/08/27 17:11:51 brouard
98: *** empty log message ***
99:
1.158 brouard 100: Revision 1.157 2014/08/27 16:26:55 brouard
101: Summary: Preparing windows Visual studio version
102: Author: Brouard
103:
104: In order to compile on Visual studio, time.h is now correct and time_t
105: and tm struct should be used. difftime should be used but sometimes I
106: just make the differences in raw time format (time(&now).
107: Trying to suppress #ifdef LINUX
108: Add xdg-open for __linux in order to open default browser.
109:
1.157 brouard 110: Revision 1.156 2014/08/25 20:10:10 brouard
111: *** empty log message ***
112:
1.156 brouard 113: Revision 1.155 2014/08/25 18:32:34 brouard
114: Summary: New compile, minor changes
115: Author: Brouard
116:
1.155 brouard 117: Revision 1.154 2014/06/20 17:32:08 brouard
118: Summary: Outputs now all graphs of convergence to period prevalence
119:
1.154 brouard 120: Revision 1.153 2014/06/20 16:45:46 brouard
121: Summary: If 3 live state, convergence to period prevalence on same graph
122: Author: Brouard
123:
1.153 brouard 124: Revision 1.152 2014/06/18 17:54:09 brouard
125: Summary: open browser, use gnuplot on same dir than imach if not found in the path
126:
1.152 brouard 127: Revision 1.151 2014/06/18 16:43:30 brouard
128: *** empty log message ***
129:
1.151 brouard 130: Revision 1.150 2014/06/18 16:42:35 brouard
131: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
132: Author: brouard
133:
1.150 brouard 134: Revision 1.149 2014/06/18 15:51:14 brouard
135: Summary: Some fixes in parameter files errors
136: Author: Nicolas Brouard
137:
1.149 brouard 138: Revision 1.148 2014/06/17 17:38:48 brouard
139: Summary: Nothing new
140: Author: Brouard
141:
142: Just a new packaging for OS/X version 0.98nS
143:
1.148 brouard 144: Revision 1.147 2014/06/16 10:33:11 brouard
145: *** empty log message ***
146:
1.147 brouard 147: Revision 1.146 2014/06/16 10:20:28 brouard
148: Summary: Merge
149: Author: Brouard
150:
151: Merge, before building revised version.
152:
1.146 brouard 153: Revision 1.145 2014/06/10 21:23:15 brouard
154: Summary: Debugging with valgrind
155: Author: Nicolas Brouard
156:
157: Lot of changes in order to output the results with some covariates
158: After the Edimburgh REVES conference 2014, it seems mandatory to
159: improve the code.
160: No more memory valgrind error but a lot has to be done in order to
161: continue the work of splitting the code into subroutines.
162: Also, decodemodel has been improved. Tricode is still not
163: optimal. nbcode should be improved. Documentation has been added in
164: the source code.
165:
1.144 brouard 166: Revision 1.143 2014/01/26 09:45:38 brouard
167: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
168:
169: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
170: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
171:
1.143 brouard 172: Revision 1.142 2014/01/26 03:57:36 brouard
173: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
174:
175: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
176:
1.142 brouard 177: Revision 1.141 2014/01/26 02:42:01 brouard
178: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
179:
1.141 brouard 180: Revision 1.140 2011/09/02 10:37:54 brouard
181: Summary: times.h is ok with mingw32 now.
182:
1.140 brouard 183: Revision 1.139 2010/06/14 07:50:17 brouard
184: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
185: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
186:
1.139 brouard 187: Revision 1.138 2010/04/30 18:19:40 brouard
188: *** empty log message ***
189:
1.138 brouard 190: Revision 1.137 2010/04/29 18:11:38 brouard
191: (Module): Checking covariates for more complex models
192: than V1+V2. A lot of change to be done. Unstable.
193:
1.137 brouard 194: Revision 1.136 2010/04/26 20:30:53 brouard
195: (Module): merging some libgsl code. Fixing computation
196: of likelione (using inter/intrapolation if mle = 0) in order to
197: get same likelihood as if mle=1.
198: Some cleaning of code and comments added.
199:
1.136 brouard 200: Revision 1.135 2009/10/29 15:33:14 brouard
201: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
202:
1.135 brouard 203: Revision 1.134 2009/10/29 13:18:53 brouard
204: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
205:
1.134 brouard 206: Revision 1.133 2009/07/06 10:21:25 brouard
207: just nforces
208:
1.133 brouard 209: Revision 1.132 2009/07/06 08:22:05 brouard
210: Many tings
211:
1.132 brouard 212: Revision 1.131 2009/06/20 16:22:47 brouard
213: Some dimensions resccaled
214:
1.131 brouard 215: Revision 1.130 2009/05/26 06:44:34 brouard
216: (Module): Max Covariate is now set to 20 instead of 8. A
217: lot of cleaning with variables initialized to 0. Trying to make
218: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
219:
1.130 brouard 220: Revision 1.129 2007/08/31 13:49:27 lievre
221: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
222:
1.129 lievre 223: Revision 1.128 2006/06/30 13:02:05 brouard
224: (Module): Clarifications on computing e.j
225:
1.128 brouard 226: Revision 1.127 2006/04/28 18:11:50 brouard
227: (Module): Yes the sum of survivors was wrong since
228: imach-114 because nhstepm was no more computed in the age
229: loop. Now we define nhstepma in the age loop.
230: (Module): In order to speed up (in case of numerous covariates) we
231: compute health expectancies (without variances) in a first step
232: and then all the health expectancies with variances or standard
233: deviation (needs data from the Hessian matrices) which slows the
234: computation.
235: In the future we should be able to stop the program is only health
236: expectancies and graph are needed without standard deviations.
237:
1.127 brouard 238: Revision 1.126 2006/04/28 17:23:28 brouard
239: (Module): Yes the sum of survivors was wrong since
240: imach-114 because nhstepm was no more computed in the age
241: loop. Now we define nhstepma in the age loop.
242: Version 0.98h
243:
1.126 brouard 244: Revision 1.125 2006/04/04 15:20:31 lievre
245: Errors in calculation of health expectancies. Age was not initialized.
246: Forecasting file added.
247:
248: Revision 1.124 2006/03/22 17:13:53 lievre
249: Parameters are printed with %lf instead of %f (more numbers after the comma).
250: The log-likelihood is printed in the log file
251:
252: Revision 1.123 2006/03/20 10:52:43 brouard
253: * imach.c (Module): <title> changed, corresponds to .htm file
254: name. <head> headers where missing.
255:
256: * imach.c (Module): Weights can have a decimal point as for
257: English (a comma might work with a correct LC_NUMERIC environment,
258: otherwise the weight is truncated).
259: Modification of warning when the covariates values are not 0 or
260: 1.
261: Version 0.98g
262:
263: Revision 1.122 2006/03/20 09:45:41 brouard
264: (Module): Weights can have a decimal point as for
265: English (a comma might work with a correct LC_NUMERIC environment,
266: otherwise the weight is truncated).
267: Modification of warning when the covariates values are not 0 or
268: 1.
269: Version 0.98g
270:
271: Revision 1.121 2006/03/16 17:45:01 lievre
272: * imach.c (Module): Comments concerning covariates added
273:
274: * imach.c (Module): refinements in the computation of lli if
275: status=-2 in order to have more reliable computation if stepm is
276: not 1 month. Version 0.98f
277:
278: Revision 1.120 2006/03/16 15:10:38 lievre
279: (Module): refinements in the computation of lli if
280: status=-2 in order to have more reliable computation if stepm is
281: not 1 month. Version 0.98f
282:
283: Revision 1.119 2006/03/15 17:42:26 brouard
284: (Module): Bug if status = -2, the loglikelihood was
285: computed as likelihood omitting the logarithm. Version O.98e
286:
287: Revision 1.118 2006/03/14 18:20:07 brouard
288: (Module): varevsij Comments added explaining the second
289: table of variances if popbased=1 .
290: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
291: (Module): Function pstamp added
292: (Module): Version 0.98d
293:
294: Revision 1.117 2006/03/14 17:16:22 brouard
295: (Module): varevsij Comments added explaining the second
296: table of variances if popbased=1 .
297: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
298: (Module): Function pstamp added
299: (Module): Version 0.98d
300:
301: Revision 1.116 2006/03/06 10:29:27 brouard
302: (Module): Variance-covariance wrong links and
303: varian-covariance of ej. is needed (Saito).
304:
305: Revision 1.115 2006/02/27 12:17:45 brouard
306: (Module): One freematrix added in mlikeli! 0.98c
307:
308: Revision 1.114 2006/02/26 12:57:58 brouard
309: (Module): Some improvements in processing parameter
310: filename with strsep.
311:
312: Revision 1.113 2006/02/24 14:20:24 brouard
313: (Module): Memory leaks checks with valgrind and:
314: datafile was not closed, some imatrix were not freed and on matrix
315: allocation too.
316:
317: Revision 1.112 2006/01/30 09:55:26 brouard
318: (Module): Back to gnuplot.exe instead of wgnuplot.exe
319:
320: Revision 1.111 2006/01/25 20:38:18 brouard
321: (Module): Lots of cleaning and bugs added (Gompertz)
322: (Module): Comments can be added in data file. Missing date values
323: can be a simple dot '.'.
324:
325: Revision 1.110 2006/01/25 00:51:50 brouard
326: (Module): Lots of cleaning and bugs added (Gompertz)
327:
328: Revision 1.109 2006/01/24 19:37:15 brouard
329: (Module): Comments (lines starting with a #) are allowed in data.
330:
331: Revision 1.108 2006/01/19 18:05:42 lievre
332: Gnuplot problem appeared...
333: To be fixed
334:
335: Revision 1.107 2006/01/19 16:20:37 brouard
336: Test existence of gnuplot in imach path
337:
338: Revision 1.106 2006/01/19 13:24:36 brouard
339: Some cleaning and links added in html output
340:
341: Revision 1.105 2006/01/05 20:23:19 lievre
342: *** empty log message ***
343:
344: Revision 1.104 2005/09/30 16:11:43 lievre
345: (Module): sump fixed, loop imx fixed, and simplifications.
346: (Module): If the status is missing at the last wave but we know
347: that the person is alive, then we can code his/her status as -2
348: (instead of missing=-1 in earlier versions) and his/her
349: contributions to the likelihood is 1 - Prob of dying from last
350: health status (= 1-p13= p11+p12 in the easiest case of somebody in
351: the healthy state at last known wave). Version is 0.98
352:
353: Revision 1.103 2005/09/30 15:54:49 lievre
354: (Module): sump fixed, loop imx fixed, and simplifications.
355:
356: Revision 1.102 2004/09/15 17:31:30 brouard
357: Add the possibility to read data file including tab characters.
358:
359: Revision 1.101 2004/09/15 10:38:38 brouard
360: Fix on curr_time
361:
362: Revision 1.100 2004/07/12 18:29:06 brouard
363: Add version for Mac OS X. Just define UNIX in Makefile
364:
365: Revision 1.99 2004/06/05 08:57:40 brouard
366: *** empty log message ***
367:
368: Revision 1.98 2004/05/16 15:05:56 brouard
369: New version 0.97 . First attempt to estimate force of mortality
370: directly from the data i.e. without the need of knowing the health
371: state at each age, but using a Gompertz model: log u =a + b*age .
372: This is the basic analysis of mortality and should be done before any
373: other analysis, in order to test if the mortality estimated from the
374: cross-longitudinal survey is different from the mortality estimated
375: from other sources like vital statistic data.
376:
377: The same imach parameter file can be used but the option for mle should be -3.
378:
1.133 brouard 379: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 380: former routines in order to include the new code within the former code.
381:
382: The output is very simple: only an estimate of the intercept and of
383: the slope with 95% confident intervals.
384:
385: Current limitations:
386: A) Even if you enter covariates, i.e. with the
387: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
388: B) There is no computation of Life Expectancy nor Life Table.
389:
390: Revision 1.97 2004/02/20 13:25:42 lievre
391: Version 0.96d. Population forecasting command line is (temporarily)
392: suppressed.
393:
394: Revision 1.96 2003/07/15 15:38:55 brouard
395: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
396: rewritten within the same printf. Workaround: many printfs.
397:
398: Revision 1.95 2003/07/08 07:54:34 brouard
399: * imach.c (Repository):
400: (Repository): Using imachwizard code to output a more meaningful covariance
401: matrix (cov(a12,c31) instead of numbers.
402:
403: Revision 1.94 2003/06/27 13:00:02 brouard
404: Just cleaning
405:
406: Revision 1.93 2003/06/25 16:33:55 brouard
407: (Module): On windows (cygwin) function asctime_r doesn't
408: exist so I changed back to asctime which exists.
409: (Module): Version 0.96b
410:
411: Revision 1.92 2003/06/25 16:30:45 brouard
412: (Module): On windows (cygwin) function asctime_r doesn't
413: exist so I changed back to asctime which exists.
414:
415: Revision 1.91 2003/06/25 15:30:29 brouard
416: * imach.c (Repository): Duplicated warning errors corrected.
417: (Repository): Elapsed time after each iteration is now output. It
418: helps to forecast when convergence will be reached. Elapsed time
419: is stamped in powell. We created a new html file for the graphs
420: concerning matrix of covariance. It has extension -cov.htm.
421:
422: Revision 1.90 2003/06/24 12:34:15 brouard
423: (Module): Some bugs corrected for windows. Also, when
424: mle=-1 a template is output in file "or"mypar.txt with the design
425: of the covariance matrix to be input.
426:
427: Revision 1.89 2003/06/24 12:30:52 brouard
428: (Module): Some bugs corrected for windows. Also, when
429: mle=-1 a template is output in file "or"mypar.txt with the design
430: of the covariance matrix to be input.
431:
432: Revision 1.88 2003/06/23 17:54:56 brouard
433: * 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.
434:
435: Revision 1.87 2003/06/18 12:26:01 brouard
436: Version 0.96
437:
438: Revision 1.86 2003/06/17 20:04:08 brouard
439: (Module): Change position of html and gnuplot routines and added
440: routine fileappend.
441:
442: Revision 1.85 2003/06/17 13:12:43 brouard
443: * imach.c (Repository): Check when date of death was earlier that
444: current date of interview. It may happen when the death was just
445: prior to the death. In this case, dh was negative and likelihood
446: was wrong (infinity). We still send an "Error" but patch by
447: assuming that the date of death was just one stepm after the
448: interview.
449: (Repository): Because some people have very long ID (first column)
450: we changed int to long in num[] and we added a new lvector for
451: memory allocation. But we also truncated to 8 characters (left
452: truncation)
453: (Repository): No more line truncation errors.
454:
455: Revision 1.84 2003/06/13 21:44:43 brouard
456: * imach.c (Repository): Replace "freqsummary" at a correct
457: place. It differs from routine "prevalence" which may be called
458: many times. Probs is memory consuming and must be used with
459: parcimony.
460: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
461:
462: Revision 1.83 2003/06/10 13:39:11 lievre
463: *** empty log message ***
464:
465: Revision 1.82 2003/06/05 15:57:20 brouard
466: Add log in imach.c and fullversion number is now printed.
467:
468: */
469: /*
470: Interpolated Markov Chain
471:
472: Short summary of the programme:
473:
474: This program computes Healthy Life Expectancies from
475: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
476: first survey ("cross") where individuals from different ages are
477: interviewed on their health status or degree of disability (in the
478: case of a health survey which is our main interest) -2- at least a
479: second wave of interviews ("longitudinal") which measure each change
480: (if any) in individual health status. Health expectancies are
481: computed from the time spent in each health state according to a
482: model. More health states you consider, more time is necessary to reach the
483: Maximum Likelihood of the parameters involved in the model. The
484: simplest model is the multinomial logistic model where pij is the
485: probability to be observed in state j at the second wave
486: conditional to be observed in state i at the first wave. Therefore
487: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
488: 'age' is age and 'sex' is a covariate. If you want to have a more
489: complex model than "constant and age", you should modify the program
490: where the markup *Covariates have to be included here again* invites
491: you to do it. More covariates you add, slower the
492: convergence.
493:
494: The advantage of this computer programme, compared to a simple
495: multinomial logistic model, is clear when the delay between waves is not
496: identical for each individual. Also, if a individual missed an
497: intermediate interview, the information is lost, but taken into
498: account using an interpolation or extrapolation.
499:
500: hPijx is the probability to be observed in state i at age x+h
501: conditional to the observed state i at age x. The delay 'h' can be
502: split into an exact number (nh*stepm) of unobserved intermediate
503: states. This elementary transition (by month, quarter,
504: semester or year) is modelled as a multinomial logistic. The hPx
505: matrix is simply the matrix product of nh*stepm elementary matrices
506: and the contribution of each individual to the likelihood is simply
507: hPijx.
508:
509: Also this programme outputs the covariance matrix of the parameters but also
510: of the life expectancies. It also computes the period (stable) prevalence.
511:
1.133 brouard 512: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
513: Institut national d'études démographiques, Paris.
1.126 brouard 514: This software have been partly granted by Euro-REVES, a concerted action
515: from the European Union.
516: It is copyrighted identically to a GNU software product, ie programme and
517: software can be distributed freely for non commercial use. Latest version
518: can be accessed at http://euroreves.ined.fr/imach .
519:
520: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
521: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
522:
523: **********************************************************************/
524: /*
525: main
526: read parameterfile
527: read datafile
528: concatwav
529: freqsummary
530: if (mle >= 1)
531: mlikeli
532: print results files
533: if mle==1
534: computes hessian
535: read end of parameter file: agemin, agemax, bage, fage, estepm
536: begin-prev-date,...
537: open gnuplot file
538: open html file
1.145 brouard 539: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
540: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
541: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
542: freexexit2 possible for memory heap.
543:
544: h Pij x | pij_nom ficrestpij
545: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
546: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
547: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
548:
549: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
550: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
551: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
552: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
553: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
554:
1.126 brouard 555: forecasting if prevfcast==1 prevforecast call prevalence()
556: health expectancies
557: Variance-covariance of DFLE
558: prevalence()
559: movingaverage()
560: varevsij()
561: if popbased==1 varevsij(,popbased)
562: total life expectancies
563: Variance of period (stable) prevalence
564: end
565: */
566:
1.165 brouard 567: #define POWELL /* Instead of NLOPT */
1.183 ! brouard 568: /* #define POWELLORIGINAL */ /* Don't use Directest to decide new direction but original Powell test */
1.126 brouard 569:
570: #include <math.h>
571: #include <stdio.h>
572: #include <stdlib.h>
573: #include <string.h>
1.159 brouard 574:
575: #ifdef _WIN32
576: #include <io.h>
1.172 brouard 577: #include <windows.h>
578: #include <tchar.h>
1.159 brouard 579: #else
1.126 brouard 580: #include <unistd.h>
1.159 brouard 581: #endif
1.126 brouard 582:
583: #include <limits.h>
584: #include <sys/types.h>
1.171 brouard 585:
586: #if defined(__GNUC__)
587: #include <sys/utsname.h> /* Doesn't work on Windows */
588: #endif
589:
1.126 brouard 590: #include <sys/stat.h>
591: #include <errno.h>
1.159 brouard 592: /* extern int errno; */
1.126 brouard 593:
1.157 brouard 594: /* #ifdef LINUX */
595: /* #include <time.h> */
596: /* #include "timeval.h" */
597: /* #else */
598: /* #include <sys/time.h> */
599: /* #endif */
600:
1.126 brouard 601: #include <time.h>
602:
1.136 brouard 603: #ifdef GSL
604: #include <gsl/gsl_errno.h>
605: #include <gsl/gsl_multimin.h>
606: #endif
607:
1.167 brouard 608:
1.162 brouard 609: #ifdef NLOPT
610: #include <nlopt.h>
611: typedef struct {
612: double (* function)(double [] );
613: } myfunc_data ;
614: #endif
615:
1.126 brouard 616: /* #include <libintl.h> */
617: /* #define _(String) gettext (String) */
618:
1.141 brouard 619: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 620:
621: #define GNUPLOTPROGRAM "gnuplot"
622: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
623: #define FILENAMELENGTH 132
624:
625: #define GLOCK_ERROR_NOPATH -1 /* empty path */
626: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
627:
1.144 brouard 628: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
629: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 630:
631: #define NINTERVMAX 8
1.144 brouard 632: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
633: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
634: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 635: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 636: #define MAXN 20000
1.144 brouard 637: #define YEARM 12. /**< Number of months per year */
1.126 brouard 638: #define AGESUP 130
639: #define AGEBASE 40
1.164 brouard 640: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 641: #ifdef _WIN32
642: #define DIRSEPARATOR '\\'
643: #define CHARSEPARATOR "\\"
644: #define ODIRSEPARATOR '/'
645: #else
1.126 brouard 646: #define DIRSEPARATOR '/'
647: #define CHARSEPARATOR "/"
648: #define ODIRSEPARATOR '\\'
649: #endif
650:
1.183 ! brouard 651: /* $Id: imach.c,v 1.182 2015/02/12 08:19:57 brouard Exp $ */
1.126 brouard 652: /* $State: Exp $ */
653:
1.183 ! brouard 654: char version[]="Imach version 0.98q0, March 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
! 655: char fullversion[]="$Revision: 1.182 $ $Date: 2015/02/12 08:19:57 $";
1.126 brouard 656: char strstart[80];
657: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 658: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 659: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 660: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
661: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
662: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
663: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
664: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
665: int cptcovprodnoage=0; /**< Number of covariate products without age */
666: int cptcoveff=0; /* Total number of covariates to vary for printing results */
667: int cptcov=0; /* Working variable */
1.126 brouard 668: int npar=NPARMAX;
669: int nlstate=2; /* Number of live states */
670: int ndeath=1; /* Number of dead states */
1.130 brouard 671: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 672: int popbased=0;
673:
674: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 675: int maxwav=0; /* Maxim number of waves */
676: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
677: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
678: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 679: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 680: int mle=1, weightopt=0;
1.126 brouard 681: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
682: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
683: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
684: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 685: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 686: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 687: double **matprod2(); /* test */
1.126 brouard 688: double **oldm, **newm, **savm; /* Working pointers to matrices */
689: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 690: /*FILE *fic ; */ /* Used in readdata only */
691: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 692: FILE *ficlog, *ficrespow;
1.130 brouard 693: int globpr=0; /* Global variable for printing or not */
1.126 brouard 694: double fretone; /* Only one call to likelihood */
1.130 brouard 695: long ipmx=0; /* Number of contributions */
1.126 brouard 696: double sw; /* Sum of weights */
697: char filerespow[FILENAMELENGTH];
698: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
699: FILE *ficresilk;
700: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
701: FILE *ficresprobmorprev;
702: FILE *fichtm, *fichtmcov; /* Html File */
703: FILE *ficreseij;
704: char filerese[FILENAMELENGTH];
705: FILE *ficresstdeij;
706: char fileresstde[FILENAMELENGTH];
707: FILE *ficrescveij;
708: char filerescve[FILENAMELENGTH];
709: FILE *ficresvij;
710: char fileresv[FILENAMELENGTH];
711: FILE *ficresvpl;
712: char fileresvpl[FILENAMELENGTH];
713: char title[MAXLINE];
714: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
715: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
716: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
717: char command[FILENAMELENGTH];
718: int outcmd=0;
719:
720: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
721:
722: char filelog[FILENAMELENGTH]; /* Log file */
723: char filerest[FILENAMELENGTH];
724: char fileregp[FILENAMELENGTH];
725: char popfile[FILENAMELENGTH];
726:
727: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
728:
1.157 brouard 729: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
730: /* struct timezone tzp; */
731: /* extern int gettimeofday(); */
732: struct tm tml, *gmtime(), *localtime();
733:
734: extern time_t time();
735:
736: struct tm start_time, end_time, curr_time, last_time, forecast_time;
737: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
738: struct tm tm;
739:
1.126 brouard 740: char strcurr[80], strfor[80];
741:
742: char *endptr;
743: long lval;
744: double dval;
745:
746: #define NR_END 1
747: #define FREE_ARG char*
748: #define FTOL 1.0e-10
749:
750: #define NRANSI
751: #define ITMAX 200
752:
753: #define TOL 2.0e-4
754:
755: #define CGOLD 0.3819660
756: #define ZEPS 1.0e-10
757: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
758:
759: #define GOLD 1.618034
760: #define GLIMIT 100.0
761: #define TINY 1.0e-20
762:
763: static double maxarg1,maxarg2;
764: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
765: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
766:
767: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
768: #define rint(a) floor(a+0.5)
1.166 brouard 769: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 ! brouard 770: #define mytinydouble 1.0e-16
1.166 brouard 771: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
772: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
773: /* static double dsqrarg; */
774: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 775: static double sqrarg;
776: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
777: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
778: int agegomp= AGEGOMP;
779:
780: int imx;
781: int stepm=1;
782: /* Stepm, step in month: minimum step interpolation*/
783:
784: int estepm;
785: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
786:
787: int m,nb;
788: long *num;
789: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
790: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
791: double **pmmij, ***probs;
792: double *ageexmed,*agecens;
793: double dateintmean=0;
794:
795: double *weight;
796: int **s; /* Status */
1.141 brouard 797: double *agedc;
1.145 brouard 798: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 799: * covar=matrix(0,NCOVMAX,1,n);
800: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
801: double idx;
802: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 803: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 804: int **codtab; /**< codtab=imatrix(1,100,1,10); */
805: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 806: double *lsurv, *lpop, *tpop;
807:
1.143 brouard 808: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
809: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 810:
811: /**************** split *************************/
812: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
813: {
814: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
815: the name of the file (name), its extension only (ext) and its first part of the name (finame)
816: */
817: char *ss; /* pointer */
818: int l1, l2; /* length counters */
819:
820: l1 = strlen(path ); /* length of path */
821: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
822: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
823: if ( ss == NULL ) { /* no directory, so determine current directory */
824: strcpy( name, path ); /* we got the fullname name because no directory */
825: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
826: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
827: /* get current working directory */
828: /* extern char* getcwd ( char *buf , int len);*/
829: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
830: return( GLOCK_ERROR_GETCWD );
831: }
832: /* got dirc from getcwd*/
833: printf(" DIRC = %s \n",dirc);
834: } else { /* strip direcotry from path */
835: ss++; /* after this, the filename */
836: l2 = strlen( ss ); /* length of filename */
837: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
838: strcpy( name, ss ); /* save file name */
839: strncpy( dirc, path, l1 - l2 ); /* now the directory */
840: dirc[l1-l2] = 0; /* add zero */
841: printf(" DIRC2 = %s \n",dirc);
842: }
843: /* We add a separator at the end of dirc if not exists */
844: l1 = strlen( dirc ); /* length of directory */
845: if( dirc[l1-1] != DIRSEPARATOR ){
846: dirc[l1] = DIRSEPARATOR;
847: dirc[l1+1] = 0;
848: printf(" DIRC3 = %s \n",dirc);
849: }
850: ss = strrchr( name, '.' ); /* find last / */
851: if (ss >0){
852: ss++;
853: strcpy(ext,ss); /* save extension */
854: l1= strlen( name);
855: l2= strlen(ss)+1;
856: strncpy( finame, name, l1-l2);
857: finame[l1-l2]= 0;
858: }
859:
860: return( 0 ); /* we're done */
861: }
862:
863:
864: /******************************************/
865:
866: void replace_back_to_slash(char *s, char*t)
867: {
868: int i;
869: int lg=0;
870: i=0;
871: lg=strlen(t);
872: for(i=0; i<= lg; i++) {
873: (s[i] = t[i]);
874: if (t[i]== '\\') s[i]='/';
875: }
876: }
877:
1.132 brouard 878: char *trimbb(char *out, char *in)
1.137 brouard 879: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 880: char *s;
881: s=out;
882: while (*in != '\0'){
1.137 brouard 883: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 884: in++;
885: }
886: *out++ = *in++;
887: }
888: *out='\0';
889: return s;
890: }
891:
1.145 brouard 892: char *cutl(char *blocc, char *alocc, char *in, char occ)
893: {
894: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
895: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
896: gives blocc="abcdef2ghi" and alocc="j".
897: If occ is not found blocc is null and alocc is equal to in. Returns blocc
898: */
1.160 brouard 899: char *s, *t;
1.145 brouard 900: t=in;s=in;
901: while ((*in != occ) && (*in != '\0')){
902: *alocc++ = *in++;
903: }
904: if( *in == occ){
905: *(alocc)='\0';
906: s=++in;
907: }
908:
909: if (s == t) {/* occ not found */
910: *(alocc-(in-s))='\0';
911: in=s;
912: }
913: while ( *in != '\0'){
914: *blocc++ = *in++;
915: }
916:
917: *blocc='\0';
918: return t;
919: }
1.137 brouard 920: char *cutv(char *blocc, char *alocc, char *in, char occ)
921: {
922: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
923: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
924: gives blocc="abcdef2ghi" and alocc="j".
925: If occ is not found blocc is null and alocc is equal to in. Returns alocc
926: */
927: char *s, *t;
928: t=in;s=in;
929: while (*in != '\0'){
930: while( *in == occ){
931: *blocc++ = *in++;
932: s=in;
933: }
934: *blocc++ = *in++;
935: }
936: if (s == t) /* occ not found */
937: *(blocc-(in-s))='\0';
938: else
939: *(blocc-(in-s)-1)='\0';
940: in=s;
941: while ( *in != '\0'){
942: *alocc++ = *in++;
943: }
944:
945: *alocc='\0';
946: return s;
947: }
948:
1.126 brouard 949: int nbocc(char *s, char occ)
950: {
951: int i,j=0;
952: int lg=20;
953: i=0;
954: lg=strlen(s);
955: for(i=0; i<= lg; i++) {
956: if (s[i] == occ ) j++;
957: }
958: return j;
959: }
960:
1.137 brouard 961: /* void cutv(char *u,char *v, char*t, char occ) */
962: /* { */
963: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
964: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
965: /* gives u="abcdef2ghi" and v="j" *\/ */
966: /* int i,lg,j,p=0; */
967: /* i=0; */
968: /* lg=strlen(t); */
969: /* for(j=0; j<=lg-1; j++) { */
970: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
971: /* } */
1.126 brouard 972:
1.137 brouard 973: /* for(j=0; j<p; j++) { */
974: /* (u[j] = t[j]); */
975: /* } */
976: /* u[p]='\0'; */
1.126 brouard 977:
1.137 brouard 978: /* for(j=0; j<= lg; j++) { */
979: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
980: /* } */
981: /* } */
1.126 brouard 982:
1.160 brouard 983: #ifdef _WIN32
984: char * strsep(char **pp, const char *delim)
985: {
986: char *p, *q;
987:
988: if ((p = *pp) == NULL)
989: return 0;
990: if ((q = strpbrk (p, delim)) != NULL)
991: {
992: *pp = q + 1;
993: *q = '\0';
994: }
995: else
996: *pp = 0;
997: return p;
998: }
999: #endif
1000:
1.126 brouard 1001: /********************** nrerror ********************/
1002:
1003: void nrerror(char error_text[])
1004: {
1005: fprintf(stderr,"ERREUR ...\n");
1006: fprintf(stderr,"%s\n",error_text);
1007: exit(EXIT_FAILURE);
1008: }
1009: /*********************** vector *******************/
1010: double *vector(int nl, int nh)
1011: {
1012: double *v;
1013: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1014: if (!v) nrerror("allocation failure in vector");
1015: return v-nl+NR_END;
1016: }
1017:
1018: /************************ free vector ******************/
1019: void free_vector(double*v, int nl, int nh)
1020: {
1021: free((FREE_ARG)(v+nl-NR_END));
1022: }
1023:
1024: /************************ivector *******************************/
1025: int *ivector(long nl,long nh)
1026: {
1027: int *v;
1028: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1029: if (!v) nrerror("allocation failure in ivector");
1030: return v-nl+NR_END;
1031: }
1032:
1033: /******************free ivector **************************/
1034: void free_ivector(int *v, long nl, long nh)
1035: {
1036: free((FREE_ARG)(v+nl-NR_END));
1037: }
1038:
1039: /************************lvector *******************************/
1040: long *lvector(long nl,long nh)
1041: {
1042: long *v;
1043: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1044: if (!v) nrerror("allocation failure in ivector");
1045: return v-nl+NR_END;
1046: }
1047:
1048: /******************free lvector **************************/
1049: void free_lvector(long *v, long nl, long nh)
1050: {
1051: free((FREE_ARG)(v+nl-NR_END));
1052: }
1053:
1054: /******************* imatrix *******************************/
1055: int **imatrix(long nrl, long nrh, long ncl, long nch)
1056: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1057: {
1058: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1059: int **m;
1060:
1061: /* allocate pointers to rows */
1062: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1063: if (!m) nrerror("allocation failure 1 in matrix()");
1064: m += NR_END;
1065: m -= nrl;
1066:
1067:
1068: /* allocate rows and set pointers to them */
1069: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1070: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1071: m[nrl] += NR_END;
1072: m[nrl] -= ncl;
1073:
1074: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1075:
1076: /* return pointer to array of pointers to rows */
1077: return m;
1078: }
1079:
1080: /****************** free_imatrix *************************/
1081: void free_imatrix(m,nrl,nrh,ncl,nch)
1082: int **m;
1083: long nch,ncl,nrh,nrl;
1084: /* free an int matrix allocated by imatrix() */
1085: {
1086: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1087: free((FREE_ARG) (m+nrl-NR_END));
1088: }
1089:
1090: /******************* matrix *******************************/
1091: double **matrix(long nrl, long nrh, long ncl, long nch)
1092: {
1093: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1094: double **m;
1095:
1096: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1097: if (!m) nrerror("allocation failure 1 in matrix()");
1098: m += NR_END;
1099: m -= nrl;
1100:
1101: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1102: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1103: m[nrl] += NR_END;
1104: m[nrl] -= ncl;
1105:
1106: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1107: return m;
1.145 brouard 1108: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1109: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1110: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1111: */
1112: }
1113:
1114: /*************************free matrix ************************/
1115: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1116: {
1117: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1118: free((FREE_ARG)(m+nrl-NR_END));
1119: }
1120:
1121: /******************* ma3x *******************************/
1122: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1123: {
1124: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1125: double ***m;
1126:
1127: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1128: if (!m) nrerror("allocation failure 1 in matrix()");
1129: m += NR_END;
1130: m -= nrl;
1131:
1132: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1133: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1134: m[nrl] += NR_END;
1135: m[nrl] -= ncl;
1136:
1137: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1138:
1139: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1140: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1141: m[nrl][ncl] += NR_END;
1142: m[nrl][ncl] -= nll;
1143: for (j=ncl+1; j<=nch; j++)
1144: m[nrl][j]=m[nrl][j-1]+nlay;
1145:
1146: for (i=nrl+1; i<=nrh; i++) {
1147: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1148: for (j=ncl+1; j<=nch; j++)
1149: m[i][j]=m[i][j-1]+nlay;
1150: }
1151: return m;
1152: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1153: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1154: */
1155: }
1156:
1157: /*************************free ma3x ************************/
1158: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1159: {
1160: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1161: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1162: free((FREE_ARG)(m+nrl-NR_END));
1163: }
1164:
1165: /*************** function subdirf ***********/
1166: char *subdirf(char fileres[])
1167: {
1168: /* Caution optionfilefiname is hidden */
1169: strcpy(tmpout,optionfilefiname);
1170: strcat(tmpout,"/"); /* Add to the right */
1171: strcat(tmpout,fileres);
1172: return tmpout;
1173: }
1174:
1175: /*************** function subdirf2 ***********/
1176: char *subdirf2(char fileres[], char *preop)
1177: {
1178:
1179: /* Caution optionfilefiname is hidden */
1180: strcpy(tmpout,optionfilefiname);
1181: strcat(tmpout,"/");
1182: strcat(tmpout,preop);
1183: strcat(tmpout,fileres);
1184: return tmpout;
1185: }
1186:
1187: /*************** function subdirf3 ***********/
1188: char *subdirf3(char fileres[], char *preop, char *preop2)
1189: {
1190:
1191: /* Caution optionfilefiname is hidden */
1192: strcpy(tmpout,optionfilefiname);
1193: strcat(tmpout,"/");
1194: strcat(tmpout,preop);
1195: strcat(tmpout,preop2);
1196: strcat(tmpout,fileres);
1197: return tmpout;
1198: }
1199:
1.162 brouard 1200: char *asc_diff_time(long time_sec, char ascdiff[])
1201: {
1202: long sec_left, days, hours, minutes;
1203: days = (time_sec) / (60*60*24);
1204: sec_left = (time_sec) % (60*60*24);
1205: hours = (sec_left) / (60*60) ;
1206: sec_left = (sec_left) %(60*60);
1207: minutes = (sec_left) /60;
1208: sec_left = (sec_left) % (60);
1209: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1210: return ascdiff;
1211: }
1212:
1.126 brouard 1213: /***************** f1dim *************************/
1214: extern int ncom;
1215: extern double *pcom,*xicom;
1216: extern double (*nrfunc)(double []);
1217:
1218: double f1dim(double x)
1219: {
1220: int j;
1221: double f;
1222: double *xt;
1223:
1224: xt=vector(1,ncom);
1225: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1226: f=(*nrfunc)(xt);
1227: free_vector(xt,1,ncom);
1228: return f;
1229: }
1230:
1231: /*****************brent *************************/
1232: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1233: {
1234: int iter;
1235: double a,b,d,etemp;
1.159 brouard 1236: double fu=0,fv,fw,fx;
1.164 brouard 1237: double ftemp=0.;
1.126 brouard 1238: double p,q,r,tol1,tol2,u,v,w,x,xm;
1239: double e=0.0;
1240:
1241: a=(ax < cx ? ax : cx);
1242: b=(ax > cx ? ax : cx);
1243: x=w=v=bx;
1244: fw=fv=fx=(*f)(x);
1245: for (iter=1;iter<=ITMAX;iter++) {
1246: xm=0.5*(a+b);
1247: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1248: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1249: printf(".");fflush(stdout);
1250: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1251: #ifdef DEBUGBRENT
1.126 brouard 1252: 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);
1253: 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);
1254: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1255: #endif
1256: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1257: *xmin=x;
1258: return fx;
1259: }
1260: ftemp=fu;
1261: if (fabs(e) > tol1) {
1262: r=(x-w)*(fx-fv);
1263: q=(x-v)*(fx-fw);
1264: p=(x-v)*q-(x-w)*r;
1265: q=2.0*(q-r);
1266: if (q > 0.0) p = -p;
1267: q=fabs(q);
1268: etemp=e;
1269: e=d;
1270: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1271: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1272: else {
1273: d=p/q;
1274: u=x+d;
1275: if (u-a < tol2 || b-u < tol2)
1276: d=SIGN(tol1,xm-x);
1277: }
1278: } else {
1279: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1280: }
1281: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1282: fu=(*f)(u);
1283: if (fu <= fx) {
1284: if (u >= x) a=x; else b=x;
1285: SHFT(v,w,x,u)
1.183 ! brouard 1286: SHFT(fv,fw,fx,fu)
! 1287: } else {
! 1288: if (u < x) a=u; else b=u;
! 1289: if (fu <= fw || w == x) {
! 1290: v=w;
! 1291: w=u;
! 1292: fv=fw;
! 1293: fw=fu;
! 1294: } else if (fu <= fv || v == x || v == w) {
! 1295: v=u;
! 1296: fv=fu;
! 1297: }
! 1298: }
1.126 brouard 1299: }
1300: nrerror("Too many iterations in brent");
1301: *xmin=x;
1302: return fx;
1303: }
1304:
1305: /****************** mnbrak ***********************/
1306:
1307: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1308: double (*func)(double))
1.183 ! brouard 1309: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
! 1310: the downhill direction (defined by the function as evaluated at the initial points) and returns
! 1311: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
! 1312: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
! 1313: */
1.126 brouard 1314: double ulim,u,r,q, dum;
1315: double fu;
1316:
1317: *fa=(*func)(*ax);
1318: *fb=(*func)(*bx);
1319: if (*fb > *fa) {
1320: SHFT(dum,*ax,*bx,dum)
1.183 ! brouard 1321: SHFT(dum,*fb,*fa,dum)
! 1322: }
1.126 brouard 1323: *cx=(*bx)+GOLD*(*bx-*ax);
1324: *fc=(*func)(*cx);
1.183 ! brouard 1325: #ifdef DEBUG
! 1326: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
! 1327: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
! 1328: #endif
! 1329: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1330: r=(*bx-*ax)*(*fb-*fc);
1331: q=(*bx-*cx)*(*fb-*fa);
1332: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 ! brouard 1333: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
! 1334: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
! 1335: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1336: fu=(*func)(u);
1.163 brouard 1337: #ifdef DEBUG
1338: /* f(x)=A(x-u)**2+f(u) */
1339: double A, fparabu;
1340: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1341: fparabu= *fa - A*(*ax-u)*(*ax-u);
1342: 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);
1343: 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);
1.183 ! brouard 1344: /* And thus,it can be that fu > *fc even if fparabu < *fc */
! 1345: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
! 1346: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
! 1347: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1348: #endif
1.183 ! brouard 1349: #ifdef MNBRAKORI
! 1350: #else
! 1351: if (fu > *fc) {
! 1352: #ifdef DEBUG
! 1353: printf("mnbrak4 fu > fc \n");
! 1354: fprintf(ficlog, "mnbrak4 fu > fc\n");
! 1355: #endif
! 1356: /* SHFT(u,*cx,*cx,u) /\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\/ */
! 1357: /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\/ */
! 1358: dum=u; /* Shifting c and u */
! 1359: u = *cx;
! 1360: *cx = dum;
! 1361: dum = fu;
! 1362: fu = *fc;
! 1363: *fc =dum;
! 1364: } else { /* end */
! 1365: #ifdef DEBUG
! 1366: printf("mnbrak3 fu < fc \n");
! 1367: fprintf(ficlog, "mnbrak3 fu < fc\n");
! 1368: #endif
! 1369: dum=u; /* Shifting c and u */
! 1370: u = *cx;
! 1371: *cx = dum;
! 1372: dum = fu;
! 1373: fu = *fc;
! 1374: *fc =dum;
! 1375: }
! 1376: #endif
1.162 brouard 1377: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 ! brouard 1378: #ifdef DEBUG
! 1379: printf("mnbrak2 u after c but before ulim\n");
! 1380: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
! 1381: #endif
1.126 brouard 1382: fu=(*func)(u);
1383: if (fu < *fc) {
1.183 ! brouard 1384: #ifdef DEBUG
! 1385: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
! 1386: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
! 1387: #endif
1.126 brouard 1388: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 ! brouard 1389: SHFT(*fb,*fc,fu,(*func)(u))
! 1390: }
1.162 brouard 1391: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 ! brouard 1392: #ifdef DEBUG
! 1393: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
! 1394: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
! 1395: #endif
1.126 brouard 1396: u=ulim;
1397: fu=(*func)(u);
1.183 ! brouard 1398: } else { /* u could be left to b (if r > q parabola has a maximum) */
! 1399: #ifdef DEBUG
! 1400: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
! 1401: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
! 1402: #endif
1.126 brouard 1403: u=(*cx)+GOLD*(*cx-*bx);
1404: fu=(*func)(u);
1.183 ! brouard 1405: } /* end tests */
1.126 brouard 1406: SHFT(*ax,*bx,*cx,u)
1.183 ! brouard 1407: SHFT(*fa,*fb,*fc,fu)
! 1408: #ifdef DEBUG
! 1409: printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
! 1410: fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
! 1411: #endif
! 1412: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126 brouard 1413: }
1414:
1415: /*************** linmin ************************/
1.162 brouard 1416: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1417: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1418: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1419: the value of func at the returned location p . This is actually all accomplished by calling the
1420: routines mnbrak and brent .*/
1.126 brouard 1421: int ncom;
1422: double *pcom,*xicom;
1423: double (*nrfunc)(double []);
1424:
1425: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1426: {
1427: double brent(double ax, double bx, double cx,
1428: double (*f)(double), double tol, double *xmin);
1429: double f1dim(double x);
1430: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1431: double *fc, double (*func)(double));
1432: int j;
1433: double xx,xmin,bx,ax;
1434: double fx,fb,fa;
1435:
1436: ncom=n;
1437: pcom=vector(1,n);
1438: xicom=vector(1,n);
1439: nrfunc=func;
1440: for (j=1;j<=n;j++) {
1441: pcom[j]=p[j];
1442: xicom[j]=xi[j];
1443: }
1444: ax=0.0;
1445: xx=1.0;
1.162 brouard 1446: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1447: *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 1448: #ifdef DEBUG
1449: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1450: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1451: #endif
1452: for (j=1;j<=n;j++) {
1453: xi[j] *= xmin;
1454: p[j] += xi[j];
1455: }
1456: free_vector(xicom,1,n);
1457: free_vector(pcom,1,n);
1458: }
1459:
1460:
1461: /*************** powell ************************/
1.162 brouard 1462: /*
1463: Minimization of a function func of n variables. Input consists of an initial starting point
1464: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1465: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1466: such that failure to decrease by more than this amount on one iteration signals doneness. On
1467: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1468: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1469: */
1.126 brouard 1470: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1471: double (*func)(double []))
1472: {
1473: void linmin(double p[], double xi[], int n, double *fret,
1474: double (*func)(double []));
1475: int i,ibig,j;
1476: double del,t,*pt,*ptt,*xit;
1.181 brouard 1477: double directest;
1.126 brouard 1478: double fp,fptt;
1479: double *xits;
1480: int niterf, itmp;
1481:
1482: pt=vector(1,n);
1483: ptt=vector(1,n);
1484: xit=vector(1,n);
1485: xits=vector(1,n);
1486: *fret=(*func)(p);
1487: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1488: rcurr_time = time(NULL);
1.126 brouard 1489: for (*iter=1;;++(*iter)) {
1490: fp=(*fret);
1491: ibig=0;
1492: del=0.0;
1.157 brouard 1493: rlast_time=rcurr_time;
1494: /* (void) gettimeofday(&curr_time,&tzp); */
1495: rcurr_time = time(NULL);
1496: curr_time = *localtime(&rcurr_time);
1497: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1498: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1499: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1500: for (i=1;i<=n;i++) {
1501: printf(" %d %.12f",i, p[i]);
1502: fprintf(ficlog," %d %.12lf",i, p[i]);
1503: fprintf(ficrespow," %.12lf", p[i]);
1504: }
1505: printf("\n");
1506: fprintf(ficlog,"\n");
1507: fprintf(ficrespow,"\n");fflush(ficrespow);
1508: if(*iter <=3){
1.157 brouard 1509: tml = *localtime(&rcurr_time);
1510: strcpy(strcurr,asctime(&tml));
1511: rforecast_time=rcurr_time;
1.126 brouard 1512: itmp = strlen(strcurr);
1513: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1514: strcurr[itmp-1]='\0';
1.162 brouard 1515: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1516: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1517: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1518: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1519: forecast_time = *localtime(&rforecast_time);
1520: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1521: itmp = strlen(strfor);
1522: if(strfor[itmp-1]=='\n')
1523: strfor[itmp-1]='\0';
1.157 brouard 1524: 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);
1525: 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 1526: }
1527: }
1528: for (i=1;i<=n;i++) {
1529: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1530: fptt=(*fret);
1531: #ifdef DEBUG
1.164 brouard 1532: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1533: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1534: #endif
1535: printf("%d",i);fflush(stdout);
1536: fprintf(ficlog,"%d",i);fflush(ficlog);
1.183 ! brouard 1537: linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
1.181 brouard 1538: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1539: because that direction will be replaced unless the gain del is small
1540: in comparison with the 'probable' gain, mu^2, with the last average direction.
1541: Unless the n directions are conjugate some gain in the determinant may be obtained
1542: with the new direction.
1543: */
1.126 brouard 1544: del=fabs(fptt-(*fret));
1545: ibig=i;
1546: }
1547: #ifdef DEBUG
1548: printf("%d %.12e",i,(*fret));
1549: fprintf(ficlog,"%d %.12e",i,(*fret));
1550: for (j=1;j<=n;j++) {
1551: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1552: printf(" x(%d)=%.12e",j,xit[j]);
1553: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1554: }
1555: for(j=1;j<=n;j++) {
1.162 brouard 1556: printf(" p(%d)=%.12e",j,p[j]);
1557: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1558: }
1559: printf("\n");
1560: fprintf(ficlog,"\n");
1561: #endif
1.162 brouard 1562: } /* end i */
1.182 brouard 1563: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.126 brouard 1564: #ifdef DEBUG
1565: int k[2],l;
1566: k[0]=1;
1567: k[1]=-1;
1568: printf("Max: %.12e",(*func)(p));
1569: fprintf(ficlog,"Max: %.12e",(*func)(p));
1570: for (j=1;j<=n;j++) {
1571: printf(" %.12e",p[j]);
1572: fprintf(ficlog," %.12e",p[j]);
1573: }
1574: printf("\n");
1575: fprintf(ficlog,"\n");
1576: for(l=0;l<=1;l++) {
1577: for (j=1;j<=n;j++) {
1578: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1579: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1580: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1581: }
1582: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1583: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1584: }
1585: #endif
1586:
1587:
1588: free_vector(xit,1,n);
1589: free_vector(xits,1,n);
1590: free_vector(ptt,1,n);
1591: free_vector(pt,1,n);
1592: return;
1593: }
1594: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1595: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1596: ptt[j]=2.0*p[j]-pt[j];
1597: xit[j]=p[j]-pt[j];
1598: pt[j]=p[j];
1599: }
1.181 brouard 1600: fptt=(*func)(ptt); /* f_3 */
1.161 brouard 1601: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1602: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1603: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1604: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1605: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1606: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1607: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1608: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 ! brouard 1609: #ifdef NRCORIGINAL
! 1610: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
! 1611: #else
! 1612: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161 brouard 1613: t= t- del*SQR(fp-fptt);
1.183 ! brouard 1614: #endif
1.182 brouard 1615: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1616: #ifdef DEBUG
1.181 brouard 1617: printf("t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1618: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1.161 brouard 1619: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1620: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1621: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1622: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1623: 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);
1624: 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);
1625: #endif
1.183 ! brouard 1626: #ifdef POWELLORIGINAL
! 1627: if (t < 0.0) { /* Then we use it for new direction */
! 1628: #else
1.182 brouard 1629: if (directest*t < 0.0) { /* Contradiction between both tests */
1630: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1631: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1632: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1633: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1634: }
1.181 brouard 1635: if (directest < 0.0) { /* Then we use it for new direction */
1636: #endif
1637: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1.126 brouard 1638: for (j=1;j<=n;j++) {
1.181 brouard 1639: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1640: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1641: }
1.181 brouard 1642: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1643: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1644:
1.126 brouard 1645: #ifdef DEBUG
1.164 brouard 1646: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1647: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1648: for(j=1;j<=n;j++){
1649: printf(" %.12e",xit[j]);
1650: fprintf(ficlog," %.12e",xit[j]);
1651: }
1652: printf("\n");
1653: fprintf(ficlog,"\n");
1654: #endif
1.162 brouard 1655: } /* end of t negative */
1656: } /* end if (fptt < fp) */
1.126 brouard 1657: }
1658: }
1659:
1660: /**** Prevalence limit (stable or period prevalence) ****************/
1661:
1662: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1663: {
1664: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1665: matrix by transitions matrix until convergence is reached */
1.169 brouard 1666:
1.126 brouard 1667: int i, ii,j,k;
1668: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1669: /* double **matprod2(); */ /* test */
1.131 brouard 1670: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1671: double **newm;
1672: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1673:
1.126 brouard 1674: for (ii=1;ii<=nlstate+ndeath;ii++)
1675: for (j=1;j<=nlstate+ndeath;j++){
1676: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1677: }
1.169 brouard 1678:
1679: cov[1]=1.;
1680:
1681: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1682: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1683: newm=savm;
1684: /* Covariates have to be included here again */
1.138 brouard 1685: cov[2]=agefin;
1686:
1687: for (k=1; k<=cptcovn;k++) {
1688: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1689: /*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 1690: }
1.145 brouard 1691: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1692: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1693: /* 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 1694:
1695: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1696: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1697: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1698: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1699: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1700: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1701:
1.126 brouard 1702: savm=oldm;
1703: oldm=newm;
1704: maxmax=0.;
1705: for(j=1;j<=nlstate;j++){
1706: min=1.;
1707: max=0.;
1708: for(i=1; i<=nlstate; i++) {
1709: sumnew=0;
1710: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1711: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1712: /*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 1713: max=FMAX(max,prlim[i][j]);
1714: min=FMIN(min,prlim[i][j]);
1715: }
1716: maxmin=max-min;
1717: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1718: } /* j loop */
1.126 brouard 1719: if(maxmax < ftolpl){
1720: return prlim;
1721: }
1.169 brouard 1722: } /* age loop */
1723: return prlim; /* should not reach here */
1.126 brouard 1724: }
1725:
1726: /*************** transition probabilities ***************/
1727:
1728: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1729: {
1.138 brouard 1730: /* According to parameters values stored in x and the covariate's values stored in cov,
1731: computes the probability to be observed in state j being in state i by appying the
1732: model to the ncovmodel covariates (including constant and age).
1733: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1734: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1735: ncth covariate in the global vector x is given by the formula:
1736: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1737: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1738: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1739: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1740: Outputs ps[i][j] the probability to be observed in j being in j according to
1741: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1742: */
1743: double s1, lnpijopii;
1.126 brouard 1744: /*double t34;*/
1.164 brouard 1745: int i,j, nc, ii, jj;
1.126 brouard 1746:
1747: for(i=1; i<= nlstate; i++){
1748: for(j=1; j<i;j++){
1.138 brouard 1749: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1750: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1751: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1752: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1753: }
1.138 brouard 1754: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1755: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1756: }
1757: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1758: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1759: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1760: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1761: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1762: }
1.138 brouard 1763: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1764: }
1765: }
1766:
1767: for(i=1; i<= nlstate; i++){
1768: s1=0;
1.131 brouard 1769: for(j=1; j<i; j++){
1.138 brouard 1770: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1771: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1772: }
1773: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1774: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1775: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1776: }
1.138 brouard 1777: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1778: ps[i][i]=1./(s1+1.);
1.138 brouard 1779: /* Computing other pijs */
1.126 brouard 1780: for(j=1; j<i; j++)
1781: ps[i][j]= exp(ps[i][j])*ps[i][i];
1782: for(j=i+1; j<=nlstate+ndeath; j++)
1783: ps[i][j]= exp(ps[i][j])*ps[i][i];
1784: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1785: } /* end i */
1786:
1787: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1788: for(jj=1; jj<= nlstate+ndeath; jj++){
1789: ps[ii][jj]=0;
1790: ps[ii][ii]=1;
1791: }
1792: }
1793:
1.145 brouard 1794:
1795: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1796: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1797: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1798: /* } */
1799: /* printf("\n "); */
1800: /* } */
1801: /* printf("\n ");printf("%lf ",cov[2]);*/
1802: /*
1.126 brouard 1803: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1804: goto end;*/
1805: return ps;
1806: }
1807:
1808: /**************** Product of 2 matrices ******************/
1809:
1.145 brouard 1810: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1811: {
1812: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1813: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1814: /* in, b, out are matrice of pointers which should have been initialized
1815: before: only the contents of out is modified. The function returns
1816: a pointer to pointers identical to out */
1.145 brouard 1817: int i, j, k;
1.126 brouard 1818: for(i=nrl; i<= nrh; i++)
1.145 brouard 1819: for(k=ncolol; k<=ncoloh; k++){
1820: out[i][k]=0.;
1821: for(j=ncl; j<=nch; j++)
1822: out[i][k] +=in[i][j]*b[j][k];
1823: }
1.126 brouard 1824: return out;
1825: }
1826:
1827:
1828: /************* Higher Matrix Product ***************/
1829:
1830: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1831: {
1832: /* Computes the transition matrix starting at age 'age' over
1833: 'nhstepm*hstepm*stepm' months (i.e. until
1834: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1835: nhstepm*hstepm matrices.
1836: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1837: (typically every 2 years instead of every month which is too big
1838: for the memory).
1839: Model is determined by parameters x and covariates have to be
1840: included manually here.
1841:
1842: */
1843:
1844: int i, j, d, h, k;
1.131 brouard 1845: double **out, cov[NCOVMAX+1];
1.126 brouard 1846: double **newm;
1847:
1848: /* Hstepm could be zero and should return the unit matrix */
1849: for (i=1;i<=nlstate+ndeath;i++)
1850: for (j=1;j<=nlstate+ndeath;j++){
1851: oldm[i][j]=(i==j ? 1.0 : 0.0);
1852: po[i][j][0]=(i==j ? 1.0 : 0.0);
1853: }
1854: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1855: for(h=1; h <=nhstepm; h++){
1856: for(d=1; d <=hstepm; d++){
1857: newm=savm;
1858: /* Covariates have to be included here again */
1859: cov[1]=1.;
1860: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1861: for (k=1; k<=cptcovn;k++)
1862: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1863: for (k=1; k<=cptcovage;k++)
1864: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1865: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1866: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1867:
1868:
1869: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1870: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1871: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1872: pmij(pmmij,cov,ncovmodel,x,nlstate));
1873: savm=oldm;
1874: oldm=newm;
1875: }
1876: for(i=1; i<=nlstate+ndeath; i++)
1877: for(j=1;j<=nlstate+ndeath;j++) {
1878: po[i][j][h]=newm[i][j];
1.128 brouard 1879: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1880: }
1.128 brouard 1881: /*printf("h=%d ",h);*/
1.126 brouard 1882: } /* end h */
1.128 brouard 1883: /* printf("\n H=%d \n",h); */
1.126 brouard 1884: return po;
1885: }
1886:
1.162 brouard 1887: #ifdef NLOPT
1888: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1889: double fret;
1890: double *xt;
1891: int j;
1892: myfunc_data *d2 = (myfunc_data *) pd;
1893: /* xt = (p1-1); */
1894: xt=vector(1,n);
1895: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1896:
1897: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1898: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1899: printf("Function = %.12lf ",fret);
1900: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1901: printf("\n");
1902: free_vector(xt,1,n);
1903: return fret;
1904: }
1905: #endif
1.126 brouard 1906:
1907: /*************** log-likelihood *************/
1908: double func( double *x)
1909: {
1910: int i, ii, j, k, mi, d, kk;
1.131 brouard 1911: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1912: double **out;
1913: double sw; /* Sum of weights */
1914: double lli; /* Individual log likelihood */
1915: int s1, s2;
1916: double bbh, survp;
1917: long ipmx;
1918: /*extern weight */
1919: /* We are differentiating ll according to initial status */
1920: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1921: /*for(i=1;i<imx;i++)
1922: printf(" %d\n",s[4][i]);
1923: */
1.162 brouard 1924:
1925: ++countcallfunc;
1926:
1.126 brouard 1927: cov[1]=1.;
1928:
1929: for(k=1; k<=nlstate; k++) ll[k]=0.;
1930:
1931: if(mle==1){
1932: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1933: /* Computes the values of the ncovmodel covariates of the model
1934: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1935: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1936: to be observed in j being in i according to the model.
1937: */
1.145 brouard 1938: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1939: cov[2+k]=covar[Tvar[k]][i];
1940: }
1.137 brouard 1941: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1942: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1943: has been calculated etc */
1.126 brouard 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++) {
1.137 brouard 1954: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 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: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1963: /* But now since version 0.9 we anticipate for bias at large stepm.
1964: * If stepm is larger than one month (smallest stepm) and if the exact delay
1965: * (in months) between two waves is not a multiple of stepm, we rounded to
1966: * the nearest (and in case of equal distance, to the lowest) interval but now
1967: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1968: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1969: * probability in order to take into account the bias as a fraction of the way
1970: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1971: * -stepm/2 to stepm/2 .
1972: * For stepm=1 the results are the same as for previous versions of Imach.
1973: * For stepm > 1 the results are less biased than in previous versions.
1974: */
1975: s1=s[mw[mi][i]][i];
1976: s2=s[mw[mi+1][i]][i];
1977: bbh=(double)bh[mi][i]/(double)stepm;
1978: /* bias bh is positive if real duration
1979: * is higher than the multiple of stepm and negative otherwise.
1980: */
1981: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1982: if( s2 > nlstate){
1983: /* i.e. if s2 is a death state and if the date of death is known
1984: then the contribution to the likelihood is the probability to
1985: die between last step unit time and current step unit time,
1986: which is also equal to probability to die before dh
1987: minus probability to die before dh-stepm .
1988: In version up to 0.92 likelihood was computed
1989: as if date of death was unknown. Death was treated as any other
1990: health state: the date of the interview describes the actual state
1991: and not the date of a change in health state. The former idea was
1992: to consider that at each interview the state was recorded
1993: (healthy, disable or death) and IMaCh was corrected; but when we
1994: introduced the exact date of death then we should have modified
1995: the contribution of an exact death to the likelihood. This new
1996: contribution is smaller and very dependent of the step unit
1997: stepm. It is no more the probability to die between last interview
1998: and month of death but the probability to survive from last
1999: interview up to one month before death multiplied by the
2000: probability to die within a month. Thanks to Chris
2001: Jackson for correcting this bug. Former versions increased
2002: mortality artificially. The bad side is that we add another loop
2003: which slows down the processing. The difference can be up to 10%
2004: lower mortality.
2005: */
1.183 ! brouard 2006: /* If, at the beginning of the maximization mostly, the
! 2007: cumulative probability or probability to be dead is
! 2008: constant (ie = 1) over time d, the difference is equal to
! 2009: 0. out[s1][3] = savm[s1][3]: probability, being at state
! 2010: s1 at precedent wave, to be dead a month before current
! 2011: wave is equal to probability, being at state s1 at
! 2012: precedent wave, to be dead at mont of the current
! 2013: wave. Then the observed probability (that this person died)
! 2014: is null according to current estimated parameter. In fact,
! 2015: it should be very low but not zero otherwise the log go to
! 2016: infinity.
! 2017: */
! 2018: /* #ifdef INFINITYORIGINAL */
! 2019: /* lli=log(out[s1][s2] - savm[s1][s2]); */
! 2020: /* #else */
! 2021: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
! 2022: /* lli=log(mytinydouble); */
! 2023: /* else */
! 2024: /* lli=log(out[s1][s2] - savm[s1][s2]); */
! 2025: /* #endif */
! 2026: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2027:
2028: } else if (s2==-2) {
2029: for (j=1,survp=0. ; j<=nlstate; j++)
2030: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2031: /*survp += out[s1][j]; */
2032: lli= log(survp);
2033: }
2034:
2035: else if (s2==-4) {
2036: for (j=3,survp=0. ; j<=nlstate; j++)
2037: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2038: lli= log(survp);
2039: }
2040:
2041: else if (s2==-5) {
2042: for (j=1,survp=0. ; j<=2; j++)
2043: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2044: lli= log(survp);
2045: }
2046:
2047: else{
2048: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2049: /* 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 */
2050: }
2051: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2052: /*if(lli ==000.0)*/
2053: /*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); */
2054: ipmx +=1;
2055: sw += weight[i];
2056: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 ! brouard 2057: /* if (lli < log(mytinydouble)){ */
! 2058: /* printf("Close to inf lli = %.10lf < %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
! 2059: /* fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
! 2060: /* } */
1.126 brouard 2061: } /* end of wave */
2062: } /* end of individual */
2063: } else if(mle==2){
2064: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2065: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2066: for(mi=1; mi<= wav[i]-1; mi++){
2067: for (ii=1;ii<=nlstate+ndeath;ii++)
2068: for (j=1;j<=nlstate+ndeath;j++){
2069: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2070: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2071: }
2072: for(d=0; d<=dh[mi][i]; d++){
2073: newm=savm;
2074: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2075: for (kk=1; kk<=cptcovage;kk++) {
2076: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2077: }
2078: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2079: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2080: savm=oldm;
2081: oldm=newm;
2082: } /* end mult */
2083:
2084: s1=s[mw[mi][i]][i];
2085: s2=s[mw[mi+1][i]][i];
2086: bbh=(double)bh[mi][i]/(double)stepm;
2087: 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 */
2088: ipmx +=1;
2089: sw += weight[i];
2090: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2091: } /* end of wave */
2092: } /* end of individual */
2093: } else if(mle==3){ /* exponential inter-extrapolation */
2094: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2095: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2096: for(mi=1; mi<= wav[i]-1; mi++){
2097: for (ii=1;ii<=nlstate+ndeath;ii++)
2098: for (j=1;j<=nlstate+ndeath;j++){
2099: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2100: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2101: }
2102: for(d=0; d<dh[mi][i]; d++){
2103: newm=savm;
2104: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2105: for (kk=1; kk<=cptcovage;kk++) {
2106: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2107: }
2108: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2109: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2110: savm=oldm;
2111: oldm=newm;
2112: } /* end mult */
2113:
2114: s1=s[mw[mi][i]][i];
2115: s2=s[mw[mi+1][i]][i];
2116: bbh=(double)bh[mi][i]/(double)stepm;
2117: 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 */
2118: ipmx +=1;
2119: sw += weight[i];
2120: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2121: } /* end of wave */
2122: } /* end of individual */
2123: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2124: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2125: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2126: for(mi=1; mi<= wav[i]-1; mi++){
2127: for (ii=1;ii<=nlstate+ndeath;ii++)
2128: for (j=1;j<=nlstate+ndeath;j++){
2129: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2130: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2131: }
2132: for(d=0; d<dh[mi][i]; d++){
2133: newm=savm;
2134: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2135: for (kk=1; kk<=cptcovage;kk++) {
2136: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2137: }
2138:
2139: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2140: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2141: savm=oldm;
2142: oldm=newm;
2143: } /* end mult */
2144:
2145: s1=s[mw[mi][i]][i];
2146: s2=s[mw[mi+1][i]][i];
2147: if( s2 > nlstate){
2148: lli=log(out[s1][s2] - savm[s1][s2]);
2149: }else{
2150: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2151: }
2152: ipmx +=1;
2153: sw += weight[i];
2154: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2155: /* 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]); */
2156: } /* end of wave */
2157: } /* end of individual */
2158: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2159: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2160: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2161: for(mi=1; mi<= wav[i]-1; mi++){
2162: for (ii=1;ii<=nlstate+ndeath;ii++)
2163: for (j=1;j<=nlstate+ndeath;j++){
2164: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2165: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2166: }
2167: for(d=0; d<dh[mi][i]; d++){
2168: newm=savm;
2169: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2170: for (kk=1; kk<=cptcovage;kk++) {
2171: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2172: }
2173:
2174: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2175: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2176: savm=oldm;
2177: oldm=newm;
2178: } /* end mult */
2179:
2180: s1=s[mw[mi][i]][i];
2181: s2=s[mw[mi+1][i]][i];
2182: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2183: ipmx +=1;
2184: sw += weight[i];
2185: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2186: /*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]);*/
2187: } /* end of wave */
2188: } /* end of individual */
2189: } /* End of if */
2190: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2191: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2192: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2193: return -l;
2194: }
2195:
2196: /*************** log-likelihood *************/
2197: double funcone( double *x)
2198: {
2199: /* Same as likeli but slower because of a lot of printf and if */
2200: int i, ii, j, k, mi, d, kk;
1.131 brouard 2201: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2202: double **out;
2203: double lli; /* Individual log likelihood */
2204: double llt;
2205: int s1, s2;
2206: double bbh, survp;
2207: /*extern weight */
2208: /* We are differentiating ll according to initial status */
2209: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2210: /*for(i=1;i<imx;i++)
2211: printf(" %d\n",s[4][i]);
2212: */
2213: cov[1]=1.;
2214:
2215: for(k=1; k<=nlstate; k++) ll[k]=0.;
2216:
2217: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2218: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2219: for(mi=1; mi<= wav[i]-1; mi++){
2220: for (ii=1;ii<=nlstate+ndeath;ii++)
2221: for (j=1;j<=nlstate+ndeath;j++){
2222: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2223: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2224: }
2225: for(d=0; d<dh[mi][i]; d++){
2226: newm=savm;
2227: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2228: for (kk=1; kk<=cptcovage;kk++) {
2229: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2230: }
1.145 brouard 2231: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2232: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2233: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2234: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2235: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2236: savm=oldm;
2237: oldm=newm;
2238: } /* end mult */
2239:
2240: s1=s[mw[mi][i]][i];
2241: s2=s[mw[mi+1][i]][i];
2242: bbh=(double)bh[mi][i]/(double)stepm;
2243: /* bias is positive if real duration
2244: * is higher than the multiple of stepm and negative otherwise.
2245: */
2246: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2247: lli=log(out[s1][s2] - savm[s1][s2]);
2248: } else if (s2==-2) {
2249: for (j=1,survp=0. ; j<=nlstate; j++)
2250: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2251: lli= log(survp);
2252: }else if (mle==1){
2253: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2254: } else if(mle==2){
2255: 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 */
2256: } else if(mle==3){ /* exponential inter-extrapolation */
2257: 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 */
2258: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2259: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2260: } else{ /* mle=0 back to 1 */
2261: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2262: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2263: } /* End of if */
2264: ipmx +=1;
2265: sw += weight[i];
2266: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2267: /*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 2268: if(globpr){
1.141 brouard 2269: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2270: %11.6f %11.6f %11.6f ", \
2271: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2272: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2273: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2274: llt +=ll[k]*gipmx/gsw;
2275: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2276: }
2277: fprintf(ficresilk," %10.6f\n", -llt);
2278: }
2279: } /* end of wave */
2280: } /* end of individual */
2281: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2282: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2283: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2284: if(globpr==0){ /* First time we count the contributions and weights */
2285: gipmx=ipmx;
2286: gsw=sw;
2287: }
2288: return -l;
2289: }
2290:
2291:
2292: /*************** function likelione ***********/
2293: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2294: {
2295: /* This routine should help understanding what is done with
2296: the selection of individuals/waves and
2297: to check the exact contribution to the likelihood.
2298: Plotting could be done.
2299: */
2300: int k;
2301:
2302: if(*globpri !=0){ /* Just counts and sums, no printings */
2303: strcpy(fileresilk,"ilk");
2304: strcat(fileresilk,fileres);
2305: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2306: printf("Problem with resultfile: %s\n", fileresilk);
2307: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2308: }
2309: 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");
2310: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2311: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2312: for(k=1; k<=nlstate; k++)
2313: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2314: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2315: }
2316:
2317: *fretone=(*funcone)(p);
2318: if(*globpri !=0){
2319: fclose(ficresilk);
2320: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2321: fflush(fichtm);
2322: }
2323: return;
2324: }
2325:
2326:
2327: /*********** Maximum Likelihood Estimation ***************/
2328:
2329: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2330: {
1.165 brouard 2331: int i,j, iter=0;
1.126 brouard 2332: double **xi;
2333: double fret;
2334: double fretone; /* Only one call to likelihood */
2335: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2336:
2337: #ifdef NLOPT
2338: int creturn;
2339: nlopt_opt opt;
2340: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2341: double *lb;
2342: double minf; /* the minimum objective value, upon return */
2343: double * p1; /* Shifted parameters from 0 instead of 1 */
2344: myfunc_data dinst, *d = &dinst;
2345: #endif
2346:
2347:
1.126 brouard 2348: xi=matrix(1,npar,1,npar);
2349: for (i=1;i<=npar;i++)
2350: for (j=1;j<=npar;j++)
2351: xi[i][j]=(i==j ? 1.0 : 0.0);
2352: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2353: strcpy(filerespow,"pow");
2354: strcat(filerespow,fileres);
2355: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2356: printf("Problem with resultfile: %s\n", filerespow);
2357: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2358: }
2359: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2360: for (i=1;i<=nlstate;i++)
2361: for(j=1;j<=nlstate+ndeath;j++)
2362: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2363: fprintf(ficrespow,"\n");
1.162 brouard 2364: #ifdef POWELL
1.126 brouard 2365: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2366: #endif
1.126 brouard 2367:
1.162 brouard 2368: #ifdef NLOPT
2369: #ifdef NEWUOA
2370: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2371: #else
2372: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2373: #endif
2374: lb=vector(0,npar-1);
2375: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2376: nlopt_set_lower_bounds(opt, lb);
2377: nlopt_set_initial_step1(opt, 0.1);
2378:
2379: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2380: d->function = func;
2381: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2382: nlopt_set_min_objective(opt, myfunc, d);
2383: nlopt_set_xtol_rel(opt, ftol);
2384: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2385: printf("nlopt failed! %d\n",creturn);
2386: }
2387: else {
2388: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2389: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2390: iter=1; /* not equal */
2391: }
2392: nlopt_destroy(opt);
2393: #endif
1.126 brouard 2394: free_matrix(xi,1,npar,1,npar);
2395: fclose(ficrespow);
1.180 brouard 2396: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2397: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2398: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2399:
2400: }
2401:
2402: /**** Computes Hessian and covariance matrix ***/
2403: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2404: {
2405: double **a,**y,*x,pd;
2406: double **hess;
1.164 brouard 2407: int i, j;
1.126 brouard 2408: int *indx;
2409:
2410: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2411: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2412: void lubksb(double **a, int npar, int *indx, double b[]) ;
2413: void ludcmp(double **a, int npar, int *indx, double *d) ;
2414: double gompertz(double p[]);
2415: hess=matrix(1,npar,1,npar);
2416:
2417: printf("\nCalculation of the hessian matrix. Wait...\n");
2418: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2419: for (i=1;i<=npar;i++){
2420: printf("%d",i);fflush(stdout);
2421: fprintf(ficlog,"%d",i);fflush(ficlog);
2422:
2423: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2424:
2425: /* printf(" %f ",p[i]);
2426: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2427: }
2428:
2429: for (i=1;i<=npar;i++) {
2430: for (j=1;j<=npar;j++) {
2431: if (j>i) {
2432: printf(".%d%d",i,j);fflush(stdout);
2433: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2434: hess[i][j]=hessij(p,delti,i,j,func,npar);
2435:
2436: hess[j][i]=hess[i][j];
2437: /*printf(" %lf ",hess[i][j]);*/
2438: }
2439: }
2440: }
2441: printf("\n");
2442: fprintf(ficlog,"\n");
2443:
2444: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2445: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2446:
2447: a=matrix(1,npar,1,npar);
2448: y=matrix(1,npar,1,npar);
2449: x=vector(1,npar);
2450: indx=ivector(1,npar);
2451: for (i=1;i<=npar;i++)
2452: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2453: ludcmp(a,npar,indx,&pd);
2454:
2455: for (j=1;j<=npar;j++) {
2456: for (i=1;i<=npar;i++) x[i]=0;
2457: x[j]=1;
2458: lubksb(a,npar,indx,x);
2459: for (i=1;i<=npar;i++){
2460: matcov[i][j]=x[i];
2461: }
2462: }
2463:
2464: printf("\n#Hessian matrix#\n");
2465: fprintf(ficlog,"\n#Hessian matrix#\n");
2466: for (i=1;i<=npar;i++) {
2467: for (j=1;j<=npar;j++) {
2468: printf("%.3e ",hess[i][j]);
2469: fprintf(ficlog,"%.3e ",hess[i][j]);
2470: }
2471: printf("\n");
2472: fprintf(ficlog,"\n");
2473: }
2474:
2475: /* Recompute Inverse */
2476: for (i=1;i<=npar;i++)
2477: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2478: ludcmp(a,npar,indx,&pd);
2479:
2480: /* printf("\n#Hessian matrix recomputed#\n");
2481:
2482: for (j=1;j<=npar;j++) {
2483: for (i=1;i<=npar;i++) x[i]=0;
2484: x[j]=1;
2485: lubksb(a,npar,indx,x);
2486: for (i=1;i<=npar;i++){
2487: y[i][j]=x[i];
2488: printf("%.3e ",y[i][j]);
2489: fprintf(ficlog,"%.3e ",y[i][j]);
2490: }
2491: printf("\n");
2492: fprintf(ficlog,"\n");
2493: }
2494: */
2495:
2496: free_matrix(a,1,npar,1,npar);
2497: free_matrix(y,1,npar,1,npar);
2498: free_vector(x,1,npar);
2499: free_ivector(indx,1,npar);
2500: free_matrix(hess,1,npar,1,npar);
2501:
2502:
2503: }
2504:
2505: /*************** hessian matrix ****************/
2506: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2507: {
2508: int i;
2509: int l=1, lmax=20;
2510: double k1,k2;
1.132 brouard 2511: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2512: double res;
2513: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2514: double fx;
2515: int k=0,kmax=10;
2516: double l1;
2517:
2518: fx=func(x);
2519: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2520: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2521: l1=pow(10,l);
2522: delts=delt;
2523: for(k=1 ; k <kmax; k=k+1){
2524: delt = delta*(l1*k);
2525: p2[theta]=x[theta] +delt;
1.145 brouard 2526: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2527: p2[theta]=x[theta]-delt;
2528: k2=func(p2)-fx;
2529: /*res= (k1-2.0*fx+k2)/delt/delt; */
2530: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2531:
1.132 brouard 2532: #ifdef DEBUGHESS
1.126 brouard 2533: 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);
2534: 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);
2535: #endif
2536: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2537: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2538: k=kmax;
2539: }
2540: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2541: k=kmax; l=lmax*10;
1.126 brouard 2542: }
2543: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2544: delts=delt;
2545: }
2546: }
2547: }
2548: delti[theta]=delts;
2549: return res;
2550:
2551: }
2552:
2553: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2554: {
2555: int i;
1.164 brouard 2556: int l=1, lmax=20;
1.126 brouard 2557: double k1,k2,k3,k4,res,fx;
1.132 brouard 2558: double p2[MAXPARM+1];
1.126 brouard 2559: int k;
2560:
2561: fx=func(x);
2562: for (k=1; k<=2; k++) {
2563: for (i=1;i<=npar;i++) p2[i]=x[i];
2564: p2[thetai]=x[thetai]+delti[thetai]/k;
2565: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2566: k1=func(p2)-fx;
2567:
2568: p2[thetai]=x[thetai]+delti[thetai]/k;
2569: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2570: k2=func(p2)-fx;
2571:
2572: p2[thetai]=x[thetai]-delti[thetai]/k;
2573: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2574: k3=func(p2)-fx;
2575:
2576: p2[thetai]=x[thetai]-delti[thetai]/k;
2577: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2578: k4=func(p2)-fx;
2579: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2580: #ifdef DEBUG
2581: 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);
2582: 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);
2583: #endif
2584: }
2585: return res;
2586: }
2587:
2588: /************** Inverse of matrix **************/
2589: void ludcmp(double **a, int n, int *indx, double *d)
2590: {
2591: int i,imax,j,k;
2592: double big,dum,sum,temp;
2593: double *vv;
2594:
2595: vv=vector(1,n);
2596: *d=1.0;
2597: for (i=1;i<=n;i++) {
2598: big=0.0;
2599: for (j=1;j<=n;j++)
2600: if ((temp=fabs(a[i][j])) > big) big=temp;
2601: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2602: vv[i]=1.0/big;
2603: }
2604: for (j=1;j<=n;j++) {
2605: for (i=1;i<j;i++) {
2606: sum=a[i][j];
2607: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2608: a[i][j]=sum;
2609: }
2610: big=0.0;
2611: for (i=j;i<=n;i++) {
2612: sum=a[i][j];
2613: for (k=1;k<j;k++)
2614: sum -= a[i][k]*a[k][j];
2615: a[i][j]=sum;
2616: if ( (dum=vv[i]*fabs(sum)) >= big) {
2617: big=dum;
2618: imax=i;
2619: }
2620: }
2621: if (j != imax) {
2622: for (k=1;k<=n;k++) {
2623: dum=a[imax][k];
2624: a[imax][k]=a[j][k];
2625: a[j][k]=dum;
2626: }
2627: *d = -(*d);
2628: vv[imax]=vv[j];
2629: }
2630: indx[j]=imax;
2631: if (a[j][j] == 0.0) a[j][j]=TINY;
2632: if (j != n) {
2633: dum=1.0/(a[j][j]);
2634: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2635: }
2636: }
2637: free_vector(vv,1,n); /* Doesn't work */
2638: ;
2639: }
2640:
2641: void lubksb(double **a, int n, int *indx, double b[])
2642: {
2643: int i,ii=0,ip,j;
2644: double sum;
2645:
2646: for (i=1;i<=n;i++) {
2647: ip=indx[i];
2648: sum=b[ip];
2649: b[ip]=b[i];
2650: if (ii)
2651: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2652: else if (sum) ii=i;
2653: b[i]=sum;
2654: }
2655: for (i=n;i>=1;i--) {
2656: sum=b[i];
2657: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2658: b[i]=sum/a[i][i];
2659: }
2660: }
2661:
2662: void pstamp(FILE *fichier)
2663: {
2664: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2665: }
2666:
2667: /************ Frequencies ********************/
2668: 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[])
2669: { /* Some frequencies */
2670:
1.164 brouard 2671: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2672: int first;
2673: double ***freq; /* Frequencies */
2674: double *pp, **prop;
2675: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2676: char fileresp[FILENAMELENGTH];
2677:
2678: pp=vector(1,nlstate);
2679: prop=matrix(1,nlstate,iagemin,iagemax+3);
2680: strcpy(fileresp,"p");
2681: strcat(fileresp,fileres);
2682: if((ficresp=fopen(fileresp,"w"))==NULL) {
2683: printf("Problem with prevalence resultfile: %s\n", fileresp);
2684: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2685: exit(0);
2686: }
2687: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2688: j1=0;
2689:
2690: j=cptcoveff;
2691: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2692:
2693: first=1;
2694:
1.169 brouard 2695: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2696: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2697: /* j1++; */
1.145 brouard 2698: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2699: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2700: scanf("%d", i);*/
2701: for (i=-5; i<=nlstate+ndeath; i++)
2702: for (jk=-5; jk<=nlstate+ndeath; jk++)
2703: for(m=iagemin; m <= iagemax+3; m++)
2704: freq[i][jk][m]=0;
1.143 brouard 2705:
2706: for (i=1; i<=nlstate; i++)
2707: for(m=iagemin; m <= iagemax+3; m++)
2708: prop[i][m]=0;
1.126 brouard 2709:
2710: dateintsum=0;
2711: k2cpt=0;
2712: for (i=1; i<=imx; i++) {
2713: bool=1;
1.144 brouard 2714: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2715: for (z1=1; z1<=cptcoveff; z1++)
2716: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2717: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2718: bool=0;
1.145 brouard 2719: /* 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",
2720: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2721: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2722: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2723: }
1.126 brouard 2724: }
1.144 brouard 2725:
1.126 brouard 2726: if (bool==1){
2727: for(m=firstpass; m<=lastpass; m++){
2728: k2=anint[m][i]+(mint[m][i]/12.);
2729: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2730: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2731: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2732: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2733: if (m<lastpass) {
2734: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2735: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2736: }
2737:
2738: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2739: dateintsum=dateintsum+k2;
2740: k2cpt++;
2741: }
2742: /*}*/
2743: }
2744: }
1.145 brouard 2745: } /* end i */
1.126 brouard 2746:
2747: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2748: pstamp(ficresp);
2749: if (cptcovn>0) {
2750: fprintf(ficresp, "\n#********** Variable ");
2751: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2752: fprintf(ficresp, "**********\n#");
1.143 brouard 2753: fprintf(ficlog, "\n#********** Variable ");
2754: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2755: fprintf(ficlog, "**********\n#");
1.126 brouard 2756: }
2757: for(i=1; i<=nlstate;i++)
2758: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2759: fprintf(ficresp, "\n");
2760:
2761: for(i=iagemin; i <= iagemax+3; i++){
2762: if(i==iagemax+3){
2763: fprintf(ficlog,"Total");
2764: }else{
2765: if(first==1){
2766: first=0;
2767: printf("See log file for details...\n");
2768: }
2769: fprintf(ficlog,"Age %d", i);
2770: }
2771: for(jk=1; jk <=nlstate ; jk++){
2772: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2773: pp[jk] += freq[jk][m][i];
2774: }
2775: for(jk=1; jk <=nlstate ; jk++){
2776: for(m=-1, pos=0; m <=0 ; m++)
2777: pos += freq[jk][m][i];
2778: if(pp[jk]>=1.e-10){
2779: if(first==1){
1.132 brouard 2780: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2781: }
2782: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2783: }else{
2784: if(first==1)
2785: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2786: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2787: }
2788: }
2789:
2790: for(jk=1; jk <=nlstate ; jk++){
2791: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2792: pp[jk] += freq[jk][m][i];
2793: }
2794: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2795: pos += pp[jk];
2796: posprop += prop[jk][i];
2797: }
2798: for(jk=1; jk <=nlstate ; jk++){
2799: if(pos>=1.e-5){
2800: if(first==1)
2801: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2802: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2803: }else{
2804: if(first==1)
2805: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2806: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2807: }
2808: if( i <= iagemax){
2809: if(pos>=1.e-5){
2810: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2811: /*probs[i][jk][j1]= pp[jk]/pos;*/
2812: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2813: }
2814: else
2815: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2816: }
2817: }
2818:
2819: for(jk=-1; jk <=nlstate+ndeath; jk++)
2820: for(m=-1; m <=nlstate+ndeath; m++)
2821: if(freq[jk][m][i] !=0 ) {
2822: if(first==1)
2823: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2824: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2825: }
2826: if(i <= iagemax)
2827: fprintf(ficresp,"\n");
2828: if(first==1)
2829: printf("Others in log...\n");
2830: fprintf(ficlog,"\n");
2831: }
1.145 brouard 2832: /*}*/
1.126 brouard 2833: }
2834: dateintmean=dateintsum/k2cpt;
2835:
2836: fclose(ficresp);
2837: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2838: free_vector(pp,1,nlstate);
2839: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2840: /* End of Freq */
2841: }
2842:
2843: /************ Prevalence ********************/
2844: 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)
2845: {
2846: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2847: in each health status at the date of interview (if between dateprev1 and dateprev2).
2848: We still use firstpass and lastpass as another selection.
2849: */
2850:
1.164 brouard 2851: int i, m, jk, j1, bool, z1,j;
2852:
2853: double **prop;
2854: double posprop;
1.126 brouard 2855: double y2; /* in fractional years */
2856: int iagemin, iagemax;
1.145 brouard 2857: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2858:
2859: iagemin= (int) agemin;
2860: iagemax= (int) agemax;
2861: /*pp=vector(1,nlstate);*/
2862: prop=matrix(1,nlstate,iagemin,iagemax+3);
2863: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2864: j1=0;
2865:
1.145 brouard 2866: /*j=cptcoveff;*/
1.126 brouard 2867: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2868:
1.145 brouard 2869: first=1;
2870: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2871: /*for(i1=1; i1<=ncodemax[k1];i1++){
2872: j1++;*/
1.126 brouard 2873:
2874: for (i=1; i<=nlstate; i++)
2875: for(m=iagemin; m <= iagemax+3; m++)
2876: prop[i][m]=0.0;
2877:
2878: for (i=1; i<=imx; i++) { /* Each individual */
2879: bool=1;
2880: if (cptcovn>0) {
2881: for (z1=1; z1<=cptcoveff; z1++)
2882: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2883: bool=0;
2884: }
2885: if (bool==1) {
2886: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2887: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2888: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2889: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2890: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2891: 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);
2892: if (s[m][i]>0 && s[m][i]<=nlstate) {
2893: /*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]]);*/
2894: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2895: prop[s[m][i]][iagemax+3] += weight[i];
2896: }
2897: }
2898: } /* end selection of waves */
2899: }
2900: }
2901: for(i=iagemin; i <= iagemax+3; i++){
2902: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2903: posprop += prop[jk][i];
2904: }
1.145 brouard 2905:
1.126 brouard 2906: for(jk=1; jk <=nlstate ; jk++){
2907: if( i <= iagemax){
2908: if(posprop>=1.e-5){
2909: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2910: } else{
2911: if(first==1){
2912: first=0;
2913: 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]);
2914: }
2915: }
1.126 brouard 2916: }
2917: }/* end jk */
2918: }/* end i */
1.145 brouard 2919: /*} *//* end i1 */
2920: } /* end j1 */
1.126 brouard 2921:
2922: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2923: /*free_vector(pp,1,nlstate);*/
2924: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2925: } /* End of prevalence */
2926:
2927: /************* Waves Concatenation ***************/
2928:
2929: 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)
2930: {
2931: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2932: Death is a valid wave (if date is known).
2933: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2934: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2935: and mw[mi+1][i]. dh depends on stepm.
2936: */
2937:
2938: int i, mi, m;
2939: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2940: double sum=0., jmean=0.;*/
2941: int first;
2942: int j, k=0,jk, ju, jl;
2943: double sum=0.;
2944: first=0;
1.164 brouard 2945: jmin=100000;
1.126 brouard 2946: jmax=-1;
2947: jmean=0.;
2948: for(i=1; i<=imx; i++){
2949: mi=0;
2950: m=firstpass;
2951: while(s[m][i] <= nlstate){
2952: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2953: mw[++mi][i]=m;
2954: if(m >=lastpass)
2955: break;
2956: else
2957: m++;
2958: }/* end while */
2959: if (s[m][i] > nlstate){
2960: mi++; /* Death is another wave */
2961: /* if(mi==0) never been interviewed correctly before death */
2962: /* Only death is a correct wave */
2963: mw[mi][i]=m;
2964: }
2965:
2966: wav[i]=mi;
2967: if(mi==0){
2968: nbwarn++;
2969: if(first==0){
2970: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2971: first=1;
2972: }
2973: if(first==1){
2974: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2975: }
2976: } /* end mi==0 */
2977: } /* End individuals */
2978:
2979: for(i=1; i<=imx; i++){
2980: for(mi=1; mi<wav[i];mi++){
2981: if (stepm <=0)
2982: dh[mi][i]=1;
2983: else{
2984: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2985: if (agedc[i] < 2*AGESUP) {
2986: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2987: if(j==0) j=1; /* Survives at least one month after exam */
2988: else if(j<0){
2989: nberr++;
2990: 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]);
2991: j=1; /* Temporary Dangerous patch */
2992: 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);
2993: 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]);
2994: 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);
2995: }
2996: k=k+1;
2997: if (j >= jmax){
2998: jmax=j;
2999: ijmax=i;
3000: }
3001: if (j <= jmin){
3002: jmin=j;
3003: ijmin=i;
3004: }
3005: sum=sum+j;
3006: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3007: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3008: }
3009: }
3010: else{
3011: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3012: /* 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]); */
3013:
3014: k=k+1;
3015: if (j >= jmax) {
3016: jmax=j;
3017: ijmax=i;
3018: }
3019: else if (j <= jmin){
3020: jmin=j;
3021: ijmin=i;
3022: }
3023: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3024: /*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]);*/
3025: if(j<0){
3026: nberr++;
3027: 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]);
3028: 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]);
3029: }
3030: sum=sum+j;
3031: }
3032: jk= j/stepm;
3033: jl= j -jk*stepm;
3034: ju= j -(jk+1)*stepm;
3035: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3036: if(jl==0){
3037: dh[mi][i]=jk;
3038: bh[mi][i]=0;
3039: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3040: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3041: dh[mi][i]=jk+1;
3042: bh[mi][i]=ju;
3043: }
3044: }else{
3045: if(jl <= -ju){
3046: dh[mi][i]=jk;
3047: bh[mi][i]=jl; /* bias is positive if real duration
3048: * is higher than the multiple of stepm and negative otherwise.
3049: */
3050: }
3051: else{
3052: dh[mi][i]=jk+1;
3053: bh[mi][i]=ju;
3054: }
3055: if(dh[mi][i]==0){
3056: dh[mi][i]=1; /* At least one step */
3057: bh[mi][i]=ju; /* At least one step */
3058: /* 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);*/
3059: }
3060: } /* end if mle */
3061: }
3062: } /* end wave */
3063: }
3064: jmean=sum/k;
3065: 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 3066: 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 3067: }
3068:
3069: /*********** Tricode ****************************/
1.145 brouard 3070: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3071: {
1.144 brouard 3072: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3073: /* 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 3074: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3075: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3076: * nbcode[Tvar[j]][1]=
1.144 brouard 3077: */
1.130 brouard 3078:
1.145 brouard 3079: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3080: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3081: int cptcode=0; /* Modality max of covariates j */
3082: int modmincovj=0; /* Modality min of covariates j */
3083:
3084:
1.126 brouard 3085: cptcoveff=0;
3086:
1.145 brouard 3087: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 3088: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3089:
1.145 brouard 3090: /* Loop on covariates without age and products */
3091: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
3092: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 3093: modality of this covariate Vj*/
1.145 brouard 3094: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3095: * If product of Vn*Vm, still boolean *:
3096: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3097: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3098: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3099: modality of the nth covariate of individual i. */
1.145 brouard 3100: if (ij > modmaxcovj)
3101: modmaxcovj=ij;
3102: else if (ij < modmincovj)
3103: modmincovj=ij;
3104: if ((ij < -1) && (ij > NCOVMAX)){
3105: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3106: exit(1);
3107: }else
1.136 brouard 3108: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3109: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3110: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3111: /* getting the maximum value of the modality of the covariate
3112: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3113: female is 1, then modmaxcovj=1.*/
1.126 brouard 3114: }
1.145 brouard 3115: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3116: cptcode=modmaxcovj;
1.137 brouard 3117: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3118: /*for (i=0; i<=cptcode; i++) {*/
3119: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3120: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3121: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3122: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3123: }
3124: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3125: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3126: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3127:
1.136 brouard 3128: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 3129: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3130: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3131: modmincovj=3; modmaxcovj = 7;
3132: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3133: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3134: variables V1_1 and V1_2.
3135: nbcode[Tvar[j]][ij]=k;
3136: nbcode[Tvar[j]][1]=0;
3137: nbcode[Tvar[j]][2]=1;
3138: nbcode[Tvar[j]][3]=2;
3139: */
3140: ij=1; /* ij is similar to i but can jumps over null modalities */
3141: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3142: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3143: /*recode from 0 */
1.131 brouard 3144: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3145: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3146: k is a modality. If we have model=V1+V1*sex
3147: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3148: ij++;
3149: }
3150: if (ij > ncodemax[j]) break;
1.137 brouard 3151: } /* end of loop on */
3152: } /* end of loop on modality */
3153: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3154:
1.145 brouard 3155: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3156:
1.145 brouard 3157: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3158: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3159: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3160: Ndum[ij]++;
3161: }
1.126 brouard 3162:
3163: ij=1;
1.145 brouard 3164: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3165: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3166: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3167: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3168: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3169: ij++;
1.145 brouard 3170: }else
3171: Tvaraff[ij]=0;
1.126 brouard 3172: }
1.131 brouard 3173: ij--;
1.144 brouard 3174: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3175:
1.126 brouard 3176: }
3177:
1.145 brouard 3178:
1.126 brouard 3179: /*********** Health Expectancies ****************/
3180:
1.127 brouard 3181: 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 3182:
3183: {
3184: /* Health expectancies, no variances */
1.164 brouard 3185: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3186: int nhstepma, nstepma; /* Decreasing with age */
3187: double age, agelim, hf;
3188: double ***p3mat;
3189: double eip;
3190:
3191: pstamp(ficreseij);
3192: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3193: fprintf(ficreseij,"# Age");
3194: for(i=1; i<=nlstate;i++){
3195: for(j=1; j<=nlstate;j++){
3196: fprintf(ficreseij," e%1d%1d ",i,j);
3197: }
3198: fprintf(ficreseij," e%1d. ",i);
3199: }
3200: fprintf(ficreseij,"\n");
3201:
3202:
3203: if(estepm < stepm){
3204: printf ("Problem %d lower than %d\n",estepm, stepm);
3205: }
3206: else hstepm=estepm;
3207: /* We compute the life expectancy from trapezoids spaced every estepm months
3208: * This is mainly to measure the difference between two models: for example
3209: * if stepm=24 months pijx are given only every 2 years and by summing them
3210: * we are calculating an estimate of the Life Expectancy assuming a linear
3211: * progression in between and thus overestimating or underestimating according
3212: * to the curvature of the survival function. If, for the same date, we
3213: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3214: * to compare the new estimate of Life expectancy with the same linear
3215: * hypothesis. A more precise result, taking into account a more precise
3216: * curvature will be obtained if estepm is as small as stepm. */
3217:
3218: /* For example we decided to compute the life expectancy with the smallest unit */
3219: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3220: nhstepm is the number of hstepm from age to agelim
3221: nstepm is the number of stepm from age to agelin.
3222: Look at hpijx to understand the reason of that which relies in memory size
3223: and note for a fixed period like estepm months */
3224: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3225: survival function given by stepm (the optimization length). Unfortunately it
3226: means that if the survival funtion is printed only each two years of age and if
3227: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3228: results. So we changed our mind and took the option of the best precision.
3229: */
3230: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3231:
3232: agelim=AGESUP;
3233: /* If stepm=6 months */
3234: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3235: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3236:
3237: /* nhstepm age range expressed in number of stepm */
3238: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3239: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3240: /* if (stepm >= YEARM) hstepm=1;*/
3241: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3242: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3243:
3244: for (age=bage; age<=fage; age ++){
3245: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3246: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3247: /* if (stepm >= YEARM) hstepm=1;*/
3248: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3249:
3250: /* If stepm=6 months */
3251: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3252: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3253:
3254: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3255:
3256: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3257:
3258: printf("%d|",(int)age);fflush(stdout);
3259: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3260:
3261: /* Computing expectancies */
3262: for(i=1; i<=nlstate;i++)
3263: for(j=1; j<=nlstate;j++)
3264: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3265: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3266:
3267: /* 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]);*/
3268:
3269: }
3270:
3271: fprintf(ficreseij,"%3.0f",age );
3272: for(i=1; i<=nlstate;i++){
3273: eip=0;
3274: for(j=1; j<=nlstate;j++){
3275: eip +=eij[i][j][(int)age];
3276: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3277: }
3278: fprintf(ficreseij,"%9.4f", eip );
3279: }
3280: fprintf(ficreseij,"\n");
3281:
3282: }
3283: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3284: printf("\n");
3285: fprintf(ficlog,"\n");
3286:
3287: }
3288:
1.127 brouard 3289: 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 3290:
3291: {
3292: /* Covariances of health expectancies eij and of total life expectancies according
3293: to initial status i, ei. .
3294: */
3295: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3296: int nhstepma, nstepma; /* Decreasing with age */
3297: double age, agelim, hf;
3298: double ***p3matp, ***p3matm, ***varhe;
3299: double **dnewm,**doldm;
3300: double *xp, *xm;
3301: double **gp, **gm;
3302: double ***gradg, ***trgradg;
3303: int theta;
3304:
3305: double eip, vip;
3306:
3307: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3308: xp=vector(1,npar);
3309: xm=vector(1,npar);
3310: dnewm=matrix(1,nlstate*nlstate,1,npar);
3311: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3312:
3313: pstamp(ficresstdeij);
3314: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3315: fprintf(ficresstdeij,"# Age");
3316: for(i=1; i<=nlstate;i++){
3317: for(j=1; j<=nlstate;j++)
3318: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3319: fprintf(ficresstdeij," e%1d. ",i);
3320: }
3321: fprintf(ficresstdeij,"\n");
3322:
3323: pstamp(ficrescveij);
3324: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3325: fprintf(ficrescveij,"# Age");
3326: for(i=1; i<=nlstate;i++)
3327: for(j=1; j<=nlstate;j++){
3328: cptj= (j-1)*nlstate+i;
3329: for(i2=1; i2<=nlstate;i2++)
3330: for(j2=1; j2<=nlstate;j2++){
3331: cptj2= (j2-1)*nlstate+i2;
3332: if(cptj2 <= cptj)
3333: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3334: }
3335: }
3336: fprintf(ficrescveij,"\n");
3337:
3338: if(estepm < stepm){
3339: printf ("Problem %d lower than %d\n",estepm, stepm);
3340: }
3341: else hstepm=estepm;
3342: /* We compute the life expectancy from trapezoids spaced every estepm months
3343: * This is mainly to measure the difference between two models: for example
3344: * if stepm=24 months pijx are given only every 2 years and by summing them
3345: * we are calculating an estimate of the Life Expectancy assuming a linear
3346: * progression in between and thus overestimating or underestimating according
3347: * to the curvature of the survival function. If, for the same date, we
3348: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3349: * to compare the new estimate of Life expectancy with the same linear
3350: * hypothesis. A more precise result, taking into account a more precise
3351: * curvature will be obtained if estepm is as small as stepm. */
3352:
3353: /* For example we decided to compute the life expectancy with the smallest unit */
3354: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3355: nhstepm is the number of hstepm from age to agelim
3356: nstepm is the number of stepm from age to agelin.
3357: Look at hpijx to understand the reason of that which relies in memory size
3358: and note for a fixed period like estepm months */
3359: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3360: survival function given by stepm (the optimization length). Unfortunately it
3361: means that if the survival funtion is printed only each two years of age and if
3362: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3363: results. So we changed our mind and took the option of the best precision.
3364: */
3365: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3366:
3367: /* If stepm=6 months */
3368: /* nhstepm age range expressed in number of stepm */
3369: agelim=AGESUP;
3370: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3371: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3372: /* if (stepm >= YEARM) hstepm=1;*/
3373: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3374:
3375: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3376: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3377: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3378: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3379: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3380: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3381:
3382: for (age=bage; age<=fage; age ++){
3383: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3384: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3385: /* if (stepm >= YEARM) hstepm=1;*/
3386: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3387:
3388: /* If stepm=6 months */
3389: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3390: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3391:
3392: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3393:
3394: /* Computing Variances of health expectancies */
3395: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3396: decrease memory allocation */
3397: for(theta=1; theta <=npar; theta++){
3398: for(i=1; i<=npar; i++){
3399: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3400: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3401: }
3402: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3403: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3404:
3405: for(j=1; j<= nlstate; j++){
3406: for(i=1; i<=nlstate; i++){
3407: for(h=0; h<=nhstepm-1; h++){
3408: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3409: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3410: }
3411: }
3412: }
3413:
3414: for(ij=1; ij<= nlstate*nlstate; ij++)
3415: for(h=0; h<=nhstepm-1; h++){
3416: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3417: }
3418: }/* End theta */
3419:
3420:
3421: for(h=0; h<=nhstepm-1; h++)
3422: for(j=1; j<=nlstate*nlstate;j++)
3423: for(theta=1; theta <=npar; theta++)
3424: trgradg[h][j][theta]=gradg[h][theta][j];
3425:
3426:
3427: for(ij=1;ij<=nlstate*nlstate;ij++)
3428: for(ji=1;ji<=nlstate*nlstate;ji++)
3429: varhe[ij][ji][(int)age] =0.;
3430:
3431: printf("%d|",(int)age);fflush(stdout);
3432: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3433: for(h=0;h<=nhstepm-1;h++){
3434: for(k=0;k<=nhstepm-1;k++){
3435: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3436: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3437: for(ij=1;ij<=nlstate*nlstate;ij++)
3438: for(ji=1;ji<=nlstate*nlstate;ji++)
3439: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3440: }
3441: }
3442:
3443: /* Computing expectancies */
3444: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3445: for(i=1; i<=nlstate;i++)
3446: for(j=1; j<=nlstate;j++)
3447: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3448: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3449:
3450: /* 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]);*/
3451:
3452: }
3453:
3454: fprintf(ficresstdeij,"%3.0f",age );
3455: for(i=1; i<=nlstate;i++){
3456: eip=0.;
3457: vip=0.;
3458: for(j=1; j<=nlstate;j++){
3459: eip += eij[i][j][(int)age];
3460: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3461: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3462: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3463: }
3464: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3465: }
3466: fprintf(ficresstdeij,"\n");
3467:
3468: fprintf(ficrescveij,"%3.0f",age );
3469: for(i=1; i<=nlstate;i++)
3470: for(j=1; j<=nlstate;j++){
3471: cptj= (j-1)*nlstate+i;
3472: for(i2=1; i2<=nlstate;i2++)
3473: for(j2=1; j2<=nlstate;j2++){
3474: cptj2= (j2-1)*nlstate+i2;
3475: if(cptj2 <= cptj)
3476: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3477: }
3478: }
3479: fprintf(ficrescveij,"\n");
3480:
3481: }
3482: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3483: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3484: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3485: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3486: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3487: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3488: printf("\n");
3489: fprintf(ficlog,"\n");
3490:
3491: free_vector(xm,1,npar);
3492: free_vector(xp,1,npar);
3493: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3494: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3495: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3496: }
3497:
3498: /************ Variance ******************/
3499: 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[])
3500: {
3501: /* Variance of health expectancies */
3502: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3503: /* double **newm;*/
1.169 brouard 3504: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3505:
3506: int movingaverage();
1.126 brouard 3507: double **dnewm,**doldm;
3508: double **dnewmp,**doldmp;
3509: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3510: int k;
1.126 brouard 3511: double *xp;
3512: double **gp, **gm; /* for var eij */
3513: double ***gradg, ***trgradg; /*for var eij */
3514: double **gradgp, **trgradgp; /* for var p point j */
3515: double *gpp, *gmp; /* for var p point j */
3516: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3517: double ***p3mat;
3518: double age,agelim, hf;
3519: double ***mobaverage;
3520: int theta;
3521: char digit[4];
3522: char digitp[25];
3523:
3524: char fileresprobmorprev[FILENAMELENGTH];
3525:
3526: if(popbased==1){
3527: if(mobilav!=0)
3528: strcpy(digitp,"-populbased-mobilav-");
3529: else strcpy(digitp,"-populbased-nomobil-");
3530: }
3531: else
3532: strcpy(digitp,"-stablbased-");
3533:
3534: if (mobilav!=0) {
3535: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3536: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3537: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3538: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3539: }
3540: }
3541:
3542: strcpy(fileresprobmorprev,"prmorprev");
3543: sprintf(digit,"%-d",ij);
3544: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3545: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3546: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3547: strcat(fileresprobmorprev,fileres);
3548: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3549: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3550: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3551: }
3552: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3553:
3554: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3555: pstamp(ficresprobmorprev);
3556: 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);
3557: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3558: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3559: fprintf(ficresprobmorprev," p.%-d SE",j);
3560: for(i=1; i<=nlstate;i++)
3561: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3562: }
3563: fprintf(ficresprobmorprev,"\n");
3564: fprintf(ficgp,"\n# Routine varevsij");
3565: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3566: 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");
3567: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3568: /* } */
3569: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3570: pstamp(ficresvij);
3571: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3572: if(popbased==1)
1.128 brouard 3573: 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 3574: else
3575: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3576: fprintf(ficresvij,"# Age");
3577: for(i=1; i<=nlstate;i++)
3578: for(j=1; j<=nlstate;j++)
3579: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3580: fprintf(ficresvij,"\n");
3581:
3582: xp=vector(1,npar);
3583: dnewm=matrix(1,nlstate,1,npar);
3584: doldm=matrix(1,nlstate,1,nlstate);
3585: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3586: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3587:
3588: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3589: gpp=vector(nlstate+1,nlstate+ndeath);
3590: gmp=vector(nlstate+1,nlstate+ndeath);
3591: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3592:
3593: if(estepm < stepm){
3594: printf ("Problem %d lower than %d\n",estepm, stepm);
3595: }
3596: else hstepm=estepm;
3597: /* For example we decided to compute the life expectancy with the smallest unit */
3598: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3599: nhstepm is the number of hstepm from age to agelim
3600: nstepm is the number of stepm from age to agelin.
1.128 brouard 3601: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3602: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3603: survival function given by stepm (the optimization length). Unfortunately it
3604: means that if the survival funtion is printed every two years of age and if
3605: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3606: results. So we changed our mind and took the option of the best precision.
3607: */
3608: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3609: agelim = AGESUP;
3610: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3611: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3612: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3613: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3614: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3615: gp=matrix(0,nhstepm,1,nlstate);
3616: gm=matrix(0,nhstepm,1,nlstate);
3617:
3618:
3619: for(theta=1; theta <=npar; theta++){
3620: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3621: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3622: }
3623: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3624: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3625:
3626: if (popbased==1) {
3627: if(mobilav ==0){
3628: for(i=1; i<=nlstate;i++)
3629: prlim[i][i]=probs[(int)age][i][ij];
3630: }else{ /* mobilav */
3631: for(i=1; i<=nlstate;i++)
3632: prlim[i][i]=mobaverage[(int)age][i][ij];
3633: }
3634: }
3635:
3636: for(j=1; j<= nlstate; j++){
3637: for(h=0; h<=nhstepm; h++){
3638: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3639: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3640: }
3641: }
3642: /* This for computing probability of death (h=1 means
3643: computed over hstepm matrices product = hstepm*stepm months)
3644: as a weighted average of prlim.
3645: */
3646: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3647: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3648: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3649: }
3650: /* end probability of death */
3651:
3652: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3653: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3654: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3655: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3656:
3657: if (popbased==1) {
3658: if(mobilav ==0){
3659: for(i=1; i<=nlstate;i++)
3660: prlim[i][i]=probs[(int)age][i][ij];
3661: }else{ /* mobilav */
3662: for(i=1; i<=nlstate;i++)
3663: prlim[i][i]=mobaverage[(int)age][i][ij];
3664: }
3665: }
3666:
1.128 brouard 3667: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3668: for(h=0; h<=nhstepm; h++){
3669: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3670: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3671: }
3672: }
3673: /* This for computing probability of death (h=1 means
3674: computed over hstepm matrices product = hstepm*stepm months)
3675: as a weighted average of prlim.
3676: */
3677: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3678: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3679: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3680: }
3681: /* end probability of death */
3682:
3683: for(j=1; j<= nlstate; j++) /* vareij */
3684: for(h=0; h<=nhstepm; h++){
3685: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3686: }
3687:
3688: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3689: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3690: }
3691:
3692: } /* End theta */
3693:
3694: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3695:
3696: for(h=0; h<=nhstepm; h++) /* veij */
3697: for(j=1; j<=nlstate;j++)
3698: for(theta=1; theta <=npar; theta++)
3699: trgradg[h][j][theta]=gradg[h][theta][j];
3700:
3701: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3702: for(theta=1; theta <=npar; theta++)
3703: trgradgp[j][theta]=gradgp[theta][j];
3704:
3705:
3706: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3707: for(i=1;i<=nlstate;i++)
3708: for(j=1;j<=nlstate;j++)
3709: vareij[i][j][(int)age] =0.;
3710:
3711: for(h=0;h<=nhstepm;h++){
3712: for(k=0;k<=nhstepm;k++){
3713: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3714: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3715: for(i=1;i<=nlstate;i++)
3716: for(j=1;j<=nlstate;j++)
3717: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3718: }
3719: }
3720:
3721: /* pptj */
3722: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3723: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3724: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3725: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3726: varppt[j][i]=doldmp[j][i];
3727: /* end ppptj */
3728: /* x centered again */
3729: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3730: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3731:
3732: if (popbased==1) {
3733: if(mobilav ==0){
3734: for(i=1; i<=nlstate;i++)
3735: prlim[i][i]=probs[(int)age][i][ij];
3736: }else{ /* mobilav */
3737: for(i=1; i<=nlstate;i++)
3738: prlim[i][i]=mobaverage[(int)age][i][ij];
3739: }
3740: }
3741:
3742: /* This for computing probability of death (h=1 means
3743: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3744: as a weighted average of prlim.
3745: */
3746: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3747: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3748: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3749: }
3750: /* end probability of death */
3751:
3752: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3753: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3754: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3755: for(i=1; i<=nlstate;i++){
3756: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3757: }
3758: }
3759: fprintf(ficresprobmorprev,"\n");
3760:
3761: fprintf(ficresvij,"%.0f ",age );
3762: for(i=1; i<=nlstate;i++)
3763: for(j=1; j<=nlstate;j++){
3764: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3765: }
3766: fprintf(ficresvij,"\n");
3767: free_matrix(gp,0,nhstepm,1,nlstate);
3768: free_matrix(gm,0,nhstepm,1,nlstate);
3769: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3770: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3771: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3772: } /* End age */
3773: free_vector(gpp,nlstate+1,nlstate+ndeath);
3774: free_vector(gmp,nlstate+1,nlstate+ndeath);
3775: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3776: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3777: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3778: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3779: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3780: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3781: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3782: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3783: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3784: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3785: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3786: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3787: 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);
3788: /* 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);
3789: */
3790: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3791: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3792:
3793: free_vector(xp,1,npar);
3794: free_matrix(doldm,1,nlstate,1,nlstate);
3795: free_matrix(dnewm,1,nlstate,1,npar);
3796: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3797: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3798: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3799: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3800: fclose(ficresprobmorprev);
3801: fflush(ficgp);
3802: fflush(fichtm);
3803: } /* end varevsij */
3804:
3805: /************ Variance of prevlim ******************/
3806: 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[])
3807: {
3808: /* Variance of prevalence limit */
3809: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3810:
1.126 brouard 3811: double **dnewm,**doldm;
3812: int i, j, nhstepm, hstepm;
3813: double *xp;
3814: double *gp, *gm;
3815: double **gradg, **trgradg;
3816: double age,agelim;
3817: int theta;
3818:
3819: pstamp(ficresvpl);
3820: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3821: fprintf(ficresvpl,"# Age");
3822: for(i=1; i<=nlstate;i++)
3823: fprintf(ficresvpl," %1d-%1d",i,i);
3824: fprintf(ficresvpl,"\n");
3825:
3826: xp=vector(1,npar);
3827: dnewm=matrix(1,nlstate,1,npar);
3828: doldm=matrix(1,nlstate,1,nlstate);
3829:
3830: hstepm=1*YEARM; /* Every year of age */
3831: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3832: agelim = AGESUP;
3833: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3834: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3835: if (stepm >= YEARM) hstepm=1;
3836: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3837: gradg=matrix(1,npar,1,nlstate);
3838: gp=vector(1,nlstate);
3839: gm=vector(1,nlstate);
3840:
3841: for(theta=1; theta <=npar; theta++){
3842: for(i=1; i<=npar; i++){ /* Computes gradient */
3843: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3844: }
3845: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3846: for(i=1;i<=nlstate;i++)
3847: gp[i] = prlim[i][i];
3848:
3849: for(i=1; i<=npar; i++) /* Computes gradient */
3850: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3851: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3852: for(i=1;i<=nlstate;i++)
3853: gm[i] = prlim[i][i];
3854:
3855: for(i=1;i<=nlstate;i++)
3856: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3857: } /* End theta */
3858:
3859: trgradg =matrix(1,nlstate,1,npar);
3860:
3861: for(j=1; j<=nlstate;j++)
3862: for(theta=1; theta <=npar; theta++)
3863: trgradg[j][theta]=gradg[theta][j];
3864:
3865: for(i=1;i<=nlstate;i++)
3866: varpl[i][(int)age] =0.;
3867: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3868: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3869: for(i=1;i<=nlstate;i++)
3870: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3871:
3872: fprintf(ficresvpl,"%.0f ",age );
3873: for(i=1; i<=nlstate;i++)
3874: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3875: fprintf(ficresvpl,"\n");
3876: free_vector(gp,1,nlstate);
3877: free_vector(gm,1,nlstate);
3878: free_matrix(gradg,1,npar,1,nlstate);
3879: free_matrix(trgradg,1,nlstate,1,npar);
3880: } /* End age */
3881:
3882: free_vector(xp,1,npar);
3883: free_matrix(doldm,1,nlstate,1,npar);
3884: free_matrix(dnewm,1,nlstate,1,nlstate);
3885:
3886: }
3887:
3888: /************ Variance of one-step probabilities ******************/
3889: 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[])
3890: {
1.164 brouard 3891: int i, j=0, k1, l1, tj;
1.126 brouard 3892: int k2, l2, j1, z1;
1.164 brouard 3893: int k=0, l;
1.145 brouard 3894: int first=1, first1, first2;
1.126 brouard 3895: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3896: double **dnewm,**doldm;
3897: double *xp;
3898: double *gp, *gm;
3899: double **gradg, **trgradg;
3900: double **mu;
1.164 brouard 3901: double age, cov[NCOVMAX+1];
1.126 brouard 3902: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3903: int theta;
3904: char fileresprob[FILENAMELENGTH];
3905: char fileresprobcov[FILENAMELENGTH];
3906: char fileresprobcor[FILENAMELENGTH];
3907: double ***varpij;
3908:
3909: strcpy(fileresprob,"prob");
3910: strcat(fileresprob,fileres);
3911: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3912: printf("Problem with resultfile: %s\n", fileresprob);
3913: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3914: }
3915: strcpy(fileresprobcov,"probcov");
3916: strcat(fileresprobcov,fileres);
3917: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3918: printf("Problem with resultfile: %s\n", fileresprobcov);
3919: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3920: }
3921: strcpy(fileresprobcor,"probcor");
3922: strcat(fileresprobcor,fileres);
3923: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3924: printf("Problem with resultfile: %s\n", fileresprobcor);
3925: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3926: }
3927: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3928: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3929: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3930: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3931: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3932: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3933: pstamp(ficresprob);
3934: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3935: fprintf(ficresprob,"# Age");
3936: pstamp(ficresprobcov);
3937: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3938: fprintf(ficresprobcov,"# Age");
3939: pstamp(ficresprobcor);
3940: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3941: fprintf(ficresprobcor,"# Age");
3942:
3943:
3944: for(i=1; i<=nlstate;i++)
3945: for(j=1; j<=(nlstate+ndeath);j++){
3946: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3947: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3948: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3949: }
3950: /* fprintf(ficresprob,"\n");
3951: fprintf(ficresprobcov,"\n");
3952: fprintf(ficresprobcor,"\n");
3953: */
1.131 brouard 3954: xp=vector(1,npar);
1.126 brouard 3955: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3956: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3957: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3958: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3959: first=1;
3960: fprintf(ficgp,"\n# Routine varprob");
3961: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3962: fprintf(fichtm,"\n");
3963:
3964: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3965: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3966: file %s<br>\n",optionfilehtmcov);
3967: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3968: and drawn. It helps understanding how is the covariance between two incidences.\
3969: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3970: 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. \
3971: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3972: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3973: standard deviations wide on each axis. <br>\
3974: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3975: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3976: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3977:
3978: cov[1]=1;
1.145 brouard 3979: /* tj=cptcoveff; */
3980: tj = (int) pow(2,cptcoveff);
1.126 brouard 3981: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3982: j1=0;
1.145 brouard 3983: for(j1=1; j1<=tj;j1++){
3984: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3985: /*j1++;*/
1.126 brouard 3986: if (cptcovn>0) {
3987: fprintf(ficresprob, "\n#********** Variable ");
3988: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3989: fprintf(ficresprob, "**********\n#\n");
3990: fprintf(ficresprobcov, "\n#********** Variable ");
3991: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3992: fprintf(ficresprobcov, "**********\n#\n");
3993:
3994: fprintf(ficgp, "\n#********** Variable ");
3995: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3996: fprintf(ficgp, "**********\n#\n");
3997:
3998:
3999: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4000: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4001: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4002:
4003: fprintf(ficresprobcor, "\n#********** Variable ");
4004: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
4005: fprintf(ficresprobcor, "**********\n#");
4006: }
4007:
1.145 brouard 4008: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4009: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4010: gp=vector(1,(nlstate)*(nlstate+ndeath));
4011: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4012: for (age=bage; age<=fage; age ++){
4013: cov[2]=age;
4014: for (k=1; k<=cptcovn;k++) {
1.145 brouard 4015: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
4016: * 1 1 1 1 1
4017: * 2 2 1 1 1
4018: * 3 1 2 1 1
4019: */
4020: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4021: }
4022: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
4023: for (k=1; k<=cptcovprod;k++)
4024: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
4025:
4026:
4027: for(theta=1; theta <=npar; theta++){
4028: for(i=1; i<=npar; i++)
4029: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4030:
4031: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4032:
4033: k=0;
4034: for(i=1; i<= (nlstate); i++){
4035: for(j=1; j<=(nlstate+ndeath);j++){
4036: k=k+1;
4037: gp[k]=pmmij[i][j];
4038: }
4039: }
4040:
4041: for(i=1; i<=npar; i++)
4042: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4043:
4044: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4045: k=0;
4046: for(i=1; i<=(nlstate); i++){
4047: for(j=1; j<=(nlstate+ndeath);j++){
4048: k=k+1;
4049: gm[k]=pmmij[i][j];
4050: }
4051: }
4052:
4053: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4054: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4055: }
4056:
4057: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4058: for(theta=1; theta <=npar; theta++)
4059: trgradg[j][theta]=gradg[theta][j];
4060:
4061: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4062: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4063:
4064: pmij(pmmij,cov,ncovmodel,x,nlstate);
4065:
4066: k=0;
4067: for(i=1; i<=(nlstate); i++){
4068: for(j=1; j<=(nlstate+ndeath);j++){
4069: k=k+1;
4070: mu[k][(int) age]=pmmij[i][j];
4071: }
4072: }
4073: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4074: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4075: varpij[i][j][(int)age] = doldm[i][j];
4076:
4077: /*printf("\n%d ",(int)age);
4078: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4079: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4080: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4081: }*/
4082:
4083: fprintf(ficresprob,"\n%d ",(int)age);
4084: fprintf(ficresprobcov,"\n%d ",(int)age);
4085: fprintf(ficresprobcor,"\n%d ",(int)age);
4086:
4087: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4088: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4089: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4090: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4091: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4092: }
4093: i=0;
4094: for (k=1; k<=(nlstate);k++){
4095: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4096: i++;
1.126 brouard 4097: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4098: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4099: for (j=1; j<=i;j++){
1.145 brouard 4100: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4101: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4102: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4103: }
4104: }
4105: }/* end of loop for state */
4106: } /* end of loop for age */
1.145 brouard 4107: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4108: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4109: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4110: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4111:
1.126 brouard 4112: /* Confidence intervalle of pij */
4113: /*
1.131 brouard 4114: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4115: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4116: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4117: 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);
4118: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4119: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4120: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4121: */
4122:
4123: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4124: first1=1;first2=2;
1.126 brouard 4125: for (k2=1; k2<=(nlstate);k2++){
4126: for (l2=1; l2<=(nlstate+ndeath);l2++){
4127: if(l2==k2) continue;
4128: j=(k2-1)*(nlstate+ndeath)+l2;
4129: for (k1=1; k1<=(nlstate);k1++){
4130: for (l1=1; l1<=(nlstate+ndeath);l1++){
4131: if(l1==k1) continue;
4132: i=(k1-1)*(nlstate+ndeath)+l1;
4133: if(i<=j) continue;
4134: for (age=bage; age<=fage; age ++){
4135: if ((int)age %5==0){
4136: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4137: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4138: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4139: mu1=mu[i][(int) age]/stepm*YEARM ;
4140: mu2=mu[j][(int) age]/stepm*YEARM;
4141: c12=cv12/sqrt(v1*v2);
4142: /* Computing eigen value of matrix of covariance */
4143: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4144: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4145: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4146: if(first2==1){
4147: first1=0;
4148: 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);
4149: }
4150: 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);
4151: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4152: /* lc2=fabs(lc2); */
1.135 brouard 4153: }
4154:
1.126 brouard 4155: /* Eigen vectors */
4156: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4157: /*v21=sqrt(1.-v11*v11); *//* error */
4158: v21=(lc1-v1)/cv12*v11;
4159: v12=-v21;
4160: v22=v11;
4161: tnalp=v21/v11;
4162: if(first1==1){
4163: first1=0;
4164: 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);
4165: }
4166: 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);
4167: /*printf(fignu*/
4168: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4169: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4170: if(first==1){
4171: first=0;
4172: fprintf(ficgp,"\nset parametric;unset label");
4173: 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 4174: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4175: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4176: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4177: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4178: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4179: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4180: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4181: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4182: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4183: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4184: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4185: 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",\
4186: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4187: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4188: }else{
4189: first=0;
4190: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4191: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4192: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4193: 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",\
4194: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4195: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4196: }/* if first */
4197: } /* age mod 5 */
4198: } /* end loop age */
4199: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4200: first=1;
4201: } /*l12 */
4202: } /* k12 */
4203: } /*l1 */
4204: }/* k1 */
1.169 brouard 4205: /* } */ /* loop covariates */
1.126 brouard 4206: }
4207: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4208: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4209: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4210: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4211: free_vector(xp,1,npar);
4212: fclose(ficresprob);
4213: fclose(ficresprobcov);
4214: fclose(ficresprobcor);
4215: fflush(ficgp);
4216: fflush(fichtmcov);
4217: }
4218:
4219:
4220: /******************* Printing html file ***********/
4221: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4222: int lastpass, int stepm, int weightopt, char model[],\
4223: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4224: int popforecast, int estepm ,\
4225: double jprev1, double mprev1,double anprev1, \
4226: double jprev2, double mprev2,double anprev2){
4227: int jj1, k1, i1, cpt;
4228:
4229: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4230: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4231: </ul>");
4232: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4233: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4234: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4235: fprintf(fichtm,"\
4236: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4237: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4238: fprintf(fichtm,"\
4239: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4240: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4241: fprintf(fichtm,"\
1.128 brouard 4242: - (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 4243: <a href=\"%s\">%s</a> <br>\n",
4244: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4245: fprintf(fichtm,"\
4246: - Population projections by age and states: \
4247: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4248:
4249: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4250:
1.145 brouard 4251: m=pow(2,cptcoveff);
1.126 brouard 4252: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4253:
4254: jj1=0;
4255: for(k1=1; k1<=m;k1++){
4256: for(i1=1; i1<=ncodemax[k1];i1++){
4257: jj1++;
4258: if (cptcovn > 0) {
4259: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4260: for (cpt=1; cpt<=cptcoveff;cpt++)
4261: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4262: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4263: }
4264: /* Pij */
1.145 brouard 4265: 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> \
4266: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4267: /* Quasi-incidences */
4268: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4269: 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> \
4270: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4271: /* Period (stable) prevalence in each health state */
1.154 brouard 4272: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4273: 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> \
4274: <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 4275: }
4276: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4277: 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> \
4278: <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 4279: }
4280: } /* end i1 */
4281: }/* End k1 */
4282: fprintf(fichtm,"</ul>");
4283:
4284:
4285: fprintf(fichtm,"\
4286: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4287: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4288:
4289: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4290: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4291: fprintf(fichtm,"\
4292: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4293: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4294:
4295: fprintf(fichtm,"\
4296: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4297: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4298: fprintf(fichtm,"\
4299: - 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): \
4300: <a href=\"%s\">%s</a> <br>\n</li>",
4301: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4302: fprintf(fichtm,"\
4303: - (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): \
4304: <a href=\"%s\">%s</a> <br>\n</li>",
4305: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4306: fprintf(fichtm,"\
1.128 brouard 4307: - 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 4308: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4309: fprintf(fichtm,"\
1.128 brouard 4310: - 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",
4311: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4312: fprintf(fichtm,"\
4313: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4314: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4315:
4316: /* if(popforecast==1) fprintf(fichtm,"\n */
4317: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4318: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4319: /* <br>",fileres,fileres,fileres,fileres); */
4320: /* else */
4321: /* 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); */
4322: fflush(fichtm);
4323: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4324:
1.145 brouard 4325: m=pow(2,cptcoveff);
1.126 brouard 4326: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4327:
4328: jj1=0;
4329: for(k1=1; k1<=m;k1++){
4330: for(i1=1; i1<=ncodemax[k1];i1++){
4331: jj1++;
4332: if (cptcovn > 0) {
4333: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4334: for (cpt=1; cpt<=cptcoveff;cpt++)
4335: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4336: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4337: }
4338: for(cpt=1; cpt<=nlstate;cpt++) {
4339: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4340: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4341: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4342: }
4343: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4344: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4345: true period expectancies (those weighted with period prevalences are also\
4346: drawn in addition to the population based expectancies computed using\
4347: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4348: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4349: } /* end i1 */
4350: }/* End k1 */
4351: fprintf(fichtm,"</ul>");
4352: fflush(fichtm);
4353: }
4354:
4355: /******************* Gnuplot file **************/
4356: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4357:
4358: char dirfileres[132],optfileres[132];
1.164 brouard 4359: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4360: int ng=0;
1.126 brouard 4361: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4362: /* printf("Problem with file %s",optionfilegnuplot); */
4363: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4364: /* } */
4365:
4366: /*#ifdef windows */
4367: fprintf(ficgp,"cd \"%s\" \n",pathc);
4368: /*#endif */
4369: m=pow(2,cptcoveff);
4370:
4371: strcpy(dirfileres,optionfilefiname);
4372: strcpy(optfileres,"vpl");
4373: /* 1eme*/
1.153 brouard 4374: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4375: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4376: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4377: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4378: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4379: fprintf(ficgp,"set xlabel \"Age\" \n\
4380: set ylabel \"Probability\" \n\
1.145 brouard 4381: set ter png small size 320, 240\n\
1.170 brouard 4382: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4383:
4384: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4385: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4386: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4387: }
1.170 brouard 4388: 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 4389: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4390: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4391: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4392: }
1.170 brouard 4393: 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 4394: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4395: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4396: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4397: }
1.145 brouard 4398: 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 4399: }
4400: }
4401: /*2 eme*/
1.153 brouard 4402: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4403: for (k1=1; k1<= m ; k1 ++) {
4404: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4405: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4406:
4407: for (i=1; i<= nlstate+1 ; i ++) {
4408: k=2*i;
1.170 brouard 4409: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4410: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4411: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4412: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4413: }
4414: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4415: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4416: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4417: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4418: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4419: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4420: }
1.145 brouard 4421: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4422: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4423: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4424: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4425: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4426: }
1.145 brouard 4427: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4428: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4429: }
4430: }
4431:
4432: /*3eme*/
4433:
4434: for (k1=1; k1<= m ; k1 ++) {
4435: for (cpt=1; cpt<= nlstate ; cpt ++) {
4436: /* k=2+nlstate*(2*cpt-2); */
4437: k=2+(nlstate+1)*(cpt-1);
4438: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4439: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4440: 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);
4441: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4442: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4443: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4444: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4445: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4446: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4447:
4448: */
4449: for (i=1; i< nlstate ; i ++) {
4450: 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);
4451: /* 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);*/
4452:
4453: }
4454: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4455: }
4456: }
4457:
4458: /* CV preval stable (period) */
1.153 brouard 4459: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4460: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4461: k=3;
1.153 brouard 4462: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4463: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4464: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4465: set ter png small size 320, 240\n\
1.126 brouard 4466: unset log y\n\
1.153 brouard 4467: plot [%.f:%.f] ", ageminpar, agemaxpar);
4468: for (i=1; i<= nlstate ; i ++){
4469: if(i==1)
4470: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4471: else
4472: fprintf(ficgp,", '' ");
1.154 brouard 4473: l=(nlstate+ndeath)*(i-1)+1;
4474: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4475: for (j=1; j<= (nlstate-1) ; j ++)
4476: fprintf(ficgp,"+$%d",k+l+j);
4477: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4478: } /* nlstate */
4479: fprintf(ficgp,"\n");
4480: } /* end cpt state*/
4481: } /* end covariate */
1.126 brouard 4482:
4483: /* proba elementaires */
4484: for(i=1,jk=1; i <=nlstate; i++){
4485: for(k=1; k <=(nlstate+ndeath); k++){
4486: if (k != i) {
4487: for(j=1; j <=ncovmodel; j++){
4488: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4489: jk++;
4490: fprintf(ficgp,"\n");
4491: }
4492: }
4493: }
4494: }
1.145 brouard 4495: /*goto avoid;*/
1.126 brouard 4496: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4497: for(jk=1; jk <=m; jk++) {
1.145 brouard 4498: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4499: if (ng==2)
4500: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4501: else
4502: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4503: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4504: i=1;
4505: for(k2=1; k2<=nlstate; k2++) {
4506: k3=i;
4507: for(k=1; k<=(nlstate+ndeath); k++) {
4508: if (k != k2){
4509: if(ng==2)
4510: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4511: else
4512: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4513: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4514: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4515: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4516: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4517: /* ij++; */
4518: /* } */
4519: /* else */
1.126 brouard 4520: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4521: }
4522: fprintf(ficgp,")/(1");
4523:
4524: for(k1=1; k1 <=nlstate; k1++){
4525: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4526: ij=1;
4527: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4528: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4529: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4530: /* ij++; */
4531: /* } */
4532: /* else */
1.126 brouard 4533: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4534: }
4535: fprintf(ficgp,")");
4536: }
4537: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4538: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4539: i=i+ncovmodel;
4540: }
4541: } /* end k */
4542: } /* end k2 */
4543: } /* end jk */
4544: } /* end ng */
1.164 brouard 4545: /* avoid: */
1.126 brouard 4546: fflush(ficgp);
4547: } /* end gnuplot */
4548:
4549:
4550: /*************** Moving average **************/
4551: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4552:
4553: int i, cpt, cptcod;
4554: int modcovmax =1;
4555: int mobilavrange, mob;
4556: double age;
4557:
4558: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4559: a covariate has 2 modalities */
4560: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4561:
4562: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4563: if(mobilav==1) mobilavrange=5; /* default */
4564: else mobilavrange=mobilav;
4565: for (age=bage; age<=fage; age++)
4566: for (i=1; i<=nlstate;i++)
4567: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4568: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4569: /* We keep the original values on the extreme ages bage, fage and for
4570: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4571: we use a 5 terms etc. until the borders are no more concerned.
4572: */
4573: for (mob=3;mob <=mobilavrange;mob=mob+2){
4574: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4575: for (i=1; i<=nlstate;i++){
4576: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4577: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4578: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4579: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4580: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4581: }
4582: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4583: }
4584: }
4585: }/* end age */
4586: }/* end mob */
4587: }else return -1;
4588: return 0;
4589: }/* End movingaverage */
4590:
4591:
4592: /************** Forecasting ******************/
1.169 brouard 4593: 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 4594: /* proj1, year, month, day of starting projection
4595: agemin, agemax range of age
4596: dateprev1 dateprev2 range of dates during which prevalence is computed
4597: anproj2 year of en of projection (same day and month as proj1).
4598: */
1.164 brouard 4599: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4600: double agec; /* generic age */
4601: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4602: double *popeffectif,*popcount;
4603: double ***p3mat;
4604: double ***mobaverage;
4605: char fileresf[FILENAMELENGTH];
4606:
4607: agelim=AGESUP;
4608: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4609:
4610: strcpy(fileresf,"f");
4611: strcat(fileresf,fileres);
4612: if((ficresf=fopen(fileresf,"w"))==NULL) {
4613: printf("Problem with forecast resultfile: %s\n", fileresf);
4614: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4615: }
4616: printf("Computing forecasting: result on file '%s' \n", fileresf);
4617: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4618:
4619: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4620:
4621: if (mobilav!=0) {
4622: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4623: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4624: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4625: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4626: }
4627: }
4628:
4629: stepsize=(int) (stepm+YEARM-1)/YEARM;
4630: if (stepm<=12) stepsize=1;
4631: if(estepm < stepm){
4632: printf ("Problem %d lower than %d\n",estepm, stepm);
4633: }
4634: else hstepm=estepm;
4635:
4636: hstepm=hstepm/stepm;
4637: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4638: fractional in yp1 */
4639: anprojmean=yp;
4640: yp2=modf((yp1*12),&yp);
4641: mprojmean=yp;
4642: yp1=modf((yp2*30.5),&yp);
4643: jprojmean=yp;
4644: if(jprojmean==0) jprojmean=1;
4645: if(mprojmean==0) jprojmean=1;
4646:
4647: i1=cptcoveff;
4648: if (cptcovn < 1){i1=1;}
4649:
4650: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4651:
4652: fprintf(ficresf,"#****** Routine prevforecast **\n");
4653:
4654: /* if (h==(int)(YEARM*yearp)){ */
4655: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4656: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4657: k=k+1;
4658: fprintf(ficresf,"\n#******");
4659: for(j=1;j<=cptcoveff;j++) {
4660: 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]]);
4661: }
4662: fprintf(ficresf,"******\n");
4663: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4664: for(j=1; j<=nlstate+ndeath;j++){
4665: for(i=1; i<=nlstate;i++)
4666: fprintf(ficresf," p%d%d",i,j);
4667: fprintf(ficresf," p.%d",j);
4668: }
4669: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4670: fprintf(ficresf,"\n");
4671: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4672:
4673: for (agec=fage; agec>=(ageminpar-1); agec--){
4674: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4675: nhstepm = nhstepm/hstepm;
4676: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4677: oldm=oldms;savm=savms;
4678: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4679:
4680: for (h=0; h<=nhstepm; h++){
4681: if (h*hstepm/YEARM*stepm ==yearp) {
4682: fprintf(ficresf,"\n");
4683: for(j=1;j<=cptcoveff;j++)
4684: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4685: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4686: }
4687: for(j=1; j<=nlstate+ndeath;j++) {
4688: ppij=0.;
4689: for(i=1; i<=nlstate;i++) {
4690: if (mobilav==1)
4691: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4692: else {
4693: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4694: }
4695: if (h*hstepm/YEARM*stepm== yearp) {
4696: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4697: }
4698: } /* end i */
4699: if (h*hstepm/YEARM*stepm==yearp) {
4700: fprintf(ficresf," %.3f", ppij);
4701: }
4702: }/* end j */
4703: } /* end h */
4704: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4705: } /* end agec */
4706: } /* end yearp */
4707: } /* end cptcod */
4708: } /* end cptcov */
4709:
4710: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4711:
4712: fclose(ficresf);
4713: }
4714:
4715: /************** Forecasting *****not tested NB*************/
1.169 brouard 4716: 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 4717:
4718: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4719: int *popage;
4720: double calagedatem, agelim, kk1, kk2;
4721: double *popeffectif,*popcount;
4722: double ***p3mat,***tabpop,***tabpopprev;
4723: double ***mobaverage;
4724: char filerespop[FILENAMELENGTH];
4725:
4726: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4727: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4728: agelim=AGESUP;
4729: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4730:
4731: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4732:
4733:
4734: strcpy(filerespop,"pop");
4735: strcat(filerespop,fileres);
4736: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4737: printf("Problem with forecast resultfile: %s\n", filerespop);
4738: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4739: }
4740: printf("Computing forecasting: result on file '%s' \n", filerespop);
4741: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4742:
4743: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4744:
4745: if (mobilav!=0) {
4746: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4747: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4748: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4749: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4750: }
4751: }
4752:
4753: stepsize=(int) (stepm+YEARM-1)/YEARM;
4754: if (stepm<=12) stepsize=1;
4755:
4756: agelim=AGESUP;
4757:
4758: hstepm=1;
4759: hstepm=hstepm/stepm;
4760:
4761: if (popforecast==1) {
4762: if((ficpop=fopen(popfile,"r"))==NULL) {
4763: printf("Problem with population file : %s\n",popfile);exit(0);
4764: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4765: }
4766: popage=ivector(0,AGESUP);
4767: popeffectif=vector(0,AGESUP);
4768: popcount=vector(0,AGESUP);
4769:
4770: i=1;
4771: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4772:
4773: imx=i;
4774: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4775: }
4776:
4777: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4778: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4779: k=k+1;
4780: fprintf(ficrespop,"\n#******");
4781: for(j=1;j<=cptcoveff;j++) {
4782: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4783: }
4784: fprintf(ficrespop,"******\n");
4785: fprintf(ficrespop,"# Age");
4786: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4787: if (popforecast==1) fprintf(ficrespop," [Population]");
4788:
4789: for (cpt=0; cpt<=0;cpt++) {
4790: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4791:
4792: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4793: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4794: nhstepm = nhstepm/hstepm;
4795:
4796: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4797: oldm=oldms;savm=savms;
4798: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4799:
4800: for (h=0; h<=nhstepm; h++){
4801: if (h==(int) (calagedatem+YEARM*cpt)) {
4802: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4803: }
4804: for(j=1; j<=nlstate+ndeath;j++) {
4805: kk1=0.;kk2=0;
4806: for(i=1; i<=nlstate;i++) {
4807: if (mobilav==1)
4808: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4809: else {
4810: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4811: }
4812: }
4813: if (h==(int)(calagedatem+12*cpt)){
4814: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4815: /*fprintf(ficrespop," %.3f", kk1);
4816: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4817: }
4818: }
4819: for(i=1; i<=nlstate;i++){
4820: kk1=0.;
4821: for(j=1; j<=nlstate;j++){
4822: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4823: }
4824: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4825: }
4826:
4827: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4828: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4829: }
4830: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4831: }
4832: }
4833:
4834: /******/
4835:
4836: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4837: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4838: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4839: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4840: nhstepm = nhstepm/hstepm;
4841:
4842: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4843: oldm=oldms;savm=savms;
4844: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4845: for (h=0; h<=nhstepm; h++){
4846: if (h==(int) (calagedatem+YEARM*cpt)) {
4847: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4848: }
4849: for(j=1; j<=nlstate+ndeath;j++) {
4850: kk1=0.;kk2=0;
4851: for(i=1; i<=nlstate;i++) {
4852: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4853: }
4854: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4855: }
4856: }
4857: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4858: }
4859: }
4860: }
4861: }
4862:
4863: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4864:
4865: if (popforecast==1) {
4866: free_ivector(popage,0,AGESUP);
4867: free_vector(popeffectif,0,AGESUP);
4868: free_vector(popcount,0,AGESUP);
4869: }
4870: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4871: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4872: fclose(ficrespop);
4873: } /* End of popforecast */
4874:
4875: int fileappend(FILE *fichier, char *optionfich)
4876: {
4877: if((fichier=fopen(optionfich,"a"))==NULL) {
4878: printf("Problem with file: %s\n", optionfich);
4879: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4880: return (0);
4881: }
4882: fflush(fichier);
4883: return (1);
4884: }
4885:
4886:
4887: /**************** function prwizard **********************/
4888: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4889: {
4890:
4891: /* Wizard to print covariance matrix template */
4892:
1.164 brouard 4893: char ca[32], cb[32];
4894: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4895: int numlinepar;
4896:
4897: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4898: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4899: for(i=1; i <=nlstate; i++){
4900: jj=0;
4901: for(j=1; j <=nlstate+ndeath; j++){
4902: if(j==i) continue;
4903: jj++;
4904: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4905: printf("%1d%1d",i,j);
4906: fprintf(ficparo,"%1d%1d",i,j);
4907: for(k=1; k<=ncovmodel;k++){
4908: /* printf(" %lf",param[i][j][k]); */
4909: /* fprintf(ficparo," %lf",param[i][j][k]); */
4910: printf(" 0.");
4911: fprintf(ficparo," 0.");
4912: }
4913: printf("\n");
4914: fprintf(ficparo,"\n");
4915: }
4916: }
4917: printf("# Scales (for hessian or gradient estimation)\n");
4918: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4919: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4920: for(i=1; i <=nlstate; i++){
4921: jj=0;
4922: for(j=1; j <=nlstate+ndeath; j++){
4923: if(j==i) continue;
4924: jj++;
4925: fprintf(ficparo,"%1d%1d",i,j);
4926: printf("%1d%1d",i,j);
4927: fflush(stdout);
4928: for(k=1; k<=ncovmodel;k++){
4929: /* printf(" %le",delti3[i][j][k]); */
4930: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4931: printf(" 0.");
4932: fprintf(ficparo," 0.");
4933: }
4934: numlinepar++;
4935: printf("\n");
4936: fprintf(ficparo,"\n");
4937: }
4938: }
4939: printf("# Covariance matrix\n");
4940: /* # 121 Var(a12)\n\ */
4941: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4942: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4943: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4944: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4945: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4946: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4947: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4948: fflush(stdout);
4949: fprintf(ficparo,"# Covariance matrix\n");
4950: /* # 121 Var(a12)\n\ */
4951: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4952: /* # ...\n\ */
4953: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4954:
4955: for(itimes=1;itimes<=2;itimes++){
4956: jj=0;
4957: for(i=1; i <=nlstate; i++){
4958: for(j=1; j <=nlstate+ndeath; j++){
4959: if(j==i) continue;
4960: for(k=1; k<=ncovmodel;k++){
4961: jj++;
4962: ca[0]= k+'a'-1;ca[1]='\0';
4963: if(itimes==1){
4964: printf("#%1d%1d%d",i,j,k);
4965: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4966: }else{
4967: printf("%1d%1d%d",i,j,k);
4968: fprintf(ficparo,"%1d%1d%d",i,j,k);
4969: /* printf(" %.5le",matcov[i][j]); */
4970: }
4971: ll=0;
4972: for(li=1;li <=nlstate; li++){
4973: for(lj=1;lj <=nlstate+ndeath; lj++){
4974: if(lj==li) continue;
4975: for(lk=1;lk<=ncovmodel;lk++){
4976: ll++;
4977: if(ll<=jj){
4978: cb[0]= lk +'a'-1;cb[1]='\0';
4979: if(ll<jj){
4980: if(itimes==1){
4981: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4982: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4983: }else{
4984: printf(" 0.");
4985: fprintf(ficparo," 0.");
4986: }
4987: }else{
4988: if(itimes==1){
4989: printf(" Var(%s%1d%1d)",ca,i,j);
4990: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4991: }else{
4992: printf(" 0.");
4993: fprintf(ficparo," 0.");
4994: }
4995: }
4996: }
4997: } /* end lk */
4998: } /* end lj */
4999: } /* end li */
5000: printf("\n");
5001: fprintf(ficparo,"\n");
5002: numlinepar++;
5003: } /* end k*/
5004: } /*end j */
5005: } /* end i */
5006: } /* end itimes */
5007:
5008: } /* end of prwizard */
5009: /******************* Gompertz Likelihood ******************************/
5010: double gompertz(double x[])
5011: {
5012: double A,B,L=0.0,sump=0.,num=0.;
5013: int i,n=0; /* n is the size of the sample */
5014:
5015: for (i=0;i<=imx-1 ; i++) {
5016: sump=sump+weight[i];
5017: /* sump=sump+1;*/
5018: num=num+1;
5019: }
5020:
5021:
5022: /* for (i=0; i<=imx; i++)
5023: 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]);*/
5024:
5025: for (i=1;i<=imx ; i++)
5026: {
5027: if (cens[i] == 1 && wav[i]>1)
5028: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5029:
5030: if (cens[i] == 0 && wav[i]>1)
5031: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5032: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5033:
5034: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5035: if (wav[i] > 1 ) { /* ??? */
5036: L=L+A*weight[i];
5037: /* 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]);*/
5038: }
5039: }
5040:
5041: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5042:
5043: return -2*L*num/sump;
5044: }
5045:
1.136 brouard 5046: #ifdef GSL
5047: /******************* Gompertz_f Likelihood ******************************/
5048: double gompertz_f(const gsl_vector *v, void *params)
5049: {
5050: double A,B,LL=0.0,sump=0.,num=0.;
5051: double *x= (double *) v->data;
5052: int i,n=0; /* n is the size of the sample */
5053:
5054: for (i=0;i<=imx-1 ; i++) {
5055: sump=sump+weight[i];
5056: /* sump=sump+1;*/
5057: num=num+1;
5058: }
5059:
5060:
5061: /* for (i=0; i<=imx; i++)
5062: 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]);*/
5063: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5064: for (i=1;i<=imx ; i++)
5065: {
5066: if (cens[i] == 1 && wav[i]>1)
5067: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5068:
5069: if (cens[i] == 0 && wav[i]>1)
5070: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5071: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5072:
5073: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5074: if (wav[i] > 1 ) { /* ??? */
5075: LL=LL+A*weight[i];
5076: /* 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]);*/
5077: }
5078: }
5079:
5080: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5081: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5082:
5083: return -2*LL*num/sump;
5084: }
5085: #endif
5086:
1.126 brouard 5087: /******************* Printing html file ***********/
5088: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5089: int lastpass, int stepm, int weightopt, char model[],\
5090: int imx, double p[],double **matcov,double agemortsup){
5091: int i,k;
5092:
5093: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5094: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5095: for (i=1;i<=2;i++)
5096: 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]));
5097: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5098: fprintf(fichtm,"</ul>");
5099:
5100: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5101:
5102: 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>");
5103:
5104: for (k=agegomp;k<(agemortsup-2);k++)
5105: 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]);
5106:
5107:
5108: fflush(fichtm);
5109: }
5110:
5111: /******************* Gnuplot file **************/
5112: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5113:
5114: char dirfileres[132],optfileres[132];
1.164 brouard 5115:
1.126 brouard 5116: int ng;
5117:
5118:
5119: /*#ifdef windows */
5120: fprintf(ficgp,"cd \"%s\" \n",pathc);
5121: /*#endif */
5122:
5123:
5124: strcpy(dirfileres,optionfilefiname);
5125: strcpy(optfileres,"vpl");
5126: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5127: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5128: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5129: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5130: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5131:
5132: }
5133:
1.136 brouard 5134: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5135: {
1.126 brouard 5136:
1.136 brouard 5137: /*-------- data file ----------*/
5138: FILE *fic;
5139: char dummy[]=" ";
1.164 brouard 5140: int i=0, j=0, n=0;
1.136 brouard 5141: int linei, month, year,iout;
5142: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5143: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5144: char *stratrunc;
5145: int lstra;
1.126 brouard 5146:
5147:
1.136 brouard 5148: if((fic=fopen(datafile,"r"))==NULL) {
5149: printf("Problem while opening datafile: %s\n", datafile);return 1;
5150: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5151: }
1.126 brouard 5152:
1.136 brouard 5153: i=1;
5154: linei=0;
5155: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5156: linei=linei+1;
5157: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5158: if(line[j] == '\t')
5159: line[j] = ' ';
5160: }
5161: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5162: ;
5163: };
5164: line[j+1]=0; /* Trims blanks at end of line */
5165: if(line[0]=='#'){
5166: fprintf(ficlog,"Comment line\n%s\n",line);
5167: printf("Comment line\n%s\n",line);
5168: continue;
5169: }
5170: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5171: strcpy(line, linetmp);
1.136 brouard 5172:
1.126 brouard 5173:
1.136 brouard 5174: for (j=maxwav;j>=1;j--){
1.137 brouard 5175: cutv(stra, strb, line, ' ');
1.136 brouard 5176: if(strb[0]=='.') { /* Missing status */
5177: lval=-1;
5178: }else{
5179: errno=0;
5180: lval=strtol(strb,&endptr,10);
5181: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5182: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5183: 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);
5184: 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 5185: return 1;
5186: }
5187: }
5188: s[j][i]=lval;
5189:
5190: strcpy(line,stra);
5191: cutv(stra, strb,line,' ');
1.169 brouard 5192: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5193: }
1.169 brouard 5194: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5195: month=99;
5196: year=9999;
5197: }else{
1.141 brouard 5198: 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);
5199: 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 5200: return 1;
5201: }
5202: anint[j][i]= (double) year;
5203: mint[j][i]= (double)month;
5204: strcpy(line,stra);
5205: } /* ENd Waves */
5206:
5207: cutv(stra, strb,line,' ');
1.169 brouard 5208: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5209: }
1.169 brouard 5210: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5211: month=99;
5212: year=9999;
5213: }else{
1.141 brouard 5214: 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);
5215: 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 5216: return 1;
5217: }
5218: andc[i]=(double) year;
5219: moisdc[i]=(double) month;
5220: strcpy(line,stra);
5221:
5222: cutv(stra, strb,line,' ');
1.169 brouard 5223: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5224: }
1.169 brouard 5225: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5226: month=99;
5227: year=9999;
5228: }else{
1.141 brouard 5229: 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);
5230: 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 5231: return 1;
5232: }
5233: if (year==9999) {
1.141 brouard 5234: 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);
5235: 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 5236: return 1;
1.126 brouard 5237:
1.136 brouard 5238: }
5239: annais[i]=(double)(year);
5240: moisnais[i]=(double)(month);
5241: strcpy(line,stra);
5242:
5243: cutv(stra, strb,line,' ');
5244: errno=0;
5245: dval=strtod(strb,&endptr);
5246: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5247: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5248: 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 5249: fflush(ficlog);
5250: return 1;
5251: }
5252: weight[i]=dval;
5253: strcpy(line,stra);
5254:
5255: for (j=ncovcol;j>=1;j--){
5256: cutv(stra, strb,line,' ');
5257: if(strb[0]=='.') { /* Missing status */
5258: lval=-1;
5259: }else{
5260: errno=0;
5261: lval=strtol(strb,&endptr,10);
5262: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5263: 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);
5264: 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 5265: return 1;
5266: }
5267: }
5268: if(lval <-1 || lval >1){
1.141 brouard 5269: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5270: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5271: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5272: For example, for multinomial values like 1, 2 and 3,\n \
5273: build V1=0 V2=0 for the reference value (1),\n \
5274: V1=1 V2=0 for (2) \n \
5275: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5276: output of IMaCh is often meaningless.\n \
5277: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5278: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5279: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5280: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5281: For example, for multinomial values like 1, 2 and 3,\n \
5282: build V1=0 V2=0 for the reference value (1),\n \
5283: V1=1 V2=0 for (2) \n \
5284: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5285: output of IMaCh is often meaningless.\n \
5286: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5287: return 1;
5288: }
5289: covar[j][i]=(double)(lval);
5290: strcpy(line,stra);
5291: }
5292: lstra=strlen(stra);
5293:
5294: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5295: stratrunc = &(stra[lstra-9]);
5296: num[i]=atol(stratrunc);
5297: }
5298: else
5299: num[i]=atol(stra);
5300: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5301: 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;}*/
5302:
5303: i=i+1;
5304: } /* End loop reading data */
1.126 brouard 5305:
1.136 brouard 5306: *imax=i-1; /* Number of individuals */
5307: fclose(fic);
5308:
5309: return (0);
1.164 brouard 5310: /* endread: */
1.136 brouard 5311: printf("Exiting readdata: ");
5312: fclose(fic);
5313: return (1);
1.126 brouard 5314:
5315:
5316:
1.136 brouard 5317: }
1.145 brouard 5318: void removespace(char *str) {
5319: char *p1 = str, *p2 = str;
5320: do
5321: while (*p2 == ' ')
5322: p2++;
1.169 brouard 5323: while (*p1++ == *p2++);
1.145 brouard 5324: }
5325:
5326: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5327: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5328: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5329: * - cptcovn or number of covariates k of the models excluding age*products =6
5330: * - cptcovage number of covariates with age*products =2
5331: * - cptcovs number of simple covariates
5332: * - 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
5333: * which is a new column after the 9 (ncovcol) variables.
5334: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5335: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5336: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5337: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5338: */
1.136 brouard 5339: {
1.145 brouard 5340: int i, j, k, ks;
1.164 brouard 5341: int j1, k1, k2;
1.136 brouard 5342: char modelsav[80];
1.145 brouard 5343: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5344:
1.145 brouard 5345: /*removespace(model);*/
1.136 brouard 5346: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5347: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5348: j=nbocc(model,'+'); /**< j=Number of '+' */
5349: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5350: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5351: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5352: /* including age products which are counted in cptcovage.
1.169 brouard 5353: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5354: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5355: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5356: strcpy(modelsav,model);
1.137 brouard 5357: if (strstr(model,"AGE") !=0){
5358: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5359: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5360: return 1;
5361: }
1.141 brouard 5362: if (strstr(model,"v") !=0){
5363: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5364: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5365: return 1;
5366: }
1.136 brouard 5367:
1.145 brouard 5368: /* Design
5369: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5370: * < ncovcol=8 >
5371: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5372: * k= 1 2 3 4 5 6 7 8
5373: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5374: * covar[k,i], value of kth covariate if not including age for individual i:
5375: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5376: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5377: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5378: * Tage[++cptcovage]=k
5379: * if products, new covar are created after ncovcol with k1
5380: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5381: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5382: * 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
5383: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5384: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5385: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5386: * < ncovcol=8 >
5387: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5388: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5389: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5390: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5391: * p Tprod[1]@2={ 6, 5}
5392: *p Tvard[1][1]@4= {7, 8, 5, 6}
5393: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5394: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5395: *How to reorganize?
5396: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5397: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5398: * {2, 1, 4, 8, 5, 6, 3, 7}
5399: * Struct []
5400: */
5401:
1.136 brouard 5402: /* This loop fills the array Tvar from the string 'model'.*/
5403: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5404: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5405: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5406: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5407: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5408: /* k=1 Tvar[1]=2 (from V2) */
5409: /* k=5 Tvar[5] */
5410: /* for (k=1; k<=cptcovn;k++) { */
5411: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5412: /* } */
5413: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5414: /*
5415: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5416: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5417: Tvar[k]=0;
5418: cptcovage=0;
5419: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5420: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5421: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5422: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5423: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5424: /*scanf("%d",i);*/
1.145 brouard 5425: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5426: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5427: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5428: /* covar is not filled and then is empty */
1.136 brouard 5429: cptcovprod--;
1.145 brouard 5430: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5431: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5432: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5433: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5434: /*printf("stre=%s ", stre);*/
1.137 brouard 5435: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5436: cptcovprod--;
1.145 brouard 5437: cutl(stre,strb,strc,'V');
1.136 brouard 5438: Tvar[k]=atoi(stre);
5439: cptcovage++;
5440: Tage[cptcovage]=k;
1.137 brouard 5441: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5442: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5443: cptcovn++;
5444: cptcovprodnoage++;k1++;
5445: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5446: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5447: because this model-covariate is a construction we invent a new column
5448: ncovcol + k1
5449: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5450: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5451: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5452: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5453: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5454: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5455: k2=k2+2;
5456: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5457: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5458: for (i=1; i<=lastobs;i++){
5459: /* Computes the new covariate which is a product of
1.145 brouard 5460: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5461: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5462: }
5463: } /* End age is not in the model */
5464: } /* End if model includes a product */
1.136 brouard 5465: else { /* no more sum */
5466: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5467: /* scanf("%d",i);*/
1.145 brouard 5468: cutl(strd,strc,strb,'V');
5469: ks++; /**< Number of simple covariates */
5470: cptcovn++;
5471: Tvar[k]=atoi(strd);
1.136 brouard 5472: }
1.137 brouard 5473: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5474: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5475: scanf("%d",i);*/
5476: } /* end of loop + */
5477: } /* end model */
5478:
5479: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5480: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5481:
5482: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5483: printf("cptcovprod=%d ", cptcovprod);
5484: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5485:
5486: scanf("%d ",i);*/
5487:
5488:
1.137 brouard 5489: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5490: /*endread:*/
1.136 brouard 5491: printf("Exiting decodemodel: ");
5492: return (1);
5493: }
5494:
1.169 brouard 5495: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5496: {
5497: int i, m;
5498:
5499: for (i=1; i<=imx; i++) {
5500: for(m=2; (m<= maxwav); m++) {
5501: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5502: anint[m][i]=9999;
5503: s[m][i]=-1;
5504: }
5505: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5506: *nberr = *nberr + 1;
5507: 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);
5508: 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 5509: s[m][i]=-1;
5510: }
5511: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5512: (*nberr)++;
1.136 brouard 5513: 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]);
5514: 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]);
5515: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5516: }
5517: }
5518: }
5519:
5520: for (i=1; i<=imx; i++) {
5521: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5522: for(m=firstpass; (m<= lastpass); m++){
5523: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5524: if (s[m][i] >= nlstate+1) {
1.169 brouard 5525: if(agedc[i]>0){
5526: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5527: agev[m][i]=agedc[i];
5528: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5529: }else {
1.136 brouard 5530: if ((int)andc[i]!=9999){
5531: nbwarn++;
5532: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5533: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5534: agev[m][i]=-1;
5535: }
5536: }
1.169 brouard 5537: } /* agedc > 0 */
1.136 brouard 5538: }
5539: else if(s[m][i] !=9){ /* Standard case, age in fractional
5540: years but with the precision of a month */
5541: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5542: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5543: agev[m][i]=1;
5544: else if(agev[m][i] < *agemin){
5545: *agemin=agev[m][i];
5546: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5547: }
5548: else if(agev[m][i] >*agemax){
5549: *agemax=agev[m][i];
1.156 brouard 5550: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5551: }
5552: /*agev[m][i]=anint[m][i]-annais[i];*/
5553: /* agev[m][i] = age[i]+2*m;*/
5554: }
5555: else { /* =9 */
5556: agev[m][i]=1;
5557: s[m][i]=-1;
5558: }
5559: }
5560: else /*= 0 Unknown */
5561: agev[m][i]=1;
5562: }
5563:
5564: }
5565: for (i=1; i<=imx; i++) {
5566: for(m=firstpass; (m<=lastpass); m++){
5567: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5568: (*nberr)++;
1.136 brouard 5569: 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);
5570: 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);
5571: return 1;
5572: }
5573: }
5574: }
5575:
5576: /*for (i=1; i<=imx; i++){
5577: for (m=firstpass; (m<lastpass); m++){
5578: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5579: }
5580:
5581: }*/
5582:
5583:
1.139 brouard 5584: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5585: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5586:
5587: return (0);
1.164 brouard 5588: /* endread:*/
1.136 brouard 5589: printf("Exiting calandcheckages: ");
5590: return (1);
5591: }
5592:
1.172 brouard 5593: #if defined(_MSC_VER)
5594: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5595: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5596: //#include "stdafx.h"
5597: //#include <stdio.h>
5598: //#include <tchar.h>
5599: //#include <windows.h>
5600: //#include <iostream>
5601: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5602:
5603: LPFN_ISWOW64PROCESS fnIsWow64Process;
5604:
5605: BOOL IsWow64()
5606: {
5607: BOOL bIsWow64 = FALSE;
5608:
5609: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5610: // (HANDLE, PBOOL);
5611:
5612: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5613:
5614: HMODULE module = GetModuleHandle(_T("kernel32"));
5615: const char funcName[] = "IsWow64Process";
5616: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5617: GetProcAddress(module, funcName);
5618:
5619: if (NULL != fnIsWow64Process)
5620: {
5621: if (!fnIsWow64Process(GetCurrentProcess(),
5622: &bIsWow64))
5623: //throw std::exception("Unknown error");
5624: printf("Unknown error\n");
5625: }
5626: return bIsWow64 != FALSE;
5627: }
5628: #endif
1.177 brouard 5629:
1.169 brouard 5630: void syscompilerinfo()
1.167 brouard 5631: {
5632: /* #include "syscompilerinfo.h"*/
1.177 brouard 5633:
5634: #if defined __INTEL_COMPILER
1.178 brouard 5635: #if defined(__GNUC__)
5636: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5637: #endif
1.177 brouard 5638: #elif defined(__GNUC__)
1.179 brouard 5639: #ifndef __APPLE__
1.174 brouard 5640: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5641: #endif
1.177 brouard 5642: struct utsname sysInfo;
1.178 brouard 5643: int cross = CROSS;
5644: if (cross){
5645: printf("Cross-");
5646: fprintf(ficlog, "Cross-");
5647: }
1.174 brouard 5648: #endif
5649:
1.171 brouard 5650: #include <stdint.h>
1.178 brouard 5651:
1.169 brouard 5652: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5653: #if defined(__clang__)
5654: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5655: #endif
5656: #if defined(__ICC) || defined(__INTEL_COMPILER)
5657: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5658: #endif
5659: #if defined(__GNUC__) || defined(__GNUG__)
5660: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5661: #endif
5662: #if defined(__HP_cc) || defined(__HP_aCC)
5663: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5664: #endif
5665: #if defined(__IBMC__) || defined(__IBMCPP__)
5666: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5667: #endif
5668: #if defined(_MSC_VER)
5669: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5670: #endif
5671: #if defined(__PGI)
5672: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5673: #endif
5674: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5675: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5676: #endif
1.174 brouard 5677: printf(" for ");fprintf(ficlog," for ");
1.169 brouard 5678:
1.167 brouard 5679: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5680: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5681: // Windows (x64 and x86)
1.174 brouard 5682: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 5683: #elif __unix__ // all unices, not all compilers
5684: // Unix
1.174 brouard 5685: printf("Unix ");fprintf(ficlog,"Unix ");
1.167 brouard 5686: #elif __linux__
5687: // linux
1.174 brouard 5688: printf("linux ");fprintf(ficlog,"linux ");
1.167 brouard 5689: #elif __APPLE__
1.174 brouard 5690: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5691: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167 brouard 5692: #endif
5693:
5694: /* __MINGW32__ */
5695: /* __CYGWIN__ */
5696: /* __MINGW64__ */
5697: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5698: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5699: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5700: /* _WIN64 // Defined for applications for Win64. */
5701: /* _M_X64 // Defined for compilations that target x64 processors. */
5702: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5703:
1.167 brouard 5704: #if UINTPTR_MAX == 0xffffffff
1.174 brouard 5705: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 5706: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174 brouard 5707: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 5708: #else
1.174 brouard 5709: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 5710: #endif
5711:
1.169 brouard 5712: #if defined(__GNUC__)
5713: # if defined(__GNUC_PATCHLEVEL__)
5714: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5715: + __GNUC_MINOR__ * 100 \
5716: + __GNUC_PATCHLEVEL__)
5717: # else
5718: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5719: + __GNUC_MINOR__ * 100)
5720: # endif
1.174 brouard 5721: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5722: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 5723:
5724: if (uname(&sysInfo) != -1) {
5725: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5726: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5727: }
5728: else
5729: perror("uname() error");
1.179 brouard 5730: //#ifndef __INTEL_COMPILER
5731: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 5732: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.179 brouard 5733: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 5734: #endif
1.169 brouard 5735: #endif
1.172 brouard 5736:
5737: // void main()
5738: // {
1.169 brouard 5739: #if defined(_MSC_VER)
1.174 brouard 5740: if (IsWow64()){
1.176 brouard 5741: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5742: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 5743: }
5744: else{
1.176 brouard 5745: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178 brouard 5746: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 5747: }
1.172 brouard 5748: // printf("\nPress Enter to continue...");
5749: // getchar();
5750: // }
5751:
1.169 brouard 5752: #endif
5753:
1.167 brouard 5754:
5755: }
1.136 brouard 5756:
1.180 brouard 5757: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5758: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5759: int i, j, k, i1 ;
5760: double ftolpl = 1.e-10;
5761: double age, agebase, agelim;
5762:
5763: strcpy(filerespl,"pl");
5764: strcat(filerespl,fileres);
5765: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5766: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5767: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5768: }
5769: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5770: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5771: pstamp(ficrespl);
5772: fprintf(ficrespl,"# Period (stable) prevalence \n");
5773: fprintf(ficrespl,"#Age ");
5774: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5775: fprintf(ficrespl,"\n");
5776:
5777: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5778:
5779: agebase=ageminpar;
5780: agelim=agemaxpar;
5781:
5782: i1=pow(2,cptcoveff);
5783: if (cptcovn < 1){i1=1;}
5784:
5785: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5786: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5787: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5788: k=k+1;
5789: /* to clean */
5790: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5791: fprintf(ficrespl,"\n#******");
5792: printf("\n#******");
5793: fprintf(ficlog,"\n#******");
5794: for(j=1;j<=cptcoveff;j++) {
5795: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5796: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5797: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5798: }
5799: fprintf(ficrespl,"******\n");
5800: printf("******\n");
5801: fprintf(ficlog,"******\n");
5802:
5803: fprintf(ficrespl,"#Age ");
5804: for(j=1;j<=cptcoveff;j++) {
5805: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5806: }
5807: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5808: fprintf(ficrespl,"\n");
5809:
5810: for (age=agebase; age<=agelim; age++){
5811: /* for (age=agebase; age<=agebase; age++){ */
5812: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5813: fprintf(ficrespl,"%.0f ",age );
5814: for(j=1;j<=cptcoveff;j++)
5815: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5816: for(i=1; i<=nlstate;i++)
5817: fprintf(ficrespl," %.5f", prlim[i][i]);
5818: fprintf(ficrespl,"\n");
5819: } /* Age */
5820: /* was end of cptcod */
5821: } /* cptcov */
5822: }
5823:
5824: int hPijx(double *p, int bage, int fage){
5825: /*------------- h Pij x at various ages ------------*/
5826:
5827: int stepsize;
5828: int agelim;
5829: int hstepm;
5830: int nhstepm;
5831: int h, i, i1, j, k;
5832:
5833: double agedeb;
5834: double ***p3mat;
5835:
5836: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5837: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5838: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5839: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5840: }
5841: printf("Computing pij: result on file '%s' \n", filerespij);
5842: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5843:
5844: stepsize=(int) (stepm+YEARM-1)/YEARM;
5845: /*if (stepm<=24) stepsize=2;*/
5846:
5847: agelim=AGESUP;
5848: hstepm=stepsize*YEARM; /* Every year of age */
5849: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5850:
5851: /* hstepm=1; aff par mois*/
5852: pstamp(ficrespij);
5853: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5854: i1= pow(2,cptcoveff);
1.183 ! brouard 5855: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
! 5856: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
! 5857: /* k=k+1; */
! 5858: for (k=1; k <= (int) pow(2,cptcoveff); k++){
! 5859: fprintf(ficrespij,"\n#****** ");
! 5860: for(j=1;j<=cptcoveff;j++)
! 5861: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
! 5862: fprintf(ficrespij,"******\n");
! 5863:
! 5864: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
! 5865: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
! 5866: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
! 5867:
! 5868: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 5869:
1.183 ! brouard 5870: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
! 5871: oldm=oldms;savm=savms;
! 5872: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
! 5873: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
! 5874: for(i=1; i<=nlstate;i++)
! 5875: for(j=1; j<=nlstate+ndeath;j++)
! 5876: fprintf(ficrespij," %1d-%1d",i,j);
! 5877: fprintf(ficrespij,"\n");
! 5878: for (h=0; h<=nhstepm; h++){
! 5879: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
! 5880: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 5881: for(i=1; i<=nlstate;i++)
5882: for(j=1; j<=nlstate+ndeath;j++)
1.183 ! brouard 5883: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 5884: fprintf(ficrespij,"\n");
5885: }
1.183 ! brouard 5886: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
! 5887: fprintf(ficrespij,"\n");
! 5888: }
1.180 brouard 5889: /*}*/
5890: }
5891: }
5892:
5893:
1.136 brouard 5894: /***********************************************/
5895: /**************** Main Program *****************/
5896: /***********************************************/
5897:
5898: int main(int argc, char *argv[])
5899: {
5900: #ifdef GSL
5901: const gsl_multimin_fminimizer_type *T;
5902: size_t iteri = 0, it;
5903: int rval = GSL_CONTINUE;
5904: int status = GSL_SUCCESS;
5905: double ssval;
5906: #endif
5907: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5908: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5909:
5910: int jj, ll, li, lj, lk;
1.136 brouard 5911: int numlinepar=0; /* Current linenumber of parameter file */
5912: int itimes;
5913: int NDIM=2;
5914: int vpopbased=0;
5915:
1.164 brouard 5916: char ca[32], cb[32];
1.136 brouard 5917: /* FILE *fichtm; *//* Html File */
5918: /* FILE *ficgp;*/ /*Gnuplot File */
5919: struct stat info;
1.164 brouard 5920: double agedeb;
1.136 brouard 5921: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5922:
1.165 brouard 5923: double fret;
1.136 brouard 5924: double dum; /* Dummy variable */
5925: double ***p3mat;
5926: double ***mobaverage;
1.164 brouard 5927:
5928: char line[MAXLINE];
1.136 brouard 5929: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5930: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5931: char *tok, *val; /* pathtot */
1.136 brouard 5932: int firstobs=1, lastobs=10;
1.164 brouard 5933: int c, h , cpt;
5934: int jl;
5935: int i1, j1, jk, stepsize;
5936: int *tab;
1.136 brouard 5937: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5938: int mobilav=0,popforecast=0;
5939: int hstepm, nhstepm;
5940: int agemortsup;
5941: float sumlpop=0.;
5942: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5943: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5944:
1.164 brouard 5945: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5946: double ftolpl=FTOL;
5947: double **prlim;
5948: double ***param; /* Matrix of parameters */
5949: double *p;
5950: double **matcov; /* Matrix of covariance */
5951: double ***delti3; /* Scale */
5952: double *delti; /* Scale */
5953: double ***eij, ***vareij;
5954: double **varpl; /* Variances of prevalence limits by age */
5955: double *epj, vepp;
1.164 brouard 5956:
1.136 brouard 5957: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5958: double **ximort;
1.145 brouard 5959: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5960: int *dcwave;
5961:
1.164 brouard 5962: char z[1]="c";
1.136 brouard 5963:
5964: /*char *strt;*/
5965: char strtend[80];
1.126 brouard 5966:
1.164 brouard 5967:
1.126 brouard 5968: /* setlocale (LC_ALL, ""); */
5969: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5970: /* textdomain (PACKAGE); */
5971: /* setlocale (LC_CTYPE, ""); */
5972: /* setlocale (LC_MESSAGES, ""); */
5973:
5974: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5975: rstart_time = time(NULL);
5976: /* (void) gettimeofday(&start_time,&tzp);*/
5977: start_time = *localtime(&rstart_time);
1.126 brouard 5978: curr_time=start_time;
1.157 brouard 5979: /*tml = *localtime(&start_time.tm_sec);*/
5980: /* strcpy(strstart,asctime(&tml)); */
5981: strcpy(strstart,asctime(&start_time));
1.126 brouard 5982:
5983: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5984: /* tp.tm_sec = tp.tm_sec +86400; */
5985: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5986: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5987: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5988: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5989: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5990: /* strt=asctime(&tmg); */
5991: /* printf("Time(after) =%s",strstart); */
5992: /* (void) time (&time_value);
5993: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5994: * tm = *localtime(&time_value);
5995: * strstart=asctime(&tm);
5996: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5997: */
5998:
5999: nberr=0; /* Number of errors and warnings */
6000: nbwarn=0;
6001: getcwd(pathcd, size);
6002:
6003: printf("\n%s\n%s",version,fullversion);
6004: if(argc <=1){
6005: printf("\nEnter the parameter file name: ");
6006: fgets(pathr,FILENAMELENGTH,stdin);
6007: i=strlen(pathr);
6008: if(pathr[i-1]=='\n')
6009: pathr[i-1]='\0';
1.156 brouard 6010: i=strlen(pathr);
6011: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6012: pathr[i-1]='\0';
1.126 brouard 6013: for (tok = pathr; tok != NULL; ){
6014: printf("Pathr |%s|\n",pathr);
6015: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6016: printf("val= |%s| pathr=%s\n",val,pathr);
6017: strcpy (pathtot, val);
6018: if(pathr[0] == '\0') break; /* Dirty */
6019: }
6020: }
6021: else{
6022: strcpy(pathtot,argv[1]);
6023: }
6024: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6025: /*cygwin_split_path(pathtot,path,optionfile);
6026: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6027: /* cutv(path,optionfile,pathtot,'\\');*/
6028:
6029: /* Split argv[0], imach program to get pathimach */
6030: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6031: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6032: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6033: /* strcpy(pathimach,argv[0]); */
6034: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6035: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6036: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6037: chdir(path); /* Can be a relative path */
6038: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6039: printf("Current directory %s!\n",pathcd);
6040: strcpy(command,"mkdir ");
6041: strcat(command,optionfilefiname);
6042: if((outcmd=system(command)) != 0){
1.169 brouard 6043: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6044: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6045: /* fclose(ficlog); */
6046: /* exit(1); */
6047: }
6048: /* if((imk=mkdir(optionfilefiname))<0){ */
6049: /* perror("mkdir"); */
6050: /* } */
6051:
6052: /*-------- arguments in the command line --------*/
6053:
6054: /* Log file */
6055: strcat(filelog, optionfilefiname);
6056: strcat(filelog,".log"); /* */
6057: if((ficlog=fopen(filelog,"w"))==NULL) {
6058: printf("Problem with logfile %s\n",filelog);
6059: goto end;
6060: }
6061: fprintf(ficlog,"Log filename:%s\n",filelog);
6062: fprintf(ficlog,"\n%s\n%s",version,fullversion);
6063: fprintf(ficlog,"\nEnter the parameter file name: \n");
6064: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6065: path=%s \n\
6066: optionfile=%s\n\
6067: optionfilext=%s\n\
1.156 brouard 6068: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6069:
1.167 brouard 6070: syscompilerinfo();
6071:
1.126 brouard 6072: printf("Local time (at start):%s",strstart);
6073: fprintf(ficlog,"Local time (at start): %s",strstart);
6074: fflush(ficlog);
6075: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6076: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6077:
6078: /* */
6079: strcpy(fileres,"r");
6080: strcat(fileres, optionfilefiname);
6081: strcat(fileres,".txt"); /* Other files have txt extension */
6082:
6083: /*---------arguments file --------*/
6084:
6085: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6086: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6087: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6088: fflush(ficlog);
1.149 brouard 6089: /* goto end; */
6090: exit(70);
1.126 brouard 6091: }
6092:
6093:
6094:
6095: strcpy(filereso,"o");
6096: strcat(filereso,fileres);
6097: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6098: printf("Problem with Output resultfile: %s\n", filereso);
6099: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6100: fflush(ficlog);
6101: goto end;
6102: }
6103:
6104: /* Reads comments: lines beginning with '#' */
6105: numlinepar=0;
6106: while((c=getc(ficpar))=='#' && c!= EOF){
6107: ungetc(c,ficpar);
6108: fgets(line, MAXLINE, ficpar);
6109: numlinepar++;
1.141 brouard 6110: fputs(line,stdout);
1.126 brouard 6111: fputs(line,ficparo);
6112: fputs(line,ficlog);
6113: }
6114: ungetc(c,ficpar);
6115:
6116: 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);
6117: numlinepar++;
6118: 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);
6119: 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);
6120: 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);
6121: fflush(ficlog);
6122: while((c=getc(ficpar))=='#' && c!= EOF){
6123: ungetc(c,ficpar);
6124: fgets(line, MAXLINE, ficpar);
6125: numlinepar++;
1.141 brouard 6126: fputs(line, stdout);
6127: //puts(line);
1.126 brouard 6128: fputs(line,ficparo);
6129: fputs(line,ficlog);
6130: }
6131: ungetc(c,ficpar);
6132:
6133:
1.145 brouard 6134: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6135: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6136: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6137: v1+v2*age+v2*v3 makes cptcovn = 3
6138: */
6139: if (strlen(model)>1)
1.145 brouard 6140: 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*/
6141: else
6142: ncovmodel=2;
1.126 brouard 6143: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 6144: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6145: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6146: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6147: 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);
6148: 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);
6149: fflush(stdout);
6150: fclose (ficlog);
6151: goto end;
6152: }
1.126 brouard 6153: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6154: delti=delti3[1][1];
6155: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6156: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6157: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6158: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6159: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6160: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6161: fclose (ficparo);
6162: fclose (ficlog);
6163: goto end;
6164: exit(0);
6165: }
6166: else if(mle==-3) {
6167: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6168: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6169: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6170: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6171: matcov=matrix(1,npar,1,npar);
6172: }
6173: else{
1.145 brouard 6174: /* Read guessed parameters */
1.126 brouard 6175: /* Reads comments: lines beginning with '#' */
6176: while((c=getc(ficpar))=='#' && c!= EOF){
6177: ungetc(c,ficpar);
6178: fgets(line, MAXLINE, ficpar);
6179: numlinepar++;
1.141 brouard 6180: fputs(line,stdout);
1.126 brouard 6181: fputs(line,ficparo);
6182: fputs(line,ficlog);
6183: }
6184: ungetc(c,ficpar);
6185:
6186: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6187: for(i=1; i <=nlstate; i++){
6188: j=0;
6189: for(jj=1; jj <=nlstate+ndeath; jj++){
6190: if(jj==i) continue;
6191: j++;
6192: fscanf(ficpar,"%1d%1d",&i1,&j1);
6193: if ((i1 != i) && (j1 != j)){
6194: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6195: It might be a problem of design; if ncovcol and the model are correct\n \
6196: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6197: exit(1);
6198: }
6199: fprintf(ficparo,"%1d%1d",i1,j1);
6200: if(mle==1)
6201: printf("%1d%1d",i,j);
6202: fprintf(ficlog,"%1d%1d",i,j);
6203: for(k=1; k<=ncovmodel;k++){
6204: fscanf(ficpar," %lf",¶m[i][j][k]);
6205: if(mle==1){
6206: printf(" %lf",param[i][j][k]);
6207: fprintf(ficlog," %lf",param[i][j][k]);
6208: }
6209: else
6210: fprintf(ficlog," %lf",param[i][j][k]);
6211: fprintf(ficparo," %lf",param[i][j][k]);
6212: }
6213: fscanf(ficpar,"\n");
6214: numlinepar++;
6215: if(mle==1)
6216: printf("\n");
6217: fprintf(ficlog,"\n");
6218: fprintf(ficparo,"\n");
6219: }
6220: }
6221: fflush(ficlog);
6222:
1.145 brouard 6223: /* Reads scales values */
1.126 brouard 6224: p=param[1][1];
6225:
6226: /* Reads comments: lines beginning with '#' */
6227: while((c=getc(ficpar))=='#' && c!= EOF){
6228: ungetc(c,ficpar);
6229: fgets(line, MAXLINE, ficpar);
6230: numlinepar++;
1.141 brouard 6231: fputs(line,stdout);
1.126 brouard 6232: fputs(line,ficparo);
6233: fputs(line,ficlog);
6234: }
6235: ungetc(c,ficpar);
6236:
6237: for(i=1; i <=nlstate; i++){
6238: for(j=1; j <=nlstate+ndeath-1; j++){
6239: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6240: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6241: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6242: exit(1);
6243: }
6244: printf("%1d%1d",i,j);
6245: fprintf(ficparo,"%1d%1d",i1,j1);
6246: fprintf(ficlog,"%1d%1d",i1,j1);
6247: for(k=1; k<=ncovmodel;k++){
6248: fscanf(ficpar,"%le",&delti3[i][j][k]);
6249: printf(" %le",delti3[i][j][k]);
6250: fprintf(ficparo," %le",delti3[i][j][k]);
6251: fprintf(ficlog," %le",delti3[i][j][k]);
6252: }
6253: fscanf(ficpar,"\n");
6254: numlinepar++;
6255: printf("\n");
6256: fprintf(ficparo,"\n");
6257: fprintf(ficlog,"\n");
6258: }
6259: }
6260: fflush(ficlog);
6261:
1.145 brouard 6262: /* Reads covariance matrix */
1.126 brouard 6263: delti=delti3[1][1];
6264:
6265:
6266: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6267:
6268: /* Reads comments: lines beginning with '#' */
6269: while((c=getc(ficpar))=='#' && c!= EOF){
6270: ungetc(c,ficpar);
6271: fgets(line, MAXLINE, ficpar);
6272: numlinepar++;
1.141 brouard 6273: fputs(line,stdout);
1.126 brouard 6274: fputs(line,ficparo);
6275: fputs(line,ficlog);
6276: }
6277: ungetc(c,ficpar);
6278:
6279: matcov=matrix(1,npar,1,npar);
1.131 brouard 6280: for(i=1; i <=npar; i++)
6281: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6282:
1.126 brouard 6283: for(i=1; i <=npar; i++){
1.145 brouard 6284: fscanf(ficpar,"%s",str);
1.126 brouard 6285: if(mle==1)
6286: printf("%s",str);
6287: fprintf(ficlog,"%s",str);
6288: fprintf(ficparo,"%s",str);
6289: for(j=1; j <=i; j++){
6290: fscanf(ficpar," %le",&matcov[i][j]);
6291: if(mle==1){
6292: printf(" %.5le",matcov[i][j]);
6293: }
6294: fprintf(ficlog," %.5le",matcov[i][j]);
6295: fprintf(ficparo," %.5le",matcov[i][j]);
6296: }
6297: fscanf(ficpar,"\n");
6298: numlinepar++;
6299: if(mle==1)
6300: printf("\n");
6301: fprintf(ficlog,"\n");
6302: fprintf(ficparo,"\n");
6303: }
6304: for(i=1; i <=npar; i++)
6305: for(j=i+1;j<=npar;j++)
6306: matcov[i][j]=matcov[j][i];
6307:
6308: if(mle==1)
6309: printf("\n");
6310: fprintf(ficlog,"\n");
6311:
6312: fflush(ficlog);
6313:
6314: /*-------- Rewriting parameter file ----------*/
6315: strcpy(rfileres,"r"); /* "Rparameterfile */
6316: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6317: strcat(rfileres,"."); /* */
6318: strcat(rfileres,optionfilext); /* Other files have txt extension */
6319: if((ficres =fopen(rfileres,"w"))==NULL) {
6320: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6321: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6322: }
6323: fprintf(ficres,"#%s\n",version);
6324: } /* End of mle != -3 */
6325:
6326:
6327: n= lastobs;
6328: num=lvector(1,n);
6329: moisnais=vector(1,n);
6330: annais=vector(1,n);
6331: moisdc=vector(1,n);
6332: andc=vector(1,n);
6333: agedc=vector(1,n);
6334: cod=ivector(1,n);
6335: weight=vector(1,n);
6336: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6337: mint=matrix(1,maxwav,1,n);
6338: anint=matrix(1,maxwav,1,n);
1.131 brouard 6339: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6340: tab=ivector(1,NCOVMAX);
1.144 brouard 6341: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6342:
1.136 brouard 6343: /* Reads data from file datafile */
6344: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6345: goto end;
6346:
6347: /* Calculation of the number of parameters from char model */
1.137 brouard 6348: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6349: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6350: k=3 V4 Tvar[k=3]= 4 (from V4)
6351: k=2 V1 Tvar[k=2]= 1 (from V1)
6352: k=1 Tvar[1]=2 (from V2)
6353: */
6354: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6355: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6356: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6357: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6358: */
6359: /* For model-covariate k tells which data-covariate to use but
6360: because this model-covariate is a construction we invent a new column
6361: ncovcol + k1
6362: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6363: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6364: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6365: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6366: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6367: */
1.145 brouard 6368: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6369: 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 6370: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6371: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6372: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6373: 4 covariates (3 plus signs)
6374: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6375: */
1.136 brouard 6376:
6377: if(decodemodel(model, lastobs) == 1)
6378: goto end;
6379:
1.137 brouard 6380: if((double)(lastobs-imx)/(double)imx > 1.10){
6381: nbwarn++;
6382: 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);
6383: 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);
6384: }
1.136 brouard 6385: /* if(mle==1){*/
1.137 brouard 6386: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6387: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6388: }
6389:
6390: /*-calculation of age at interview from date of interview and age at death -*/
6391: agev=matrix(1,maxwav,1,imx);
6392:
6393: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6394: goto end;
6395:
1.126 brouard 6396:
1.136 brouard 6397: agegomp=(int)agemin;
6398: free_vector(moisnais,1,n);
6399: free_vector(annais,1,n);
1.126 brouard 6400: /* free_matrix(mint,1,maxwav,1,n);
6401: free_matrix(anint,1,maxwav,1,n);*/
6402: free_vector(moisdc,1,n);
6403: free_vector(andc,1,n);
1.145 brouard 6404: /* */
6405:
1.126 brouard 6406: wav=ivector(1,imx);
6407: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6408: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6409: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6410:
6411: /* Concatenates waves */
6412: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6413: /* */
6414:
1.126 brouard 6415: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6416:
6417: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6418: ncodemax[1]=1;
1.145 brouard 6419: Ndum =ivector(-1,NCOVMAX);
6420: if (ncovmodel > 2)
6421: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6422:
6423: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6424: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6425: h=0;
6426:
6427:
6428: /*if (cptcovn > 0) */
1.126 brouard 6429:
1.145 brouard 6430:
1.126 brouard 6431: m=pow(2,cptcoveff);
6432:
1.131 brouard 6433: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6434: 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 */
6435: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6436: 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 6437: h++;
1.141 brouard 6438: if (h>m)
1.136 brouard 6439: h=1;
1.144 brouard 6440: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6441: * h 1 2 3 4
6442: *______________________________
6443: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6444: * 2 2 1 1 1
6445: * 3 i=2 1 2 1 1
6446: * 4 2 2 1 1
6447: * 5 i=3 1 i=2 1 2 1
6448: * 6 2 1 2 1
6449: * 7 i=4 1 2 2 1
6450: * 8 2 2 2 1
6451: * 9 i=5 1 i=3 1 i=2 1 1
6452: * 10 2 1 1 1
6453: * 11 i=6 1 2 1 1
6454: * 12 2 2 1 1
6455: * 13 i=7 1 i=4 1 2 1
6456: * 14 2 1 2 1
6457: * 15 i=8 1 2 2 1
6458: * 16 2 2 2 1
6459: */
1.141 brouard 6460: codtab[h][k]=j;
1.145 brouard 6461: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6462: 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 6463: }
6464: }
6465: }
6466: }
6467: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6468: codtab[1][2]=1;codtab[2][2]=2; */
6469: /* for(i=1; i <=m ;i++){
6470: for(k=1; k <=cptcovn; k++){
1.131 brouard 6471: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6472: }
6473: printf("\n");
6474: }
6475: scanf("%d",i);*/
1.145 brouard 6476:
6477: free_ivector(Ndum,-1,NCOVMAX);
6478:
6479:
1.126 brouard 6480:
6481: /*------------ gnuplot -------------*/
6482: strcpy(optionfilegnuplot,optionfilefiname);
6483: if(mle==-3)
6484: strcat(optionfilegnuplot,"-mort");
6485: strcat(optionfilegnuplot,".gp");
6486:
6487: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6488: printf("Problem with file %s",optionfilegnuplot);
6489: }
6490: else{
6491: fprintf(ficgp,"\n# %s\n", version);
6492: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6493: //fprintf(ficgp,"set missing 'NaNq'\n");
6494: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6495: }
6496: /* fclose(ficgp);*/
6497: /*--------- index.htm --------*/
6498:
6499: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6500: if(mle==-3)
6501: strcat(optionfilehtm,"-mort");
6502: strcat(optionfilehtm,".htm");
6503: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6504: printf("Problem with %s \n",optionfilehtm);
6505: exit(0);
1.126 brouard 6506: }
6507:
6508: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6509: strcat(optionfilehtmcov,"-cov.htm");
6510: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6511: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6512: }
6513: else{
6514: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6515: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6516: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6517: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6518: }
6519:
6520: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6521: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6522: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6523: \n\
6524: <hr size=\"2\" color=\"#EC5E5E\">\
6525: <ul><li><h4>Parameter files</h4>\n\
6526: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6527: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6528: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6529: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6530: - Date and time at start: %s</ul>\n",\
6531: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6532: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6533: fileres,fileres,\
6534: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6535: fflush(fichtm);
6536:
6537: strcpy(pathr,path);
6538: strcat(pathr,optionfilefiname);
6539: chdir(optionfilefiname); /* Move to directory named optionfile */
6540:
6541: /* Calculates basic frequencies. Computes observed prevalence at single age
6542: and prints on file fileres'p'. */
6543: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6544:
6545: fprintf(fichtm,"\n");
6546: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6547: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6548: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6549: imx,agemin,agemax,jmin,jmax,jmean);
6550: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6551: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6552: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6553: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6554: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6555:
6556:
6557: /* For Powell, parameters are in a vector p[] starting at p[1]
6558: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6559: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6560:
6561: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6562:
6563: if (mle==-3){
1.136 brouard 6564: ximort=matrix(1,NDIM,1,NDIM);
6565: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6566: cens=ivector(1,n);
6567: ageexmed=vector(1,n);
6568: agecens=vector(1,n);
6569: dcwave=ivector(1,n);
6570:
6571: for (i=1; i<=imx; i++){
6572: dcwave[i]=-1;
6573: for (m=firstpass; m<=lastpass; m++)
6574: if (s[m][i]>nlstate) {
6575: dcwave[i]=m;
6576: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6577: break;
6578: }
6579: }
6580:
6581: for (i=1; i<=imx; i++) {
6582: if (wav[i]>0){
6583: ageexmed[i]=agev[mw[1][i]][i];
6584: j=wav[i];
6585: agecens[i]=1.;
6586:
6587: if (ageexmed[i]> 1 && wav[i] > 0){
6588: agecens[i]=agev[mw[j][i]][i];
6589: cens[i]= 1;
6590: }else if (ageexmed[i]< 1)
6591: cens[i]= -1;
6592: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6593: cens[i]=0 ;
6594: }
6595: else cens[i]=-1;
6596: }
6597:
6598: for (i=1;i<=NDIM;i++) {
6599: for (j=1;j<=NDIM;j++)
6600: ximort[i][j]=(i == j ? 1.0 : 0.0);
6601: }
6602:
1.145 brouard 6603: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6604: /*printf("%lf %lf", p[1], p[2]);*/
6605:
6606:
1.136 brouard 6607: #ifdef GSL
6608: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6609: #else
1.126 brouard 6610: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6611: #endif
1.126 brouard 6612: strcpy(filerespow,"pow-mort");
6613: strcat(filerespow,fileres);
6614: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6615: printf("Problem with resultfile: %s\n", filerespow);
6616: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6617: }
1.136 brouard 6618: #ifdef GSL
6619: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6620: #else
1.126 brouard 6621: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6622: #endif
1.126 brouard 6623: /* for (i=1;i<=nlstate;i++)
6624: for(j=1;j<=nlstate+ndeath;j++)
6625: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6626: */
6627: fprintf(ficrespow,"\n");
1.136 brouard 6628: #ifdef GSL
6629: /* gsl starts here */
6630: T = gsl_multimin_fminimizer_nmsimplex;
6631: gsl_multimin_fminimizer *sfm = NULL;
6632: gsl_vector *ss, *x;
6633: gsl_multimin_function minex_func;
6634:
6635: /* Initial vertex size vector */
6636: ss = gsl_vector_alloc (NDIM);
6637:
6638: if (ss == NULL){
6639: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6640: }
6641: /* Set all step sizes to 1 */
6642: gsl_vector_set_all (ss, 0.001);
6643:
6644: /* Starting point */
1.126 brouard 6645:
1.136 brouard 6646: x = gsl_vector_alloc (NDIM);
6647:
6648: if (x == NULL){
6649: gsl_vector_free(ss);
6650: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6651: }
6652:
6653: /* Initialize method and iterate */
6654: /* p[1]=0.0268; p[NDIM]=0.083; */
6655: /* gsl_vector_set(x, 0, 0.0268); */
6656: /* gsl_vector_set(x, 1, 0.083); */
6657: gsl_vector_set(x, 0, p[1]);
6658: gsl_vector_set(x, 1, p[2]);
6659:
6660: minex_func.f = &gompertz_f;
6661: minex_func.n = NDIM;
6662: minex_func.params = (void *)&p; /* ??? */
6663:
6664: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6665: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6666:
6667: printf("Iterations beginning .....\n\n");
6668: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6669:
6670: iteri=0;
6671: while (rval == GSL_CONTINUE){
6672: iteri++;
6673: status = gsl_multimin_fminimizer_iterate(sfm);
6674:
6675: if (status) printf("error: %s\n", gsl_strerror (status));
6676: fflush(0);
6677:
6678: if (status)
6679: break;
6680:
6681: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6682: ssval = gsl_multimin_fminimizer_size (sfm);
6683:
6684: if (rval == GSL_SUCCESS)
6685: printf ("converged to a local maximum at\n");
6686:
6687: printf("%5d ", iteri);
6688: for (it = 0; it < NDIM; it++){
6689: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6690: }
6691: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6692: }
6693:
6694: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6695:
6696: gsl_vector_free(x); /* initial values */
6697: gsl_vector_free(ss); /* inital step size */
6698: for (it=0; it<NDIM; it++){
6699: p[it+1]=gsl_vector_get(sfm->x,it);
6700: fprintf(ficrespow," %.12lf", p[it]);
6701: }
6702: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6703: #endif
6704: #ifdef POWELL
6705: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6706: #endif
1.126 brouard 6707: fclose(ficrespow);
6708:
6709: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6710:
6711: for(i=1; i <=NDIM; i++)
6712: for(j=i+1;j<=NDIM;j++)
6713: matcov[i][j]=matcov[j][i];
6714:
6715: printf("\nCovariance matrix\n ");
6716: for(i=1; i <=NDIM; i++) {
6717: for(j=1;j<=NDIM;j++){
6718: printf("%f ",matcov[i][j]);
6719: }
6720: printf("\n ");
6721: }
6722:
6723: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6724: for (i=1;i<=NDIM;i++)
6725: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6726:
6727: lsurv=vector(1,AGESUP);
6728: lpop=vector(1,AGESUP);
6729: tpop=vector(1,AGESUP);
6730: lsurv[agegomp]=100000;
6731:
6732: for (k=agegomp;k<=AGESUP;k++) {
6733: agemortsup=k;
6734: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6735: }
6736:
6737: for (k=agegomp;k<agemortsup;k++)
6738: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6739:
6740: for (k=agegomp;k<agemortsup;k++){
6741: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6742: sumlpop=sumlpop+lpop[k];
6743: }
6744:
6745: tpop[agegomp]=sumlpop;
6746: for (k=agegomp;k<(agemortsup-3);k++){
6747: /* tpop[k+1]=2;*/
6748: tpop[k+1]=tpop[k]-lpop[k];
6749: }
6750:
6751:
6752: printf("\nAge lx qx dx Lx Tx e(x)\n");
6753: for (k=agegomp;k<(agemortsup-2);k++)
6754: 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]);
6755:
6756:
6757: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6758: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6759:
6760: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6761: stepm, weightopt,\
6762: model,imx,p,matcov,agemortsup);
6763:
6764: free_vector(lsurv,1,AGESUP);
6765: free_vector(lpop,1,AGESUP);
6766: free_vector(tpop,1,AGESUP);
1.136 brouard 6767: #ifdef GSL
6768: free_ivector(cens,1,n);
6769: free_vector(agecens,1,n);
6770: free_ivector(dcwave,1,n);
6771: free_matrix(ximort,1,NDIM,1,NDIM);
6772: #endif
1.126 brouard 6773: } /* Endof if mle==-3 */
6774:
6775: else{ /* For mle >=1 */
1.132 brouard 6776: globpr=0;/* debug */
6777: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6778: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6779: for (k=1; k<=npar;k++)
6780: printf(" %d %8.5f",k,p[k]);
6781: printf("\n");
6782: globpr=1; /* to print the contributions */
6783: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6784: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6785: for (k=1; k<=npar;k++)
6786: printf(" %d %8.5f",k,p[k]);
6787: printf("\n");
6788: if(mle>=1){ /* Could be 1 or 2 */
6789: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6790: }
6791:
6792: /*--------- results files --------------*/
6793: 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);
6794:
6795:
6796: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6797: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6798: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6799: for(i=1,jk=1; i <=nlstate; i++){
6800: for(k=1; k <=(nlstate+ndeath); k++){
6801: if (k != i) {
6802: printf("%d%d ",i,k);
6803: fprintf(ficlog,"%d%d ",i,k);
6804: fprintf(ficres,"%1d%1d ",i,k);
6805: for(j=1; j <=ncovmodel; j++){
6806: printf("%lf ",p[jk]);
6807: fprintf(ficlog,"%lf ",p[jk]);
6808: fprintf(ficres,"%lf ",p[jk]);
6809: jk++;
6810: }
6811: printf("\n");
6812: fprintf(ficlog,"\n");
6813: fprintf(ficres,"\n");
6814: }
6815: }
6816: }
6817: if(mle!=0){
6818: /* Computing hessian and covariance matrix */
6819: ftolhess=ftol; /* Usually correct */
6820: hesscov(matcov, p, npar, delti, ftolhess, func);
6821: }
6822: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6823: printf("# Scales (for hessian or gradient estimation)\n");
6824: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6825: for(i=1,jk=1; i <=nlstate; i++){
6826: for(j=1; j <=nlstate+ndeath; j++){
6827: if (j!=i) {
6828: fprintf(ficres,"%1d%1d",i,j);
6829: printf("%1d%1d",i,j);
6830: fprintf(ficlog,"%1d%1d",i,j);
6831: for(k=1; k<=ncovmodel;k++){
6832: printf(" %.5e",delti[jk]);
6833: fprintf(ficlog," %.5e",delti[jk]);
6834: fprintf(ficres," %.5e",delti[jk]);
6835: jk++;
6836: }
6837: printf("\n");
6838: fprintf(ficlog,"\n");
6839: fprintf(ficres,"\n");
6840: }
6841: }
6842: }
6843:
6844: 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");
6845: if(mle>=1)
6846: 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");
6847: 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");
6848: /* # 121 Var(a12)\n\ */
6849: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6850: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6851: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6852: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6853: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6854: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6855: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6856:
6857:
6858: /* Just to have a covariance matrix which will be more understandable
6859: even is we still don't want to manage dictionary of variables
6860: */
6861: for(itimes=1;itimes<=2;itimes++){
6862: jj=0;
6863: for(i=1; i <=nlstate; i++){
6864: for(j=1; j <=nlstate+ndeath; j++){
6865: if(j==i) continue;
6866: for(k=1; k<=ncovmodel;k++){
6867: jj++;
6868: ca[0]= k+'a'-1;ca[1]='\0';
6869: if(itimes==1){
6870: if(mle>=1)
6871: printf("#%1d%1d%d",i,j,k);
6872: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6873: fprintf(ficres,"#%1d%1d%d",i,j,k);
6874: }else{
6875: if(mle>=1)
6876: printf("%1d%1d%d",i,j,k);
6877: fprintf(ficlog,"%1d%1d%d",i,j,k);
6878: fprintf(ficres,"%1d%1d%d",i,j,k);
6879: }
6880: ll=0;
6881: for(li=1;li <=nlstate; li++){
6882: for(lj=1;lj <=nlstate+ndeath; lj++){
6883: if(lj==li) continue;
6884: for(lk=1;lk<=ncovmodel;lk++){
6885: ll++;
6886: if(ll<=jj){
6887: cb[0]= lk +'a'-1;cb[1]='\0';
6888: if(ll<jj){
6889: if(itimes==1){
6890: if(mle>=1)
6891: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6892: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6893: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6894: }else{
6895: if(mle>=1)
6896: printf(" %.5e",matcov[jj][ll]);
6897: fprintf(ficlog," %.5e",matcov[jj][ll]);
6898: fprintf(ficres," %.5e",matcov[jj][ll]);
6899: }
6900: }else{
6901: if(itimes==1){
6902: if(mle>=1)
6903: printf(" Var(%s%1d%1d)",ca,i,j);
6904: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6905: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6906: }else{
6907: if(mle>=1)
6908: printf(" %.5e",matcov[jj][ll]);
6909: fprintf(ficlog," %.5e",matcov[jj][ll]);
6910: fprintf(ficres," %.5e",matcov[jj][ll]);
6911: }
6912: }
6913: }
6914: } /* end lk */
6915: } /* end lj */
6916: } /* end li */
6917: if(mle>=1)
6918: printf("\n");
6919: fprintf(ficlog,"\n");
6920: fprintf(ficres,"\n");
6921: numlinepar++;
6922: } /* end k*/
6923: } /*end j */
6924: } /* end i */
6925: } /* end itimes */
6926:
6927: fflush(ficlog);
6928: fflush(ficres);
6929:
6930: while((c=getc(ficpar))=='#' && c!= EOF){
6931: ungetc(c,ficpar);
6932: fgets(line, MAXLINE, ficpar);
1.141 brouard 6933: fputs(line,stdout);
1.126 brouard 6934: fputs(line,ficparo);
6935: }
6936: ungetc(c,ficpar);
6937:
6938: estepm=0;
6939: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6940: if (estepm==0 || estepm < stepm) estepm=stepm;
6941: if (fage <= 2) {
6942: bage = ageminpar;
6943: fage = agemaxpar;
6944: }
6945:
6946: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6947: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6948: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6949:
6950: while((c=getc(ficpar))=='#' && c!= EOF){
6951: ungetc(c,ficpar);
6952: fgets(line, MAXLINE, ficpar);
1.141 brouard 6953: fputs(line,stdout);
1.126 brouard 6954: fputs(line,ficparo);
6955: }
6956: ungetc(c,ficpar);
6957:
6958: 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);
6959: 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);
6960: 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);
6961: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6962: 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);
6963:
6964: while((c=getc(ficpar))=='#' && c!= EOF){
6965: ungetc(c,ficpar);
6966: fgets(line, MAXLINE, ficpar);
1.141 brouard 6967: fputs(line,stdout);
1.126 brouard 6968: fputs(line,ficparo);
6969: }
6970: ungetc(c,ficpar);
6971:
6972:
6973: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6974: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6975:
6976: fscanf(ficpar,"pop_based=%d\n",&popbased);
6977: fprintf(ficparo,"pop_based=%d\n",popbased);
6978: fprintf(ficres,"pop_based=%d\n",popbased);
6979:
6980: while((c=getc(ficpar))=='#' && c!= EOF){
6981: ungetc(c,ficpar);
6982: fgets(line, MAXLINE, ficpar);
1.141 brouard 6983: fputs(line,stdout);
1.126 brouard 6984: fputs(line,ficparo);
6985: }
6986: ungetc(c,ficpar);
6987:
6988: 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);
6989: 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);
6990: 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);
6991: 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);
6992: 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);
6993: /* day and month of proj2 are not used but only year anproj2.*/
6994:
6995:
6996:
1.145 brouard 6997: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6998: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6999:
7000: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7001: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7002:
7003: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7004: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7005: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7006:
7007: /*------------ free_vector -------------*/
7008: /* chdir(path); */
7009:
7010: free_ivector(wav,1,imx);
7011: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7012: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7013: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7014: free_lvector(num,1,n);
7015: free_vector(agedc,1,n);
7016: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7017: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7018: fclose(ficparo);
7019: fclose(ficres);
7020:
7021:
7022: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7023: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7024: prlim=matrix(1,nlstate,1,nlstate);
7025: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7026: fclose(ficrespl);
7027:
1.145 brouard 7028: #ifdef FREEEXIT2
7029: #include "freeexit2.h"
7030: #endif
7031:
1.126 brouard 7032: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7033: /*#include "hpijx.h"*/
7034: hPijx(p, bage, fage);
1.145 brouard 7035: fclose(ficrespij);
1.126 brouard 7036:
1.145 brouard 7037: /*-------------- Variance of one-step probabilities---*/
7038: k=1;
1.126 brouard 7039: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7040:
7041:
7042: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7043: for(i=1;i<=AGESUP;i++)
7044: for(j=1;j<=NCOVMAX;j++)
7045: for(k=1;k<=NCOVMAX;k++)
7046: probs[i][j][k]=0.;
7047:
7048: /*---------- Forecasting ------------------*/
7049: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7050: if(prevfcast==1){
7051: /* if(stepm ==1){*/
7052: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7053: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7054: /* } */
7055: /* else{ */
7056: /* erreur=108; */
7057: /* 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); */
7058: /* 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); */
7059: /* } */
7060: }
7061:
7062:
1.127 brouard 7063: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7064:
7065: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7066: /* 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",\
7067: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7068: */
1.126 brouard 7069:
1.127 brouard 7070: if (mobilav!=0) {
7071: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7072: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7073: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7074: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7075: }
1.126 brouard 7076: }
7077:
7078:
1.127 brouard 7079: /*---------- Health expectancies, no variances ------------*/
7080:
1.126 brouard 7081: strcpy(filerese,"e");
7082: strcat(filerese,fileres);
7083: if((ficreseij=fopen(filerese,"w"))==NULL) {
7084: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7085: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7086: }
7087: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7088: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7089: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7090: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7091:
7092: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7093: fprintf(ficreseij,"\n#****** ");
7094: for(j=1;j<=cptcoveff;j++) {
7095: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7096: }
7097: fprintf(ficreseij,"******\n");
7098:
7099: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7100: oldm=oldms;savm=savms;
7101: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7102:
7103: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7104: /*}*/
1.127 brouard 7105: }
7106: fclose(ficreseij);
7107:
7108:
7109: /*---------- Health expectancies and variances ------------*/
7110:
7111:
7112: strcpy(filerest,"t");
7113: strcat(filerest,fileres);
7114: if((ficrest=fopen(filerest,"w"))==NULL) {
7115: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7116: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7117: }
7118: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7119: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7120:
1.126 brouard 7121:
7122: strcpy(fileresstde,"stde");
7123: strcat(fileresstde,fileres);
7124: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7125: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7126: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7127: }
7128: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7129: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7130:
7131: strcpy(filerescve,"cve");
7132: strcat(filerescve,fileres);
7133: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7134: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7135: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7136: }
7137: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7138: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7139:
7140: strcpy(fileresv,"v");
7141: strcat(fileresv,fileres);
7142: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7143: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7144: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7145: }
7146: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7147: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7148:
1.145 brouard 7149: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7150: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7151:
7152: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7153: fprintf(ficrest,"\n#****** ");
1.126 brouard 7154: for(j=1;j<=cptcoveff;j++)
7155: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7156: fprintf(ficrest,"******\n");
7157:
7158: fprintf(ficresstdeij,"\n#****** ");
7159: fprintf(ficrescveij,"\n#****** ");
7160: for(j=1;j<=cptcoveff;j++) {
7161: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7162: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7163: }
7164: fprintf(ficresstdeij,"******\n");
7165: fprintf(ficrescveij,"******\n");
7166:
7167: fprintf(ficresvij,"\n#****** ");
7168: for(j=1;j<=cptcoveff;j++)
7169: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7170: fprintf(ficresvij,"******\n");
7171:
7172: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7173: oldm=oldms;savm=savms;
1.127 brouard 7174: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7175: /*
7176: */
7177: /* goto endfree; */
1.126 brouard 7178:
7179: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7180: pstamp(ficrest);
1.145 brouard 7181:
7182:
1.128 brouard 7183: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7184: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7185: cptcod= 0; /* To be deleted */
7186: 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 7187: 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 7188: if(vpopbased==1)
7189: 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);
7190: else
7191: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7192: fprintf(ficrest,"# Age e.. (std) ");
7193: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7194: fprintf(ficrest,"\n");
1.126 brouard 7195:
1.128 brouard 7196: epj=vector(1,nlstate+1);
7197: for(age=bage; age <=fage ;age++){
7198: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7199: if (vpopbased==1) {
7200: if(mobilav ==0){
7201: for(i=1; i<=nlstate;i++)
7202: prlim[i][i]=probs[(int)age][i][k];
7203: }else{ /* mobilav */
7204: for(i=1; i<=nlstate;i++)
7205: prlim[i][i]=mobaverage[(int)age][i][k];
7206: }
1.126 brouard 7207: }
7208:
1.128 brouard 7209: fprintf(ficrest," %4.0f",age);
7210: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7211: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7212: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7213: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7214: }
7215: epj[nlstate+1] +=epj[j];
1.126 brouard 7216: }
7217:
1.128 brouard 7218: for(i=1, vepp=0.;i <=nlstate;i++)
7219: for(j=1;j <=nlstate;j++)
7220: vepp += vareij[i][j][(int)age];
7221: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7222: for(j=1;j <=nlstate;j++){
7223: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7224: }
7225: fprintf(ficrest,"\n");
1.126 brouard 7226: }
7227: }
7228: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7229: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7230: free_vector(epj,1,nlstate+1);
1.145 brouard 7231: /*}*/
1.126 brouard 7232: }
7233: free_vector(weight,1,n);
1.145 brouard 7234: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7235: free_imatrix(s,1,maxwav+1,1,n);
7236: free_matrix(anint,1,maxwav,1,n);
7237: free_matrix(mint,1,maxwav,1,n);
7238: free_ivector(cod,1,n);
7239: free_ivector(tab,1,NCOVMAX);
7240: fclose(ficresstdeij);
7241: fclose(ficrescveij);
7242: fclose(ficresvij);
7243: fclose(ficrest);
7244: fclose(ficpar);
7245:
7246: /*------- Variance of period (stable) prevalence------*/
7247:
7248: strcpy(fileresvpl,"vpl");
7249: strcat(fileresvpl,fileres);
7250: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7251: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7252: exit(0);
7253: }
7254: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7255:
1.145 brouard 7256: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7257: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7258:
7259: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7260: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7261: for(j=1;j<=cptcoveff;j++)
7262: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7263: fprintf(ficresvpl,"******\n");
7264:
7265: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7266: oldm=oldms;savm=savms;
7267: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7268: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7269: /*}*/
1.126 brouard 7270: }
7271:
7272: fclose(ficresvpl);
7273:
7274: /*---------- End : free ----------------*/
7275: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7276: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7277: } /* mle==-3 arrives here for freeing */
1.164 brouard 7278: /* endfree:*/
1.141 brouard 7279: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7280: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7281: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7282: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7283: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7284: free_matrix(covar,0,NCOVMAX,1,n);
7285: free_matrix(matcov,1,npar,1,npar);
7286: /*free_vector(delti,1,npar);*/
7287: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7288: free_matrix(agev,1,maxwav,1,imx);
7289: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7290:
1.145 brouard 7291: free_ivector(ncodemax,1,NCOVMAX);
7292: free_ivector(Tvar,1,NCOVMAX);
7293: free_ivector(Tprod,1,NCOVMAX);
7294: free_ivector(Tvaraff,1,NCOVMAX);
7295: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7296:
7297: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7298: free_imatrix(codtab,1,100,1,10);
7299: fflush(fichtm);
7300: fflush(ficgp);
7301:
7302:
7303: if((nberr >0) || (nbwarn>0)){
7304: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7305: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7306: }else{
7307: printf("End of Imach\n");
7308: fprintf(ficlog,"End of Imach\n");
7309: }
7310: printf("See log file on %s\n",filelog);
7311: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7312: /*(void) gettimeofday(&end_time,&tzp);*/
7313: rend_time = time(NULL);
7314: end_time = *localtime(&rend_time);
7315: /* tml = *localtime(&end_time.tm_sec); */
7316: strcpy(strtend,asctime(&end_time));
1.126 brouard 7317: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7318: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7319: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7320:
1.157 brouard 7321: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7322: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7323: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7324: /* printf("Total time was %d uSec.\n", total_usecs);*/
7325: /* if(fileappend(fichtm,optionfilehtm)){ */
7326: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7327: fclose(fichtm);
7328: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7329: fclose(fichtmcov);
7330: fclose(ficgp);
7331: fclose(ficlog);
7332: /*------ End -----------*/
7333:
7334:
7335: printf("Before Current directory %s!\n",pathcd);
7336: if(chdir(pathcd) != 0)
7337: printf("Can't move to directory %s!\n",path);
7338: if(getcwd(pathcd,MAXLINE) > 0)
7339: printf("Current directory %s!\n",pathcd);
7340: /*strcat(plotcmd,CHARSEPARATOR);*/
7341: sprintf(plotcmd,"gnuplot");
1.157 brouard 7342: #ifdef _WIN32
1.126 brouard 7343: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7344: #endif
7345: if(!stat(plotcmd,&info)){
1.158 brouard 7346: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7347: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7348: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7349: }else
7350: strcpy(pplotcmd,plotcmd);
1.157 brouard 7351: #ifdef __unix
1.126 brouard 7352: strcpy(plotcmd,GNUPLOTPROGRAM);
7353: if(!stat(plotcmd,&info)){
1.158 brouard 7354: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7355: }else
7356: strcpy(pplotcmd,plotcmd);
7357: #endif
7358: }else
7359: strcpy(pplotcmd,plotcmd);
7360:
7361: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7362: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7363:
7364: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7365: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7366: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7367: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7368: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7369: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7370: }
1.158 brouard 7371: printf(" Successful, please wait...");
1.126 brouard 7372: while (z[0] != 'q') {
7373: /* chdir(path); */
1.154 brouard 7374: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7375: scanf("%s",z);
7376: /* if (z[0] == 'c') system("./imach"); */
7377: if (z[0] == 'e') {
1.158 brouard 7378: #ifdef __APPLE__
1.152 brouard 7379: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7380: #elif __linux
7381: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7382: #else
1.152 brouard 7383: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7384: #endif
7385: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7386: system(pplotcmd);
1.126 brouard 7387: }
7388: else if (z[0] == 'g') system(plotcmd);
7389: else if (z[0] == 'q') exit(0);
7390: }
7391: end:
7392: while (z[0] != 'q') {
7393: printf("\nType q for exiting: ");
7394: scanf("%s",z);
7395: }
7396: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>