Annotation of imach/src/imach.c, revision 1.167
1.167 ! brouard 1: /* $Id: imach.c,v 1.166 2014/12/22 11:40:47 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.167 ! brouard 4: Revision 1.166 2014/12/22 11:40:47 brouard
! 5: *** empty log message ***
! 6:
1.166 brouard 7: Revision 1.165 2014/12/16 11:20:36 brouard
8: Summary: After compiling on Visual C
9:
10: * imach.c (Module): Merging 1.61 to 1.162
11:
1.165 brouard 12: Revision 1.164 2014/12/16 10:52:11 brouard
13: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
14:
15: * imach.c (Module): Merging 1.61 to 1.162
16:
1.164 brouard 17: Revision 1.163 2014/12/16 10:30:11 brouard
18: * imach.c (Module): Merging 1.61 to 1.162
19:
1.163 brouard 20: Revision 1.162 2014/09/25 11:43:39 brouard
21: Summary: temporary backup 0.99!
22:
1.162 brouard 23: Revision 1.1 2014/09/16 11:06:58 brouard
24: Summary: With some code (wrong) for nlopt
25:
26: Author:
27:
28: Revision 1.161 2014/09/15 20:41:41 brouard
29: Summary: Problem with macro SQR on Intel compiler
30:
1.161 brouard 31: Revision 1.160 2014/09/02 09:24:05 brouard
32: *** empty log message ***
33:
1.160 brouard 34: Revision 1.159 2014/09/01 10:34:10 brouard
35: Summary: WIN32
36: Author: Brouard
37:
1.159 brouard 38: Revision 1.158 2014/08/27 17:11:51 brouard
39: *** empty log message ***
40:
1.158 brouard 41: Revision 1.157 2014/08/27 16:26:55 brouard
42: Summary: Preparing windows Visual studio version
43: Author: Brouard
44:
45: In order to compile on Visual studio, time.h is now correct and time_t
46: and tm struct should be used. difftime should be used but sometimes I
47: just make the differences in raw time format (time(&now).
48: Trying to suppress #ifdef LINUX
49: Add xdg-open for __linux in order to open default browser.
50:
1.157 brouard 51: Revision 1.156 2014/08/25 20:10:10 brouard
52: *** empty log message ***
53:
1.156 brouard 54: Revision 1.155 2014/08/25 18:32:34 brouard
55: Summary: New compile, minor changes
56: Author: Brouard
57:
1.155 brouard 58: Revision 1.154 2014/06/20 17:32:08 brouard
59: Summary: Outputs now all graphs of convergence to period prevalence
60:
1.154 brouard 61: Revision 1.153 2014/06/20 16:45:46 brouard
62: Summary: If 3 live state, convergence to period prevalence on same graph
63: Author: Brouard
64:
1.153 brouard 65: Revision 1.152 2014/06/18 17:54:09 brouard
66: Summary: open browser, use gnuplot on same dir than imach if not found in the path
67:
1.152 brouard 68: Revision 1.151 2014/06/18 16:43:30 brouard
69: *** empty log message ***
70:
1.151 brouard 71: Revision 1.150 2014/06/18 16:42:35 brouard
72: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
73: Author: brouard
74:
1.150 brouard 75: Revision 1.149 2014/06/18 15:51:14 brouard
76: Summary: Some fixes in parameter files errors
77: Author: Nicolas Brouard
78:
1.149 brouard 79: Revision 1.148 2014/06/17 17:38:48 brouard
80: Summary: Nothing new
81: Author: Brouard
82:
83: Just a new packaging for OS/X version 0.98nS
84:
1.148 brouard 85: Revision 1.147 2014/06/16 10:33:11 brouard
86: *** empty log message ***
87:
1.147 brouard 88: Revision 1.146 2014/06/16 10:20:28 brouard
89: Summary: Merge
90: Author: Brouard
91:
92: Merge, before building revised version.
93:
1.146 brouard 94: Revision 1.145 2014/06/10 21:23:15 brouard
95: Summary: Debugging with valgrind
96: Author: Nicolas Brouard
97:
98: Lot of changes in order to output the results with some covariates
99: After the Edimburgh REVES conference 2014, it seems mandatory to
100: improve the code.
101: No more memory valgrind error but a lot has to be done in order to
102: continue the work of splitting the code into subroutines.
103: Also, decodemodel has been improved. Tricode is still not
104: optimal. nbcode should be improved. Documentation has been added in
105: the source code.
106:
1.144 brouard 107: Revision 1.143 2014/01/26 09:45:38 brouard
108: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
109:
110: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
111: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
112:
1.143 brouard 113: Revision 1.142 2014/01/26 03:57:36 brouard
114: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
115:
116: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
117:
1.142 brouard 118: Revision 1.141 2014/01/26 02:42:01 brouard
119: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
120:
1.141 brouard 121: Revision 1.140 2011/09/02 10:37:54 brouard
122: Summary: times.h is ok with mingw32 now.
123:
1.140 brouard 124: Revision 1.139 2010/06/14 07:50:17 brouard
125: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
126: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
127:
1.139 brouard 128: Revision 1.138 2010/04/30 18:19:40 brouard
129: *** empty log message ***
130:
1.138 brouard 131: Revision 1.137 2010/04/29 18:11:38 brouard
132: (Module): Checking covariates for more complex models
133: than V1+V2. A lot of change to be done. Unstable.
134:
1.137 brouard 135: Revision 1.136 2010/04/26 20:30:53 brouard
136: (Module): merging some libgsl code. Fixing computation
137: of likelione (using inter/intrapolation if mle = 0) in order to
138: get same likelihood as if mle=1.
139: Some cleaning of code and comments added.
140:
1.136 brouard 141: Revision 1.135 2009/10/29 15:33:14 brouard
142: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
143:
1.135 brouard 144: Revision 1.134 2009/10/29 13:18:53 brouard
145: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
146:
1.134 brouard 147: Revision 1.133 2009/07/06 10:21:25 brouard
148: just nforces
149:
1.133 brouard 150: Revision 1.132 2009/07/06 08:22:05 brouard
151: Many tings
152:
1.132 brouard 153: Revision 1.131 2009/06/20 16:22:47 brouard
154: Some dimensions resccaled
155:
1.131 brouard 156: Revision 1.130 2009/05/26 06:44:34 brouard
157: (Module): Max Covariate is now set to 20 instead of 8. A
158: lot of cleaning with variables initialized to 0. Trying to make
159: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
160:
1.130 brouard 161: Revision 1.129 2007/08/31 13:49:27 lievre
162: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
163:
1.129 lievre 164: Revision 1.128 2006/06/30 13:02:05 brouard
165: (Module): Clarifications on computing e.j
166:
1.128 brouard 167: Revision 1.127 2006/04/28 18:11:50 brouard
168: (Module): Yes the sum of survivors was wrong since
169: imach-114 because nhstepm was no more computed in the age
170: loop. Now we define nhstepma in the age loop.
171: (Module): In order to speed up (in case of numerous covariates) we
172: compute health expectancies (without variances) in a first step
173: and then all the health expectancies with variances or standard
174: deviation (needs data from the Hessian matrices) which slows the
175: computation.
176: In the future we should be able to stop the program is only health
177: expectancies and graph are needed without standard deviations.
178:
1.127 brouard 179: Revision 1.126 2006/04/28 17:23:28 brouard
180: (Module): Yes the sum of survivors was wrong since
181: imach-114 because nhstepm was no more computed in the age
182: loop. Now we define nhstepma in the age loop.
183: Version 0.98h
184:
1.126 brouard 185: Revision 1.125 2006/04/04 15:20:31 lievre
186: Errors in calculation of health expectancies. Age was not initialized.
187: Forecasting file added.
188:
189: Revision 1.124 2006/03/22 17:13:53 lievre
190: Parameters are printed with %lf instead of %f (more numbers after the comma).
191: The log-likelihood is printed in the log file
192:
193: Revision 1.123 2006/03/20 10:52:43 brouard
194: * imach.c (Module): <title> changed, corresponds to .htm file
195: name. <head> headers where missing.
196:
197: * imach.c (Module): Weights can have a decimal point as for
198: English (a comma might work with a correct LC_NUMERIC environment,
199: otherwise the weight is truncated).
200: Modification of warning when the covariates values are not 0 or
201: 1.
202: Version 0.98g
203:
204: Revision 1.122 2006/03/20 09:45:41 brouard
205: (Module): Weights can have a decimal point as for
206: English (a comma might work with a correct LC_NUMERIC environment,
207: otherwise the weight is truncated).
208: Modification of warning when the covariates values are not 0 or
209: 1.
210: Version 0.98g
211:
212: Revision 1.121 2006/03/16 17:45:01 lievre
213: * imach.c (Module): Comments concerning covariates added
214:
215: * imach.c (Module): refinements in the computation of lli if
216: status=-2 in order to have more reliable computation if stepm is
217: not 1 month. Version 0.98f
218:
219: Revision 1.120 2006/03/16 15:10:38 lievre
220: (Module): refinements in the computation of lli if
221: status=-2 in order to have more reliable computation if stepm is
222: not 1 month. Version 0.98f
223:
224: Revision 1.119 2006/03/15 17:42:26 brouard
225: (Module): Bug if status = -2, the loglikelihood was
226: computed as likelihood omitting the logarithm. Version O.98e
227:
228: Revision 1.118 2006/03/14 18:20:07 brouard
229: (Module): varevsij Comments added explaining the second
230: table of variances if popbased=1 .
231: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
232: (Module): Function pstamp added
233: (Module): Version 0.98d
234:
235: Revision 1.117 2006/03/14 17:16:22 brouard
236: (Module): varevsij Comments added explaining the second
237: table of variances if popbased=1 .
238: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
239: (Module): Function pstamp added
240: (Module): Version 0.98d
241:
242: Revision 1.116 2006/03/06 10:29:27 brouard
243: (Module): Variance-covariance wrong links and
244: varian-covariance of ej. is needed (Saito).
245:
246: Revision 1.115 2006/02/27 12:17:45 brouard
247: (Module): One freematrix added in mlikeli! 0.98c
248:
249: Revision 1.114 2006/02/26 12:57:58 brouard
250: (Module): Some improvements in processing parameter
251: filename with strsep.
252:
253: Revision 1.113 2006/02/24 14:20:24 brouard
254: (Module): Memory leaks checks with valgrind and:
255: datafile was not closed, some imatrix were not freed and on matrix
256: allocation too.
257:
258: Revision 1.112 2006/01/30 09:55:26 brouard
259: (Module): Back to gnuplot.exe instead of wgnuplot.exe
260:
261: Revision 1.111 2006/01/25 20:38:18 brouard
262: (Module): Lots of cleaning and bugs added (Gompertz)
263: (Module): Comments can be added in data file. Missing date values
264: can be a simple dot '.'.
265:
266: Revision 1.110 2006/01/25 00:51:50 brouard
267: (Module): Lots of cleaning and bugs added (Gompertz)
268:
269: Revision 1.109 2006/01/24 19:37:15 brouard
270: (Module): Comments (lines starting with a #) are allowed in data.
271:
272: Revision 1.108 2006/01/19 18:05:42 lievre
273: Gnuplot problem appeared...
274: To be fixed
275:
276: Revision 1.107 2006/01/19 16:20:37 brouard
277: Test existence of gnuplot in imach path
278:
279: Revision 1.106 2006/01/19 13:24:36 brouard
280: Some cleaning and links added in html output
281:
282: Revision 1.105 2006/01/05 20:23:19 lievre
283: *** empty log message ***
284:
285: Revision 1.104 2005/09/30 16:11:43 lievre
286: (Module): sump fixed, loop imx fixed, and simplifications.
287: (Module): If the status is missing at the last wave but we know
288: that the person is alive, then we can code his/her status as -2
289: (instead of missing=-1 in earlier versions) and his/her
290: contributions to the likelihood is 1 - Prob of dying from last
291: health status (= 1-p13= p11+p12 in the easiest case of somebody in
292: the healthy state at last known wave). Version is 0.98
293:
294: Revision 1.103 2005/09/30 15:54:49 lievre
295: (Module): sump fixed, loop imx fixed, and simplifications.
296:
297: Revision 1.102 2004/09/15 17:31:30 brouard
298: Add the possibility to read data file including tab characters.
299:
300: Revision 1.101 2004/09/15 10:38:38 brouard
301: Fix on curr_time
302:
303: Revision 1.100 2004/07/12 18:29:06 brouard
304: Add version for Mac OS X. Just define UNIX in Makefile
305:
306: Revision 1.99 2004/06/05 08:57:40 brouard
307: *** empty log message ***
308:
309: Revision 1.98 2004/05/16 15:05:56 brouard
310: New version 0.97 . First attempt to estimate force of mortality
311: directly from the data i.e. without the need of knowing the health
312: state at each age, but using a Gompertz model: log u =a + b*age .
313: This is the basic analysis of mortality and should be done before any
314: other analysis, in order to test if the mortality estimated from the
315: cross-longitudinal survey is different from the mortality estimated
316: from other sources like vital statistic data.
317:
318: The same imach parameter file can be used but the option for mle should be -3.
319:
1.133 brouard 320: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 321: former routines in order to include the new code within the former code.
322:
323: The output is very simple: only an estimate of the intercept and of
324: the slope with 95% confident intervals.
325:
326: Current limitations:
327: A) Even if you enter covariates, i.e. with the
328: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
329: B) There is no computation of Life Expectancy nor Life Table.
330:
331: Revision 1.97 2004/02/20 13:25:42 lievre
332: Version 0.96d. Population forecasting command line is (temporarily)
333: suppressed.
334:
335: Revision 1.96 2003/07/15 15:38:55 brouard
336: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
337: rewritten within the same printf. Workaround: many printfs.
338:
339: Revision 1.95 2003/07/08 07:54:34 brouard
340: * imach.c (Repository):
341: (Repository): Using imachwizard code to output a more meaningful covariance
342: matrix (cov(a12,c31) instead of numbers.
343:
344: Revision 1.94 2003/06/27 13:00:02 brouard
345: Just cleaning
346:
347: Revision 1.93 2003/06/25 16:33:55 brouard
348: (Module): On windows (cygwin) function asctime_r doesn't
349: exist so I changed back to asctime which exists.
350: (Module): Version 0.96b
351:
352: Revision 1.92 2003/06/25 16:30:45 brouard
353: (Module): On windows (cygwin) function asctime_r doesn't
354: exist so I changed back to asctime which exists.
355:
356: Revision 1.91 2003/06/25 15:30:29 brouard
357: * imach.c (Repository): Duplicated warning errors corrected.
358: (Repository): Elapsed time after each iteration is now output. It
359: helps to forecast when convergence will be reached. Elapsed time
360: is stamped in powell. We created a new html file for the graphs
361: concerning matrix of covariance. It has extension -cov.htm.
362:
363: Revision 1.90 2003/06/24 12:34:15 brouard
364: (Module): Some bugs corrected for windows. Also, when
365: mle=-1 a template is output in file "or"mypar.txt with the design
366: of the covariance matrix to be input.
367:
368: Revision 1.89 2003/06/24 12:30:52 brouard
369: (Module): Some bugs corrected for windows. Also, when
370: mle=-1 a template is output in file "or"mypar.txt with the design
371: of the covariance matrix to be input.
372:
373: Revision 1.88 2003/06/23 17:54:56 brouard
374: * 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.
375:
376: Revision 1.87 2003/06/18 12:26:01 brouard
377: Version 0.96
378:
379: Revision 1.86 2003/06/17 20:04:08 brouard
380: (Module): Change position of html and gnuplot routines and added
381: routine fileappend.
382:
383: Revision 1.85 2003/06/17 13:12:43 brouard
384: * imach.c (Repository): Check when date of death was earlier that
385: current date of interview. It may happen when the death was just
386: prior to the death. In this case, dh was negative and likelihood
387: was wrong (infinity). We still send an "Error" but patch by
388: assuming that the date of death was just one stepm after the
389: interview.
390: (Repository): Because some people have very long ID (first column)
391: we changed int to long in num[] and we added a new lvector for
392: memory allocation. But we also truncated to 8 characters (left
393: truncation)
394: (Repository): No more line truncation errors.
395:
396: Revision 1.84 2003/06/13 21:44:43 brouard
397: * imach.c (Repository): Replace "freqsummary" at a correct
398: place. It differs from routine "prevalence" which may be called
399: many times. Probs is memory consuming and must be used with
400: parcimony.
401: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
402:
403: Revision 1.83 2003/06/10 13:39:11 lievre
404: *** empty log message ***
405:
406: Revision 1.82 2003/06/05 15:57:20 brouard
407: Add log in imach.c and fullversion number is now printed.
408:
409: */
410: /*
411: Interpolated Markov Chain
412:
413: Short summary of the programme:
414:
415: This program computes Healthy Life Expectancies from
416: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
417: first survey ("cross") where individuals from different ages are
418: interviewed on their health status or degree of disability (in the
419: case of a health survey which is our main interest) -2- at least a
420: second wave of interviews ("longitudinal") which measure each change
421: (if any) in individual health status. Health expectancies are
422: computed from the time spent in each health state according to a
423: model. More health states you consider, more time is necessary to reach the
424: Maximum Likelihood of the parameters involved in the model. The
425: simplest model is the multinomial logistic model where pij is the
426: probability to be observed in state j at the second wave
427: conditional to be observed in state i at the first wave. Therefore
428: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
429: 'age' is age and 'sex' is a covariate. If you want to have a more
430: complex model than "constant and age", you should modify the program
431: where the markup *Covariates have to be included here again* invites
432: you to do it. More covariates you add, slower the
433: convergence.
434:
435: The advantage of this computer programme, compared to a simple
436: multinomial logistic model, is clear when the delay between waves is not
437: identical for each individual. Also, if a individual missed an
438: intermediate interview, the information is lost, but taken into
439: account using an interpolation or extrapolation.
440:
441: hPijx is the probability to be observed in state i at age x+h
442: conditional to the observed state i at age x. The delay 'h' can be
443: split into an exact number (nh*stepm) of unobserved intermediate
444: states. This elementary transition (by month, quarter,
445: semester or year) is modelled as a multinomial logistic. The hPx
446: matrix is simply the matrix product of nh*stepm elementary matrices
447: and the contribution of each individual to the likelihood is simply
448: hPijx.
449:
450: Also this programme outputs the covariance matrix of the parameters but also
451: of the life expectancies. It also computes the period (stable) prevalence.
452:
1.133 brouard 453: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
454: Institut national d'études démographiques, Paris.
1.126 brouard 455: This software have been partly granted by Euro-REVES, a concerted action
456: from the European Union.
457: It is copyrighted identically to a GNU software product, ie programme and
458: software can be distributed freely for non commercial use. Latest version
459: can be accessed at http://euroreves.ined.fr/imach .
460:
461: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
462: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
463:
464: **********************************************************************/
465: /*
466: main
467: read parameterfile
468: read datafile
469: concatwav
470: freqsummary
471: if (mle >= 1)
472: mlikeli
473: print results files
474: if mle==1
475: computes hessian
476: read end of parameter file: agemin, agemax, bage, fage, estepm
477: begin-prev-date,...
478: open gnuplot file
479: open html file
1.145 brouard 480: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
481: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
482: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
483: freexexit2 possible for memory heap.
484:
485: h Pij x | pij_nom ficrestpij
486: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
487: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
488: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
489:
490: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
491: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
492: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
493: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
494: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
495:
1.126 brouard 496: forecasting if prevfcast==1 prevforecast call prevalence()
497: health expectancies
498: Variance-covariance of DFLE
499: prevalence()
500: movingaverage()
501: varevsij()
502: if popbased==1 varevsij(,popbased)
503: total life expectancies
504: Variance of period (stable) prevalence
505: end
506: */
507:
1.165 brouard 508: #define POWELL /* Instead of NLOPT */
1.126 brouard 509:
510: #include <math.h>
511: #include <stdio.h>
512: #include <stdlib.h>
513: #include <string.h>
1.159 brouard 514:
515: #ifdef _WIN32
516: #include <io.h>
517: #else
1.126 brouard 518: #include <unistd.h>
1.159 brouard 519: #endif
1.126 brouard 520:
521: #include <limits.h>
522: #include <sys/types.h>
1.167 ! brouard 523: #include <sys/utsname.h>
1.126 brouard 524: #include <sys/stat.h>
525: #include <errno.h>
1.159 brouard 526: /* extern int errno; */
1.126 brouard 527:
1.157 brouard 528: /* #ifdef LINUX */
529: /* #include <time.h> */
530: /* #include "timeval.h" */
531: /* #else */
532: /* #include <sys/time.h> */
533: /* #endif */
534:
1.126 brouard 535: #include <time.h>
536:
1.136 brouard 537: #ifdef GSL
538: #include <gsl/gsl_errno.h>
539: #include <gsl/gsl_multimin.h>
540: #endif
541:
1.167 ! brouard 542:
1.162 brouard 543: #ifdef NLOPT
544: #include <nlopt.h>
545: typedef struct {
546: double (* function)(double [] );
547: } myfunc_data ;
548: #endif
549:
1.126 brouard 550: /* #include <libintl.h> */
551: /* #define _(String) gettext (String) */
552:
1.141 brouard 553: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 554:
555: #define GNUPLOTPROGRAM "gnuplot"
556: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
557: #define FILENAMELENGTH 132
558:
559: #define GLOCK_ERROR_NOPATH -1 /* empty path */
560: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
561:
1.144 brouard 562: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
563: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 564:
565: #define NINTERVMAX 8
1.144 brouard 566: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
567: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
568: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 569: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 570: #define MAXN 20000
1.144 brouard 571: #define YEARM 12. /**< Number of months per year */
1.126 brouard 572: #define AGESUP 130
573: #define AGEBASE 40
1.164 brouard 574: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 575: #ifdef _WIN32
576: #define DIRSEPARATOR '\\'
577: #define CHARSEPARATOR "\\"
578: #define ODIRSEPARATOR '/'
579: #else
1.126 brouard 580: #define DIRSEPARATOR '/'
581: #define CHARSEPARATOR "/"
582: #define ODIRSEPARATOR '\\'
583: #endif
584:
1.167 ! brouard 585: /* $Id: imach.c,v 1.166 2014/12/22 11:40:47 brouard Exp $ */
1.126 brouard 586: /* $State: Exp $ */
587:
1.162 brouard 588: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.167 ! brouard 589: char fullversion[]="$Revision: 1.166 $ $Date: 2014/12/22 11:40:47 $";
1.126 brouard 590: char strstart[80];
591: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 592: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 593: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 594: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
595: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
596: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
597: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
598: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
599: int cptcovprodnoage=0; /**< Number of covariate products without age */
600: int cptcoveff=0; /* Total number of covariates to vary for printing results */
601: int cptcov=0; /* Working variable */
1.126 brouard 602: int npar=NPARMAX;
603: int nlstate=2; /* Number of live states */
604: int ndeath=1; /* Number of dead states */
1.130 brouard 605: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 606: int popbased=0;
607:
608: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 609: int maxwav=0; /* Maxim number of waves */
610: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
611: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
612: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 613: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 614: int mle=1, weightopt=0;
1.126 brouard 615: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
616: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
617: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
618: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 619: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 620: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 621: double **matprod2(); /* test */
1.126 brouard 622: double **oldm, **newm, **savm; /* Working pointers to matrices */
623: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 624: /*FILE *fic ; */ /* Used in readdata only */
625: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 626: FILE *ficlog, *ficrespow;
1.130 brouard 627: int globpr=0; /* Global variable for printing or not */
1.126 brouard 628: double fretone; /* Only one call to likelihood */
1.130 brouard 629: long ipmx=0; /* Number of contributions */
1.126 brouard 630: double sw; /* Sum of weights */
631: char filerespow[FILENAMELENGTH];
632: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
633: FILE *ficresilk;
634: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
635: FILE *ficresprobmorprev;
636: FILE *fichtm, *fichtmcov; /* Html File */
637: FILE *ficreseij;
638: char filerese[FILENAMELENGTH];
639: FILE *ficresstdeij;
640: char fileresstde[FILENAMELENGTH];
641: FILE *ficrescveij;
642: char filerescve[FILENAMELENGTH];
643: FILE *ficresvij;
644: char fileresv[FILENAMELENGTH];
645: FILE *ficresvpl;
646: char fileresvpl[FILENAMELENGTH];
647: char title[MAXLINE];
648: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
649: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
650: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
651: char command[FILENAMELENGTH];
652: int outcmd=0;
653:
654: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
655:
656: char filelog[FILENAMELENGTH]; /* Log file */
657: char filerest[FILENAMELENGTH];
658: char fileregp[FILENAMELENGTH];
659: char popfile[FILENAMELENGTH];
660:
661: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
662:
1.157 brouard 663: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
664: /* struct timezone tzp; */
665: /* extern int gettimeofday(); */
666: struct tm tml, *gmtime(), *localtime();
667:
668: extern time_t time();
669:
670: struct tm start_time, end_time, curr_time, last_time, forecast_time;
671: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
672: struct tm tm;
673:
1.126 brouard 674: char strcurr[80], strfor[80];
675:
676: char *endptr;
677: long lval;
678: double dval;
679:
680: #define NR_END 1
681: #define FREE_ARG char*
682: #define FTOL 1.0e-10
683:
684: #define NRANSI
685: #define ITMAX 200
686:
687: #define TOL 2.0e-4
688:
689: #define CGOLD 0.3819660
690: #define ZEPS 1.0e-10
691: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
692:
693: #define GOLD 1.618034
694: #define GLIMIT 100.0
695: #define TINY 1.0e-20
696:
697: static double maxarg1,maxarg2;
698: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
699: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
700:
701: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
702: #define rint(a) floor(a+0.5)
1.166 brouard 703: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
704: /* #define mytinydouble 1.0e-16 */
705: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
706: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
707: /* static double dsqrarg; */
708: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 709: static double sqrarg;
710: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
711: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
712: int agegomp= AGEGOMP;
713:
714: int imx;
715: int stepm=1;
716: /* Stepm, step in month: minimum step interpolation*/
717:
718: int estepm;
719: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
720:
721: int m,nb;
722: long *num;
723: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
724: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
725: double **pmmij, ***probs;
726: double *ageexmed,*agecens;
727: double dateintmean=0;
728:
729: double *weight;
730: int **s; /* Status */
1.141 brouard 731: double *agedc;
1.145 brouard 732: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 733: * covar=matrix(0,NCOVMAX,1,n);
734: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
735: double idx;
736: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 737: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 738: int **codtab; /**< codtab=imatrix(1,100,1,10); */
739: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 740: double *lsurv, *lpop, *tpop;
741:
1.143 brouard 742: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
743: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 744:
745: /**************** split *************************/
746: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
747: {
748: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
749: the name of the file (name), its extension only (ext) and its first part of the name (finame)
750: */
751: char *ss; /* pointer */
752: int l1, l2; /* length counters */
753:
754: l1 = strlen(path ); /* length of path */
755: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
756: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
757: if ( ss == NULL ) { /* no directory, so determine current directory */
758: strcpy( name, path ); /* we got the fullname name because no directory */
759: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
760: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
761: /* get current working directory */
762: /* extern char* getcwd ( char *buf , int len);*/
763: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
764: return( GLOCK_ERROR_GETCWD );
765: }
766: /* got dirc from getcwd*/
767: printf(" DIRC = %s \n",dirc);
768: } else { /* strip direcotry from path */
769: ss++; /* after this, the filename */
770: l2 = strlen( ss ); /* length of filename */
771: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
772: strcpy( name, ss ); /* save file name */
773: strncpy( dirc, path, l1 - l2 ); /* now the directory */
774: dirc[l1-l2] = 0; /* add zero */
775: printf(" DIRC2 = %s \n",dirc);
776: }
777: /* We add a separator at the end of dirc if not exists */
778: l1 = strlen( dirc ); /* length of directory */
779: if( dirc[l1-1] != DIRSEPARATOR ){
780: dirc[l1] = DIRSEPARATOR;
781: dirc[l1+1] = 0;
782: printf(" DIRC3 = %s \n",dirc);
783: }
784: ss = strrchr( name, '.' ); /* find last / */
785: if (ss >0){
786: ss++;
787: strcpy(ext,ss); /* save extension */
788: l1= strlen( name);
789: l2= strlen(ss)+1;
790: strncpy( finame, name, l1-l2);
791: finame[l1-l2]= 0;
792: }
793:
794: return( 0 ); /* we're done */
795: }
796:
797:
798: /******************************************/
799:
800: void replace_back_to_slash(char *s, char*t)
801: {
802: int i;
803: int lg=0;
804: i=0;
805: lg=strlen(t);
806: for(i=0; i<= lg; i++) {
807: (s[i] = t[i]);
808: if (t[i]== '\\') s[i]='/';
809: }
810: }
811:
1.132 brouard 812: char *trimbb(char *out, char *in)
1.137 brouard 813: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 814: char *s;
815: s=out;
816: while (*in != '\0'){
1.137 brouard 817: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 818: in++;
819: }
820: *out++ = *in++;
821: }
822: *out='\0';
823: return s;
824: }
825:
1.145 brouard 826: char *cutl(char *blocc, char *alocc, char *in, char occ)
827: {
828: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
829: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
830: gives blocc="abcdef2ghi" and alocc="j".
831: If occ is not found blocc is null and alocc is equal to in. Returns blocc
832: */
1.160 brouard 833: char *s, *t;
1.145 brouard 834: t=in;s=in;
835: while ((*in != occ) && (*in != '\0')){
836: *alocc++ = *in++;
837: }
838: if( *in == occ){
839: *(alocc)='\0';
840: s=++in;
841: }
842:
843: if (s == t) {/* occ not found */
844: *(alocc-(in-s))='\0';
845: in=s;
846: }
847: while ( *in != '\0'){
848: *blocc++ = *in++;
849: }
850:
851: *blocc='\0';
852: return t;
853: }
1.137 brouard 854: char *cutv(char *blocc, char *alocc, char *in, char occ)
855: {
856: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
857: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
858: gives blocc="abcdef2ghi" and alocc="j".
859: If occ is not found blocc is null and alocc is equal to in. Returns alocc
860: */
861: char *s, *t;
862: t=in;s=in;
863: while (*in != '\0'){
864: while( *in == occ){
865: *blocc++ = *in++;
866: s=in;
867: }
868: *blocc++ = *in++;
869: }
870: if (s == t) /* occ not found */
871: *(blocc-(in-s))='\0';
872: else
873: *(blocc-(in-s)-1)='\0';
874: in=s;
875: while ( *in != '\0'){
876: *alocc++ = *in++;
877: }
878:
879: *alocc='\0';
880: return s;
881: }
882:
1.126 brouard 883: int nbocc(char *s, char occ)
884: {
885: int i,j=0;
886: int lg=20;
887: i=0;
888: lg=strlen(s);
889: for(i=0; i<= lg; i++) {
890: if (s[i] == occ ) j++;
891: }
892: return j;
893: }
894:
1.137 brouard 895: /* void cutv(char *u,char *v, char*t, char occ) */
896: /* { */
897: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
898: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
899: /* gives u="abcdef2ghi" and v="j" *\/ */
900: /* int i,lg,j,p=0; */
901: /* i=0; */
902: /* lg=strlen(t); */
903: /* for(j=0; j<=lg-1; j++) { */
904: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
905: /* } */
1.126 brouard 906:
1.137 brouard 907: /* for(j=0; j<p; j++) { */
908: /* (u[j] = t[j]); */
909: /* } */
910: /* u[p]='\0'; */
1.126 brouard 911:
1.137 brouard 912: /* for(j=0; j<= lg; j++) { */
913: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
914: /* } */
915: /* } */
1.126 brouard 916:
1.160 brouard 917: #ifdef _WIN32
918: char * strsep(char **pp, const char *delim)
919: {
920: char *p, *q;
921:
922: if ((p = *pp) == NULL)
923: return 0;
924: if ((q = strpbrk (p, delim)) != NULL)
925: {
926: *pp = q + 1;
927: *q = '\0';
928: }
929: else
930: *pp = 0;
931: return p;
932: }
933: #endif
934:
1.126 brouard 935: /********************** nrerror ********************/
936:
937: void nrerror(char error_text[])
938: {
939: fprintf(stderr,"ERREUR ...\n");
940: fprintf(stderr,"%s\n",error_text);
941: exit(EXIT_FAILURE);
942: }
943: /*********************** vector *******************/
944: double *vector(int nl, int nh)
945: {
946: double *v;
947: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
948: if (!v) nrerror("allocation failure in vector");
949: return v-nl+NR_END;
950: }
951:
952: /************************ free vector ******************/
953: void free_vector(double*v, int nl, int nh)
954: {
955: free((FREE_ARG)(v+nl-NR_END));
956: }
957:
958: /************************ivector *******************************/
959: int *ivector(long nl,long nh)
960: {
961: int *v;
962: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
963: if (!v) nrerror("allocation failure in ivector");
964: return v-nl+NR_END;
965: }
966:
967: /******************free ivector **************************/
968: void free_ivector(int *v, long nl, long nh)
969: {
970: free((FREE_ARG)(v+nl-NR_END));
971: }
972:
973: /************************lvector *******************************/
974: long *lvector(long nl,long nh)
975: {
976: long *v;
977: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
978: if (!v) nrerror("allocation failure in ivector");
979: return v-nl+NR_END;
980: }
981:
982: /******************free lvector **************************/
983: void free_lvector(long *v, long nl, long nh)
984: {
985: free((FREE_ARG)(v+nl-NR_END));
986: }
987:
988: /******************* imatrix *******************************/
989: int **imatrix(long nrl, long nrh, long ncl, long nch)
990: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
991: {
992: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
993: int **m;
994:
995: /* allocate pointers to rows */
996: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
997: if (!m) nrerror("allocation failure 1 in matrix()");
998: m += NR_END;
999: m -= nrl;
1000:
1001:
1002: /* allocate rows and set pointers to them */
1003: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1004: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1005: m[nrl] += NR_END;
1006: m[nrl] -= ncl;
1007:
1008: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1009:
1010: /* return pointer to array of pointers to rows */
1011: return m;
1012: }
1013:
1014: /****************** free_imatrix *************************/
1015: void free_imatrix(m,nrl,nrh,ncl,nch)
1016: int **m;
1017: long nch,ncl,nrh,nrl;
1018: /* free an int matrix allocated by imatrix() */
1019: {
1020: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1021: free((FREE_ARG) (m+nrl-NR_END));
1022: }
1023:
1024: /******************* matrix *******************************/
1025: double **matrix(long nrl, long nrh, long ncl, long nch)
1026: {
1027: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1028: double **m;
1029:
1030: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1031: if (!m) nrerror("allocation failure 1 in matrix()");
1032: m += NR_END;
1033: m -= nrl;
1034:
1035: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1036: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1037: m[nrl] += NR_END;
1038: m[nrl] -= ncl;
1039:
1040: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1041: return m;
1.145 brouard 1042: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1043: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1044: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1045: */
1046: }
1047:
1048: /*************************free matrix ************************/
1049: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1050: {
1051: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1052: free((FREE_ARG)(m+nrl-NR_END));
1053: }
1054:
1055: /******************* ma3x *******************************/
1056: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1057: {
1058: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1059: double ***m;
1060:
1061: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1062: if (!m) nrerror("allocation failure 1 in matrix()");
1063: m += NR_END;
1064: m -= nrl;
1065:
1066: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1067: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1068: m[nrl] += NR_END;
1069: m[nrl] -= ncl;
1070:
1071: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1072:
1073: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1074: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1075: m[nrl][ncl] += NR_END;
1076: m[nrl][ncl] -= nll;
1077: for (j=ncl+1; j<=nch; j++)
1078: m[nrl][j]=m[nrl][j-1]+nlay;
1079:
1080: for (i=nrl+1; i<=nrh; i++) {
1081: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1082: for (j=ncl+1; j<=nch; j++)
1083: m[i][j]=m[i][j-1]+nlay;
1084: }
1085: return m;
1086: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1087: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1088: */
1089: }
1090:
1091: /*************************free ma3x ************************/
1092: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1093: {
1094: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1095: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1096: free((FREE_ARG)(m+nrl-NR_END));
1097: }
1098:
1099: /*************** function subdirf ***********/
1100: char *subdirf(char fileres[])
1101: {
1102: /* Caution optionfilefiname is hidden */
1103: strcpy(tmpout,optionfilefiname);
1104: strcat(tmpout,"/"); /* Add to the right */
1105: strcat(tmpout,fileres);
1106: return tmpout;
1107: }
1108:
1109: /*************** function subdirf2 ***********/
1110: char *subdirf2(char fileres[], char *preop)
1111: {
1112:
1113: /* Caution optionfilefiname is hidden */
1114: strcpy(tmpout,optionfilefiname);
1115: strcat(tmpout,"/");
1116: strcat(tmpout,preop);
1117: strcat(tmpout,fileres);
1118: return tmpout;
1119: }
1120:
1121: /*************** function subdirf3 ***********/
1122: char *subdirf3(char fileres[], char *preop, char *preop2)
1123: {
1124:
1125: /* Caution optionfilefiname is hidden */
1126: strcpy(tmpout,optionfilefiname);
1127: strcat(tmpout,"/");
1128: strcat(tmpout,preop);
1129: strcat(tmpout,preop2);
1130: strcat(tmpout,fileres);
1131: return tmpout;
1132: }
1133:
1.162 brouard 1134: char *asc_diff_time(long time_sec, char ascdiff[])
1135: {
1136: long sec_left, days, hours, minutes;
1137: days = (time_sec) / (60*60*24);
1138: sec_left = (time_sec) % (60*60*24);
1139: hours = (sec_left) / (60*60) ;
1140: sec_left = (sec_left) %(60*60);
1141: minutes = (sec_left) /60;
1142: sec_left = (sec_left) % (60);
1143: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1144: return ascdiff;
1145: }
1146:
1.126 brouard 1147: /***************** f1dim *************************/
1148: extern int ncom;
1149: extern double *pcom,*xicom;
1150: extern double (*nrfunc)(double []);
1151:
1152: double f1dim(double x)
1153: {
1154: int j;
1155: double f;
1156: double *xt;
1157:
1158: xt=vector(1,ncom);
1159: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1160: f=(*nrfunc)(xt);
1161: free_vector(xt,1,ncom);
1162: return f;
1163: }
1164:
1165: /*****************brent *************************/
1166: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1167: {
1168: int iter;
1169: double a,b,d,etemp;
1.159 brouard 1170: double fu=0,fv,fw,fx;
1.164 brouard 1171: double ftemp=0.;
1.126 brouard 1172: double p,q,r,tol1,tol2,u,v,w,x,xm;
1173: double e=0.0;
1174:
1175: a=(ax < cx ? ax : cx);
1176: b=(ax > cx ? ax : cx);
1177: x=w=v=bx;
1178: fw=fv=fx=(*f)(x);
1179: for (iter=1;iter<=ITMAX;iter++) {
1180: xm=0.5*(a+b);
1181: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1182: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1183: printf(".");fflush(stdout);
1184: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1185: #ifdef DEBUGBRENT
1.126 brouard 1186: 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);
1187: 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);
1188: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1189: #endif
1190: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1191: *xmin=x;
1192: return fx;
1193: }
1194: ftemp=fu;
1195: if (fabs(e) > tol1) {
1196: r=(x-w)*(fx-fv);
1197: q=(x-v)*(fx-fw);
1198: p=(x-v)*q-(x-w)*r;
1199: q=2.0*(q-r);
1200: if (q > 0.0) p = -p;
1201: q=fabs(q);
1202: etemp=e;
1203: e=d;
1204: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1205: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1206: else {
1207: d=p/q;
1208: u=x+d;
1209: if (u-a < tol2 || b-u < tol2)
1210: d=SIGN(tol1,xm-x);
1211: }
1212: } else {
1213: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1214: }
1215: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1216: fu=(*f)(u);
1217: if (fu <= fx) {
1218: if (u >= x) a=x; else b=x;
1219: SHFT(v,w,x,u)
1220: SHFT(fv,fw,fx,fu)
1221: } else {
1222: if (u < x) a=u; else b=u;
1223: if (fu <= fw || w == x) {
1224: v=w;
1225: w=u;
1226: fv=fw;
1227: fw=fu;
1228: } else if (fu <= fv || v == x || v == w) {
1229: v=u;
1230: fv=fu;
1231: }
1232: }
1233: }
1234: nrerror("Too many iterations in brent");
1235: *xmin=x;
1236: return fx;
1237: }
1238:
1239: /****************** mnbrak ***********************/
1240:
1241: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1242: double (*func)(double))
1243: {
1244: double ulim,u,r,q, dum;
1245: double fu;
1246:
1247: *fa=(*func)(*ax);
1248: *fb=(*func)(*bx);
1249: if (*fb > *fa) {
1250: SHFT(dum,*ax,*bx,dum)
1251: SHFT(dum,*fb,*fa,dum)
1252: }
1253: *cx=(*bx)+GOLD*(*bx-*ax);
1254: *fc=(*func)(*cx);
1.162 brouard 1255: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1256: r=(*bx-*ax)*(*fb-*fc);
1257: q=(*bx-*cx)*(*fb-*fa);
1258: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1259: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1260: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1261: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1262: fu=(*func)(u);
1.163 brouard 1263: #ifdef DEBUG
1264: /* f(x)=A(x-u)**2+f(u) */
1265: double A, fparabu;
1266: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1267: fparabu= *fa - A*(*ax-u)*(*ax-u);
1268: 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);
1269: 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);
1270: #endif
1.162 brouard 1271: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1272: fu=(*func)(u);
1273: if (fu < *fc) {
1274: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1275: SHFT(*fb,*fc,fu,(*func)(u))
1276: }
1.162 brouard 1277: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1278: u=ulim;
1279: fu=(*func)(u);
1280: } else {
1281: u=(*cx)+GOLD*(*cx-*bx);
1282: fu=(*func)(u);
1283: }
1284: SHFT(*ax,*bx,*cx,u)
1285: SHFT(*fa,*fb,*fc,fu)
1286: }
1287: }
1288:
1289: /*************** linmin ************************/
1.162 brouard 1290: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1291: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1292: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1293: the value of func at the returned location p . This is actually all accomplished by calling the
1294: routines mnbrak and brent .*/
1.126 brouard 1295: int ncom;
1296: double *pcom,*xicom;
1297: double (*nrfunc)(double []);
1298:
1299: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1300: {
1301: double brent(double ax, double bx, double cx,
1302: double (*f)(double), double tol, double *xmin);
1303: double f1dim(double x);
1304: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1305: double *fc, double (*func)(double));
1306: int j;
1307: double xx,xmin,bx,ax;
1308: double fx,fb,fa;
1309:
1310: ncom=n;
1311: pcom=vector(1,n);
1312: xicom=vector(1,n);
1313: nrfunc=func;
1314: for (j=1;j<=n;j++) {
1315: pcom[j]=p[j];
1316: xicom[j]=xi[j];
1317: }
1318: ax=0.0;
1319: xx=1.0;
1.162 brouard 1320: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1321: *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 1322: #ifdef DEBUG
1323: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1324: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1325: #endif
1326: for (j=1;j<=n;j++) {
1327: xi[j] *= xmin;
1328: p[j] += xi[j];
1329: }
1330: free_vector(xicom,1,n);
1331: free_vector(pcom,1,n);
1332: }
1333:
1334:
1335: /*************** powell ************************/
1.162 brouard 1336: /*
1337: Minimization of a function func of n variables. Input consists of an initial starting point
1338: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1339: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1340: such that failure to decrease by more than this amount on one iteration signals doneness. On
1341: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1342: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1343: */
1.126 brouard 1344: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1345: double (*func)(double []))
1346: {
1347: void linmin(double p[], double xi[], int n, double *fret,
1348: double (*func)(double []));
1349: int i,ibig,j;
1350: double del,t,*pt,*ptt,*xit;
1351: double fp,fptt;
1352: double *xits;
1353: int niterf, itmp;
1354:
1355: pt=vector(1,n);
1356: ptt=vector(1,n);
1357: xit=vector(1,n);
1358: xits=vector(1,n);
1359: *fret=(*func)(p);
1360: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1361: rcurr_time = time(NULL);
1.126 brouard 1362: for (*iter=1;;++(*iter)) {
1363: fp=(*fret);
1364: ibig=0;
1365: del=0.0;
1.157 brouard 1366: rlast_time=rcurr_time;
1367: /* (void) gettimeofday(&curr_time,&tzp); */
1368: rcurr_time = time(NULL);
1369: curr_time = *localtime(&rcurr_time);
1370: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1371: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1372: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1373: for (i=1;i<=n;i++) {
1374: printf(" %d %.12f",i, p[i]);
1375: fprintf(ficlog," %d %.12lf",i, p[i]);
1376: fprintf(ficrespow," %.12lf", p[i]);
1377: }
1378: printf("\n");
1379: fprintf(ficlog,"\n");
1380: fprintf(ficrespow,"\n");fflush(ficrespow);
1381: if(*iter <=3){
1.157 brouard 1382: tml = *localtime(&rcurr_time);
1383: strcpy(strcurr,asctime(&tml));
1384: rforecast_time=rcurr_time;
1.126 brouard 1385: itmp = strlen(strcurr);
1386: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1387: strcurr[itmp-1]='\0';
1.162 brouard 1388: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1389: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1390: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1391: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1392: forecast_time = *localtime(&rforecast_time);
1393: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1394: itmp = strlen(strfor);
1395: if(strfor[itmp-1]=='\n')
1396: strfor[itmp-1]='\0';
1.157 brouard 1397: 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);
1398: 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 1399: }
1400: }
1401: for (i=1;i<=n;i++) {
1402: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1403: fptt=(*fret);
1404: #ifdef DEBUG
1.164 brouard 1405: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1406: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1407: #endif
1408: printf("%d",i);fflush(stdout);
1409: fprintf(ficlog,"%d",i);fflush(ficlog);
1410: linmin(p,xit,n,fret,func);
1411: if (fabs(fptt-(*fret)) > del) {
1412: del=fabs(fptt-(*fret));
1413: ibig=i;
1414: }
1415: #ifdef DEBUG
1416: printf("%d %.12e",i,(*fret));
1417: fprintf(ficlog,"%d %.12e",i,(*fret));
1418: for (j=1;j<=n;j++) {
1419: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1420: printf(" x(%d)=%.12e",j,xit[j]);
1421: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1422: }
1423: for(j=1;j<=n;j++) {
1.162 brouard 1424: printf(" p(%d)=%.12e",j,p[j]);
1425: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1426: }
1427: printf("\n");
1428: fprintf(ficlog,"\n");
1429: #endif
1.162 brouard 1430: } /* end i */
1.126 brouard 1431: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1432: #ifdef DEBUG
1433: int k[2],l;
1434: k[0]=1;
1435: k[1]=-1;
1436: printf("Max: %.12e",(*func)(p));
1437: fprintf(ficlog,"Max: %.12e",(*func)(p));
1438: for (j=1;j<=n;j++) {
1439: printf(" %.12e",p[j]);
1440: fprintf(ficlog," %.12e",p[j]);
1441: }
1442: printf("\n");
1443: fprintf(ficlog,"\n");
1444: for(l=0;l<=1;l++) {
1445: for (j=1;j<=n;j++) {
1446: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1447: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1448: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1449: }
1450: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1451: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1452: }
1453: #endif
1454:
1455:
1456: free_vector(xit,1,n);
1457: free_vector(xits,1,n);
1458: free_vector(ptt,1,n);
1459: free_vector(pt,1,n);
1460: return;
1461: }
1462: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1463: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1464: ptt[j]=2.0*p[j]-pt[j];
1465: xit[j]=p[j]-pt[j];
1466: pt[j]=p[j];
1467: }
1468: fptt=(*func)(ptt);
1.161 brouard 1469: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1470: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1471: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1472: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1473: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1474: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1475: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1476: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1477: /* or best gain on one ancient line 'del' with total */
1478: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1479: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1480:
1.161 brouard 1481: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1482: t= t- del*SQR(fp-fptt);
1483: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1484: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1485: #ifdef DEBUG
1486: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1487: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1488: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1489: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1490: 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);
1491: 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);
1492: #endif
1493: if (t < 0.0) { /* Then we use it for last direction */
1494: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1495: for (j=1;j<=n;j++) {
1.161 brouard 1496: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1497: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1498: }
1.161 brouard 1499: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1500: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1501:
1.126 brouard 1502: #ifdef DEBUG
1.164 brouard 1503: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1504: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1505: for(j=1;j<=n;j++){
1506: printf(" %.12e",xit[j]);
1507: fprintf(ficlog," %.12e",xit[j]);
1508: }
1509: printf("\n");
1510: fprintf(ficlog,"\n");
1511: #endif
1.162 brouard 1512: } /* end of t negative */
1513: } /* end if (fptt < fp) */
1.126 brouard 1514: }
1515: }
1516:
1517: /**** Prevalence limit (stable or period prevalence) ****************/
1518:
1519: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1520: {
1521: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1522: matrix by transitions matrix until convergence is reached */
1523:
1524: int i, ii,j,k;
1525: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1526: /* double **matprod2(); */ /* test */
1.131 brouard 1527: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1528: double **newm;
1529: double agefin, delaymax=50 ; /* Max number of years to converge */
1530:
1531: for (ii=1;ii<=nlstate+ndeath;ii++)
1532: for (j=1;j<=nlstate+ndeath;j++){
1533: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1534: }
1535:
1536: cov[1]=1.;
1537:
1538: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1539: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1540: newm=savm;
1541: /* Covariates have to be included here again */
1.138 brouard 1542: cov[2]=agefin;
1543:
1544: for (k=1; k<=cptcovn;k++) {
1545: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1546: /*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 1547: }
1.145 brouard 1548: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1549: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1550: /* 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 1551:
1552: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1553: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1554: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1555: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1556: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1557: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1558:
1.126 brouard 1559: savm=oldm;
1560: oldm=newm;
1561: maxmax=0.;
1562: for(j=1;j<=nlstate;j++){
1563: min=1.;
1564: max=0.;
1565: for(i=1; i<=nlstate; i++) {
1566: sumnew=0;
1567: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1568: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1569: /*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 1570: max=FMAX(max,prlim[i][j]);
1571: min=FMIN(min,prlim[i][j]);
1572: }
1573: maxmin=max-min;
1574: maxmax=FMAX(maxmax,maxmin);
1575: }
1576: if(maxmax < ftolpl){
1577: return prlim;
1578: }
1579: }
1580: }
1581:
1582: /*************** transition probabilities ***************/
1583:
1584: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1585: {
1.138 brouard 1586: /* According to parameters values stored in x and the covariate's values stored in cov,
1587: computes the probability to be observed in state j being in state i by appying the
1588: model to the ncovmodel covariates (including constant and age).
1589: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1590: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1591: ncth covariate in the global vector x is given by the formula:
1592: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1593: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1594: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1595: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1596: Outputs ps[i][j] the probability to be observed in j being in j according to
1597: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1598: */
1599: double s1, lnpijopii;
1.126 brouard 1600: /*double t34;*/
1.164 brouard 1601: int i,j, nc, ii, jj;
1.126 brouard 1602:
1603: for(i=1; i<= nlstate; i++){
1604: for(j=1; j<i;j++){
1.138 brouard 1605: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1606: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1607: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1608: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1609: }
1.138 brouard 1610: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1611: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1612: }
1613: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1614: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1615: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1616: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1617: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1618: }
1.138 brouard 1619: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1620: }
1621: }
1622:
1623: for(i=1; i<= nlstate; i++){
1624: s1=0;
1.131 brouard 1625: for(j=1; j<i; j++){
1.138 brouard 1626: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1627: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1628: }
1629: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1630: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1631: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1632: }
1.138 brouard 1633: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1634: ps[i][i]=1./(s1+1.);
1.138 brouard 1635: /* Computing other pijs */
1.126 brouard 1636: for(j=1; j<i; j++)
1637: ps[i][j]= exp(ps[i][j])*ps[i][i];
1638: for(j=i+1; j<=nlstate+ndeath; j++)
1639: ps[i][j]= exp(ps[i][j])*ps[i][i];
1640: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1641: } /* end i */
1642:
1643: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1644: for(jj=1; jj<= nlstate+ndeath; jj++){
1645: ps[ii][jj]=0;
1646: ps[ii][ii]=1;
1647: }
1648: }
1649:
1.145 brouard 1650:
1651: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1652: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1653: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1654: /* } */
1655: /* printf("\n "); */
1656: /* } */
1657: /* printf("\n ");printf("%lf ",cov[2]);*/
1658: /*
1.126 brouard 1659: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1660: goto end;*/
1661: return ps;
1662: }
1663:
1664: /**************** Product of 2 matrices ******************/
1665:
1.145 brouard 1666: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1667: {
1668: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1669: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1670: /* in, b, out are matrice of pointers which should have been initialized
1671: before: only the contents of out is modified. The function returns
1672: a pointer to pointers identical to out */
1.145 brouard 1673: int i, j, k;
1.126 brouard 1674: for(i=nrl; i<= nrh; i++)
1.145 brouard 1675: for(k=ncolol; k<=ncoloh; k++){
1676: out[i][k]=0.;
1677: for(j=ncl; j<=nch; j++)
1678: out[i][k] +=in[i][j]*b[j][k];
1679: }
1.126 brouard 1680: return out;
1681: }
1682:
1683:
1684: /************* Higher Matrix Product ***************/
1685:
1686: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1687: {
1688: /* Computes the transition matrix starting at age 'age' over
1689: 'nhstepm*hstepm*stepm' months (i.e. until
1690: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1691: nhstepm*hstepm matrices.
1692: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1693: (typically every 2 years instead of every month which is too big
1694: for the memory).
1695: Model is determined by parameters x and covariates have to be
1696: included manually here.
1697:
1698: */
1699:
1700: int i, j, d, h, k;
1.131 brouard 1701: double **out, cov[NCOVMAX+1];
1.126 brouard 1702: double **newm;
1703:
1704: /* Hstepm could be zero and should return the unit matrix */
1705: for (i=1;i<=nlstate+ndeath;i++)
1706: for (j=1;j<=nlstate+ndeath;j++){
1707: oldm[i][j]=(i==j ? 1.0 : 0.0);
1708: po[i][j][0]=(i==j ? 1.0 : 0.0);
1709: }
1710: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1711: for(h=1; h <=nhstepm; h++){
1712: for(d=1; d <=hstepm; d++){
1713: newm=savm;
1714: /* Covariates have to be included here again */
1715: cov[1]=1.;
1716: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1717: for (k=1; k<=cptcovn;k++)
1718: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1719: for (k=1; k<=cptcovage;k++)
1720: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1721: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1722: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1723:
1724:
1725: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1726: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1727: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1728: pmij(pmmij,cov,ncovmodel,x,nlstate));
1729: savm=oldm;
1730: oldm=newm;
1731: }
1732: for(i=1; i<=nlstate+ndeath; i++)
1733: for(j=1;j<=nlstate+ndeath;j++) {
1734: po[i][j][h]=newm[i][j];
1.128 brouard 1735: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1736: }
1.128 brouard 1737: /*printf("h=%d ",h);*/
1.126 brouard 1738: } /* end h */
1.128 brouard 1739: /* printf("\n H=%d \n",h); */
1.126 brouard 1740: return po;
1741: }
1742:
1.162 brouard 1743: #ifdef NLOPT
1744: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1745: double fret;
1746: double *xt;
1747: int j;
1748: myfunc_data *d2 = (myfunc_data *) pd;
1749: /* xt = (p1-1); */
1750: xt=vector(1,n);
1751: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1752:
1753: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1754: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1755: printf("Function = %.12lf ",fret);
1756: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1757: printf("\n");
1758: free_vector(xt,1,n);
1759: return fret;
1760: }
1761: #endif
1.126 brouard 1762:
1763: /*************** log-likelihood *************/
1764: double func( double *x)
1765: {
1766: int i, ii, j, k, mi, d, kk;
1.131 brouard 1767: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1768: double **out;
1769: double sw; /* Sum of weights */
1770: double lli; /* Individual log likelihood */
1771: int s1, s2;
1772: double bbh, survp;
1773: long ipmx;
1774: /*extern weight */
1775: /* We are differentiating ll according to initial status */
1776: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1777: /*for(i=1;i<imx;i++)
1778: printf(" %d\n",s[4][i]);
1779: */
1.162 brouard 1780:
1781: ++countcallfunc;
1782:
1.126 brouard 1783: cov[1]=1.;
1784:
1785: for(k=1; k<=nlstate; k++) ll[k]=0.;
1786:
1787: if(mle==1){
1788: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1789: /* Computes the values of the ncovmodel covariates of the model
1790: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1791: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1792: to be observed in j being in i according to the model.
1793: */
1.145 brouard 1794: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1795: cov[2+k]=covar[Tvar[k]][i];
1796: }
1.137 brouard 1797: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1798: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1799: has been calculated etc */
1.126 brouard 1800: for(mi=1; mi<= wav[i]-1; mi++){
1801: for (ii=1;ii<=nlstate+ndeath;ii++)
1802: for (j=1;j<=nlstate+ndeath;j++){
1803: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1804: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1805: }
1806: for(d=0; d<dh[mi][i]; d++){
1807: newm=savm;
1808: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1809: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1810: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1811: }
1812: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1813: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1814: savm=oldm;
1815: oldm=newm;
1816: } /* end mult */
1817:
1818: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1819: /* But now since version 0.9 we anticipate for bias at large stepm.
1820: * If stepm is larger than one month (smallest stepm) and if the exact delay
1821: * (in months) between two waves is not a multiple of stepm, we rounded to
1822: * the nearest (and in case of equal distance, to the lowest) interval but now
1823: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1824: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1825: * probability in order to take into account the bias as a fraction of the way
1826: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1827: * -stepm/2 to stepm/2 .
1828: * For stepm=1 the results are the same as for previous versions of Imach.
1829: * For stepm > 1 the results are less biased than in previous versions.
1830: */
1831: s1=s[mw[mi][i]][i];
1832: s2=s[mw[mi+1][i]][i];
1833: bbh=(double)bh[mi][i]/(double)stepm;
1834: /* bias bh is positive if real duration
1835: * is higher than the multiple of stepm and negative otherwise.
1836: */
1837: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1838: if( s2 > nlstate){
1839: /* i.e. if s2 is a death state and if the date of death is known
1840: then the contribution to the likelihood is the probability to
1841: die between last step unit time and current step unit time,
1842: which is also equal to probability to die before dh
1843: minus probability to die before dh-stepm .
1844: In version up to 0.92 likelihood was computed
1845: as if date of death was unknown. Death was treated as any other
1846: health state: the date of the interview describes the actual state
1847: and not the date of a change in health state. The former idea was
1848: to consider that at each interview the state was recorded
1849: (healthy, disable or death) and IMaCh was corrected; but when we
1850: introduced the exact date of death then we should have modified
1851: the contribution of an exact death to the likelihood. This new
1852: contribution is smaller and very dependent of the step unit
1853: stepm. It is no more the probability to die between last interview
1854: and month of death but the probability to survive from last
1855: interview up to one month before death multiplied by the
1856: probability to die within a month. Thanks to Chris
1857: Jackson for correcting this bug. Former versions increased
1858: mortality artificially. The bad side is that we add another loop
1859: which slows down the processing. The difference can be up to 10%
1860: lower mortality.
1861: */
1862: lli=log(out[s1][s2] - savm[s1][s2]);
1863:
1864:
1865: } else if (s2==-2) {
1866: for (j=1,survp=0. ; j<=nlstate; j++)
1867: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1868: /*survp += out[s1][j]; */
1869: lli= log(survp);
1870: }
1871:
1872: else if (s2==-4) {
1873: for (j=3,survp=0. ; j<=nlstate; j++)
1874: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1875: lli= log(survp);
1876: }
1877:
1878: else if (s2==-5) {
1879: for (j=1,survp=0. ; j<=2; j++)
1880: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1881: lli= log(survp);
1882: }
1883:
1884: else{
1885: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1886: /* 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 */
1887: }
1888: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1889: /*if(lli ==000.0)*/
1890: /*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); */
1891: ipmx +=1;
1892: sw += weight[i];
1893: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1894: } /* end of wave */
1895: } /* end of individual */
1896: } else if(mle==2){
1897: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1898: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1899: for(mi=1; mi<= wav[i]-1; mi++){
1900: for (ii=1;ii<=nlstate+ndeath;ii++)
1901: for (j=1;j<=nlstate+ndeath;j++){
1902: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1903: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1904: }
1905: for(d=0; d<=dh[mi][i]; d++){
1906: newm=savm;
1907: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1908: for (kk=1; kk<=cptcovage;kk++) {
1909: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1910: }
1911: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1912: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1913: savm=oldm;
1914: oldm=newm;
1915: } /* end mult */
1916:
1917: s1=s[mw[mi][i]][i];
1918: s2=s[mw[mi+1][i]][i];
1919: bbh=(double)bh[mi][i]/(double)stepm;
1920: 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 */
1921: ipmx +=1;
1922: sw += weight[i];
1923: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1924: } /* end of wave */
1925: } /* end of individual */
1926: } else if(mle==3){ /* exponential inter-extrapolation */
1927: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1928: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1929: for(mi=1; mi<= wav[i]-1; mi++){
1930: for (ii=1;ii<=nlstate+ndeath;ii++)
1931: for (j=1;j<=nlstate+ndeath;j++){
1932: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1933: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1934: }
1935: for(d=0; d<dh[mi][i]; d++){
1936: newm=savm;
1937: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1938: for (kk=1; kk<=cptcovage;kk++) {
1939: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1940: }
1941: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1942: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1943: savm=oldm;
1944: oldm=newm;
1945: } /* end mult */
1946:
1947: s1=s[mw[mi][i]][i];
1948: s2=s[mw[mi+1][i]][i];
1949: bbh=(double)bh[mi][i]/(double)stepm;
1950: 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 */
1951: ipmx +=1;
1952: sw += weight[i];
1953: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1954: } /* end of wave */
1955: } /* end of individual */
1956: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1957: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1958: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1959: for(mi=1; mi<= wav[i]-1; mi++){
1960: for (ii=1;ii<=nlstate+ndeath;ii++)
1961: for (j=1;j<=nlstate+ndeath;j++){
1962: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1963: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1964: }
1965: for(d=0; d<dh[mi][i]; d++){
1966: newm=savm;
1967: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1968: for (kk=1; kk<=cptcovage;kk++) {
1969: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1970: }
1971:
1972: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1973: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1974: savm=oldm;
1975: oldm=newm;
1976: } /* end mult */
1977:
1978: s1=s[mw[mi][i]][i];
1979: s2=s[mw[mi+1][i]][i];
1980: if( s2 > nlstate){
1981: lli=log(out[s1][s2] - savm[s1][s2]);
1982: }else{
1983: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1984: }
1985: ipmx +=1;
1986: sw += weight[i];
1987: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1988: /* 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]); */
1989: } /* end of wave */
1990: } /* end of individual */
1991: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1992: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1993: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1994: for(mi=1; mi<= wav[i]-1; mi++){
1995: for (ii=1;ii<=nlstate+ndeath;ii++)
1996: for (j=1;j<=nlstate+ndeath;j++){
1997: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1998: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1999: }
2000: for(d=0; d<dh[mi][i]; d++){
2001: newm=savm;
2002: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2003: for (kk=1; kk<=cptcovage;kk++) {
2004: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2005: }
2006:
2007: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2008: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2009: savm=oldm;
2010: oldm=newm;
2011: } /* end mult */
2012:
2013: s1=s[mw[mi][i]][i];
2014: s2=s[mw[mi+1][i]][i];
2015: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2016: ipmx +=1;
2017: sw += weight[i];
2018: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2019: /*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]);*/
2020: } /* end of wave */
2021: } /* end of individual */
2022: } /* End of if */
2023: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2024: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2025: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2026: return -l;
2027: }
2028:
2029: /*************** log-likelihood *************/
2030: double funcone( double *x)
2031: {
2032: /* Same as likeli but slower because of a lot of printf and if */
2033: int i, ii, j, k, mi, d, kk;
1.131 brouard 2034: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2035: double **out;
2036: double lli; /* Individual log likelihood */
2037: double llt;
2038: int s1, s2;
2039: double bbh, survp;
2040: /*extern weight */
2041: /* We are differentiating ll according to initial status */
2042: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2043: /*for(i=1;i<imx;i++)
2044: printf(" %d\n",s[4][i]);
2045: */
2046: cov[1]=1.;
2047:
2048: for(k=1; k<=nlstate; k++) ll[k]=0.;
2049:
2050: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2051: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2052: for(mi=1; mi<= wav[i]-1; mi++){
2053: for (ii=1;ii<=nlstate+ndeath;ii++)
2054: for (j=1;j<=nlstate+ndeath;j++){
2055: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2056: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2057: }
2058: for(d=0; d<dh[mi][i]; d++){
2059: newm=savm;
2060: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2061: for (kk=1; kk<=cptcovage;kk++) {
2062: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2063: }
1.145 brouard 2064: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2065: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2066: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2067: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2068: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2069: savm=oldm;
2070: oldm=newm;
2071: } /* end mult */
2072:
2073: s1=s[mw[mi][i]][i];
2074: s2=s[mw[mi+1][i]][i];
2075: bbh=(double)bh[mi][i]/(double)stepm;
2076: /* bias is positive if real duration
2077: * is higher than the multiple of stepm and negative otherwise.
2078: */
2079: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2080: lli=log(out[s1][s2] - savm[s1][s2]);
2081: } else if (s2==-2) {
2082: for (j=1,survp=0. ; j<=nlstate; j++)
2083: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2084: lli= log(survp);
2085: }else if (mle==1){
2086: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2087: } else if(mle==2){
2088: 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 */
2089: } else if(mle==3){ /* exponential inter-extrapolation */
2090: 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 */
2091: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2092: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2093: } else{ /* mle=0 back to 1 */
2094: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2095: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2096: } /* End of if */
2097: ipmx +=1;
2098: sw += weight[i];
2099: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2100: /*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 2101: if(globpr){
1.141 brouard 2102: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2103: %11.6f %11.6f %11.6f ", \
2104: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2105: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2106: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2107: llt +=ll[k]*gipmx/gsw;
2108: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2109: }
2110: fprintf(ficresilk," %10.6f\n", -llt);
2111: }
2112: } /* end of wave */
2113: } /* end of individual */
2114: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2115: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2116: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2117: if(globpr==0){ /* First time we count the contributions and weights */
2118: gipmx=ipmx;
2119: gsw=sw;
2120: }
2121: return -l;
2122: }
2123:
2124:
2125: /*************** function likelione ***********/
2126: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2127: {
2128: /* This routine should help understanding what is done with
2129: the selection of individuals/waves and
2130: to check the exact contribution to the likelihood.
2131: Plotting could be done.
2132: */
2133: int k;
2134:
2135: if(*globpri !=0){ /* Just counts and sums, no printings */
2136: strcpy(fileresilk,"ilk");
2137: strcat(fileresilk,fileres);
2138: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2139: printf("Problem with resultfile: %s\n", fileresilk);
2140: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2141: }
2142: 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");
2143: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2144: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2145: for(k=1; k<=nlstate; k++)
2146: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2147: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2148: }
2149:
2150: *fretone=(*funcone)(p);
2151: if(*globpri !=0){
2152: fclose(ficresilk);
2153: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2154: fflush(fichtm);
2155: }
2156: return;
2157: }
2158:
2159:
2160: /*********** Maximum Likelihood Estimation ***************/
2161:
2162: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2163: {
1.165 brouard 2164: int i,j, iter=0;
1.126 brouard 2165: double **xi;
2166: double fret;
2167: double fretone; /* Only one call to likelihood */
2168: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2169:
2170: #ifdef NLOPT
2171: int creturn;
2172: nlopt_opt opt;
2173: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2174: double *lb;
2175: double minf; /* the minimum objective value, upon return */
2176: double * p1; /* Shifted parameters from 0 instead of 1 */
2177: myfunc_data dinst, *d = &dinst;
2178: #endif
2179:
2180:
1.126 brouard 2181: xi=matrix(1,npar,1,npar);
2182: for (i=1;i<=npar;i++)
2183: for (j=1;j<=npar;j++)
2184: xi[i][j]=(i==j ? 1.0 : 0.0);
2185: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2186: strcpy(filerespow,"pow");
2187: strcat(filerespow,fileres);
2188: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2189: printf("Problem with resultfile: %s\n", filerespow);
2190: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2191: }
2192: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2193: for (i=1;i<=nlstate;i++)
2194: for(j=1;j<=nlstate+ndeath;j++)
2195: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2196: fprintf(ficrespow,"\n");
1.162 brouard 2197: #ifdef POWELL
1.126 brouard 2198: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2199: #endif
1.126 brouard 2200:
1.162 brouard 2201: #ifdef NLOPT
2202: #ifdef NEWUOA
2203: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2204: #else
2205: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2206: #endif
2207: lb=vector(0,npar-1);
2208: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2209: nlopt_set_lower_bounds(opt, lb);
2210: nlopt_set_initial_step1(opt, 0.1);
2211:
2212: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2213: d->function = func;
2214: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2215: nlopt_set_min_objective(opt, myfunc, d);
2216: nlopt_set_xtol_rel(opt, ftol);
2217: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2218: printf("nlopt failed! %d\n",creturn);
2219: }
2220: else {
2221: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2222: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2223: iter=1; /* not equal */
2224: }
2225: nlopt_destroy(opt);
2226: #endif
1.126 brouard 2227: free_matrix(xi,1,npar,1,npar);
2228: fclose(ficrespow);
1.162 brouard 2229: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2230: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2231: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2232:
2233: }
2234:
2235: /**** Computes Hessian and covariance matrix ***/
2236: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2237: {
2238: double **a,**y,*x,pd;
2239: double **hess;
1.164 brouard 2240: int i, j;
1.126 brouard 2241: int *indx;
2242:
2243: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2244: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2245: void lubksb(double **a, int npar, int *indx, double b[]) ;
2246: void ludcmp(double **a, int npar, int *indx, double *d) ;
2247: double gompertz(double p[]);
2248: hess=matrix(1,npar,1,npar);
2249:
2250: printf("\nCalculation of the hessian matrix. Wait...\n");
2251: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2252: for (i=1;i<=npar;i++){
2253: printf("%d",i);fflush(stdout);
2254: fprintf(ficlog,"%d",i);fflush(ficlog);
2255:
2256: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2257:
2258: /* printf(" %f ",p[i]);
2259: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2260: }
2261:
2262: for (i=1;i<=npar;i++) {
2263: for (j=1;j<=npar;j++) {
2264: if (j>i) {
2265: printf(".%d%d",i,j);fflush(stdout);
2266: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2267: hess[i][j]=hessij(p,delti,i,j,func,npar);
2268:
2269: hess[j][i]=hess[i][j];
2270: /*printf(" %lf ",hess[i][j]);*/
2271: }
2272: }
2273: }
2274: printf("\n");
2275: fprintf(ficlog,"\n");
2276:
2277: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2278: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2279:
2280: a=matrix(1,npar,1,npar);
2281: y=matrix(1,npar,1,npar);
2282: x=vector(1,npar);
2283: indx=ivector(1,npar);
2284: for (i=1;i<=npar;i++)
2285: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2286: ludcmp(a,npar,indx,&pd);
2287:
2288: for (j=1;j<=npar;j++) {
2289: for (i=1;i<=npar;i++) x[i]=0;
2290: x[j]=1;
2291: lubksb(a,npar,indx,x);
2292: for (i=1;i<=npar;i++){
2293: matcov[i][j]=x[i];
2294: }
2295: }
2296:
2297: printf("\n#Hessian matrix#\n");
2298: fprintf(ficlog,"\n#Hessian matrix#\n");
2299: for (i=1;i<=npar;i++) {
2300: for (j=1;j<=npar;j++) {
2301: printf("%.3e ",hess[i][j]);
2302: fprintf(ficlog,"%.3e ",hess[i][j]);
2303: }
2304: printf("\n");
2305: fprintf(ficlog,"\n");
2306: }
2307:
2308: /* Recompute Inverse */
2309: for (i=1;i<=npar;i++)
2310: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2311: ludcmp(a,npar,indx,&pd);
2312:
2313: /* printf("\n#Hessian matrix recomputed#\n");
2314:
2315: for (j=1;j<=npar;j++) {
2316: for (i=1;i<=npar;i++) x[i]=0;
2317: x[j]=1;
2318: lubksb(a,npar,indx,x);
2319: for (i=1;i<=npar;i++){
2320: y[i][j]=x[i];
2321: printf("%.3e ",y[i][j]);
2322: fprintf(ficlog,"%.3e ",y[i][j]);
2323: }
2324: printf("\n");
2325: fprintf(ficlog,"\n");
2326: }
2327: */
2328:
2329: free_matrix(a,1,npar,1,npar);
2330: free_matrix(y,1,npar,1,npar);
2331: free_vector(x,1,npar);
2332: free_ivector(indx,1,npar);
2333: free_matrix(hess,1,npar,1,npar);
2334:
2335:
2336: }
2337:
2338: /*************** hessian matrix ****************/
2339: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2340: {
2341: int i;
2342: int l=1, lmax=20;
2343: double k1,k2;
1.132 brouard 2344: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2345: double res;
2346: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2347: double fx;
2348: int k=0,kmax=10;
2349: double l1;
2350:
2351: fx=func(x);
2352: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2353: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2354: l1=pow(10,l);
2355: delts=delt;
2356: for(k=1 ; k <kmax; k=k+1){
2357: delt = delta*(l1*k);
2358: p2[theta]=x[theta] +delt;
1.145 brouard 2359: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2360: p2[theta]=x[theta]-delt;
2361: k2=func(p2)-fx;
2362: /*res= (k1-2.0*fx+k2)/delt/delt; */
2363: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2364:
1.132 brouard 2365: #ifdef DEBUGHESS
1.126 brouard 2366: 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);
2367: 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);
2368: #endif
2369: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2370: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2371: k=kmax;
2372: }
2373: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2374: k=kmax; l=lmax*10;
1.126 brouard 2375: }
2376: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2377: delts=delt;
2378: }
2379: }
2380: }
2381: delti[theta]=delts;
2382: return res;
2383:
2384: }
2385:
2386: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2387: {
2388: int i;
1.164 brouard 2389: int l=1, lmax=20;
1.126 brouard 2390: double k1,k2,k3,k4,res,fx;
1.132 brouard 2391: double p2[MAXPARM+1];
1.126 brouard 2392: int k;
2393:
2394: fx=func(x);
2395: for (k=1; k<=2; k++) {
2396: for (i=1;i<=npar;i++) p2[i]=x[i];
2397: p2[thetai]=x[thetai]+delti[thetai]/k;
2398: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2399: k1=func(p2)-fx;
2400:
2401: p2[thetai]=x[thetai]+delti[thetai]/k;
2402: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2403: k2=func(p2)-fx;
2404:
2405: p2[thetai]=x[thetai]-delti[thetai]/k;
2406: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2407: k3=func(p2)-fx;
2408:
2409: p2[thetai]=x[thetai]-delti[thetai]/k;
2410: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2411: k4=func(p2)-fx;
2412: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2413: #ifdef DEBUG
2414: 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);
2415: 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);
2416: #endif
2417: }
2418: return res;
2419: }
2420:
2421: /************** Inverse of matrix **************/
2422: void ludcmp(double **a, int n, int *indx, double *d)
2423: {
2424: int i,imax,j,k;
2425: double big,dum,sum,temp;
2426: double *vv;
2427:
2428: vv=vector(1,n);
2429: *d=1.0;
2430: for (i=1;i<=n;i++) {
2431: big=0.0;
2432: for (j=1;j<=n;j++)
2433: if ((temp=fabs(a[i][j])) > big) big=temp;
2434: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2435: vv[i]=1.0/big;
2436: }
2437: for (j=1;j<=n;j++) {
2438: for (i=1;i<j;i++) {
2439: sum=a[i][j];
2440: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2441: a[i][j]=sum;
2442: }
2443: big=0.0;
2444: for (i=j;i<=n;i++) {
2445: sum=a[i][j];
2446: for (k=1;k<j;k++)
2447: sum -= a[i][k]*a[k][j];
2448: a[i][j]=sum;
2449: if ( (dum=vv[i]*fabs(sum)) >= big) {
2450: big=dum;
2451: imax=i;
2452: }
2453: }
2454: if (j != imax) {
2455: for (k=1;k<=n;k++) {
2456: dum=a[imax][k];
2457: a[imax][k]=a[j][k];
2458: a[j][k]=dum;
2459: }
2460: *d = -(*d);
2461: vv[imax]=vv[j];
2462: }
2463: indx[j]=imax;
2464: if (a[j][j] == 0.0) a[j][j]=TINY;
2465: if (j != n) {
2466: dum=1.0/(a[j][j]);
2467: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2468: }
2469: }
2470: free_vector(vv,1,n); /* Doesn't work */
2471: ;
2472: }
2473:
2474: void lubksb(double **a, int n, int *indx, double b[])
2475: {
2476: int i,ii=0,ip,j;
2477: double sum;
2478:
2479: for (i=1;i<=n;i++) {
2480: ip=indx[i];
2481: sum=b[ip];
2482: b[ip]=b[i];
2483: if (ii)
2484: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2485: else if (sum) ii=i;
2486: b[i]=sum;
2487: }
2488: for (i=n;i>=1;i--) {
2489: sum=b[i];
2490: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2491: b[i]=sum/a[i][i];
2492: }
2493: }
2494:
2495: void pstamp(FILE *fichier)
2496: {
2497: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2498: }
2499:
2500: /************ Frequencies ********************/
2501: 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[])
2502: { /* Some frequencies */
2503:
1.164 brouard 2504: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2505: int first;
2506: double ***freq; /* Frequencies */
2507: double *pp, **prop;
2508: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2509: char fileresp[FILENAMELENGTH];
2510:
2511: pp=vector(1,nlstate);
2512: prop=matrix(1,nlstate,iagemin,iagemax+3);
2513: strcpy(fileresp,"p");
2514: strcat(fileresp,fileres);
2515: if((ficresp=fopen(fileresp,"w"))==NULL) {
2516: printf("Problem with prevalence resultfile: %s\n", fileresp);
2517: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2518: exit(0);
2519: }
2520: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2521: j1=0;
2522:
2523: j=cptcoveff;
2524: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2525:
2526: first=1;
2527:
1.145 brouard 2528: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2529: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2530: /* j1++;
2531: */
2532: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2533: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2534: scanf("%d", i);*/
2535: for (i=-5; i<=nlstate+ndeath; i++)
2536: for (jk=-5; jk<=nlstate+ndeath; jk++)
2537: for(m=iagemin; m <= iagemax+3; m++)
2538: freq[i][jk][m]=0;
1.143 brouard 2539:
2540: for (i=1; i<=nlstate; i++)
2541: for(m=iagemin; m <= iagemax+3; m++)
2542: prop[i][m]=0;
1.126 brouard 2543:
2544: dateintsum=0;
2545: k2cpt=0;
2546: for (i=1; i<=imx; i++) {
2547: bool=1;
1.144 brouard 2548: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2549: for (z1=1; z1<=cptcoveff; z1++)
2550: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2551: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2552: bool=0;
1.145 brouard 2553: /* 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",
2554: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2555: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2556: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2557: }
1.126 brouard 2558: }
1.144 brouard 2559:
1.126 brouard 2560: if (bool==1){
2561: for(m=firstpass; m<=lastpass; m++){
2562: k2=anint[m][i]+(mint[m][i]/12.);
2563: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2564: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2565: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2566: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2567: if (m<lastpass) {
2568: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2569: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2570: }
2571:
2572: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2573: dateintsum=dateintsum+k2;
2574: k2cpt++;
2575: }
2576: /*}*/
2577: }
2578: }
1.145 brouard 2579: } /* end i */
1.126 brouard 2580:
2581: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2582: pstamp(ficresp);
2583: if (cptcovn>0) {
2584: fprintf(ficresp, "\n#********** Variable ");
2585: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2586: fprintf(ficresp, "**********\n#");
1.143 brouard 2587: fprintf(ficlog, "\n#********** Variable ");
2588: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2589: fprintf(ficlog, "**********\n#");
1.126 brouard 2590: }
2591: for(i=1; i<=nlstate;i++)
2592: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2593: fprintf(ficresp, "\n");
2594:
2595: for(i=iagemin; i <= iagemax+3; i++){
2596: if(i==iagemax+3){
2597: fprintf(ficlog,"Total");
2598: }else{
2599: if(first==1){
2600: first=0;
2601: printf("See log file for details...\n");
2602: }
2603: fprintf(ficlog,"Age %d", i);
2604: }
2605: for(jk=1; jk <=nlstate ; jk++){
2606: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2607: pp[jk] += freq[jk][m][i];
2608: }
2609: for(jk=1; jk <=nlstate ; jk++){
2610: for(m=-1, pos=0; m <=0 ; m++)
2611: pos += freq[jk][m][i];
2612: if(pp[jk]>=1.e-10){
2613: if(first==1){
1.132 brouard 2614: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2615: }
2616: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2617: }else{
2618: if(first==1)
2619: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2620: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2621: }
2622: }
2623:
2624: for(jk=1; jk <=nlstate ; jk++){
2625: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2626: pp[jk] += freq[jk][m][i];
2627: }
2628: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2629: pos += pp[jk];
2630: posprop += prop[jk][i];
2631: }
2632: for(jk=1; jk <=nlstate ; jk++){
2633: if(pos>=1.e-5){
2634: if(first==1)
2635: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2636: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2637: }else{
2638: if(first==1)
2639: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2640: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2641: }
2642: if( i <= iagemax){
2643: if(pos>=1.e-5){
2644: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2645: /*probs[i][jk][j1]= pp[jk]/pos;*/
2646: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2647: }
2648: else
2649: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2650: }
2651: }
2652:
2653: for(jk=-1; jk <=nlstate+ndeath; jk++)
2654: for(m=-1; m <=nlstate+ndeath; m++)
2655: if(freq[jk][m][i] !=0 ) {
2656: if(first==1)
2657: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2658: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2659: }
2660: if(i <= iagemax)
2661: fprintf(ficresp,"\n");
2662: if(first==1)
2663: printf("Others in log...\n");
2664: fprintf(ficlog,"\n");
2665: }
1.145 brouard 2666: /*}*/
1.126 brouard 2667: }
2668: dateintmean=dateintsum/k2cpt;
2669:
2670: fclose(ficresp);
2671: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2672: free_vector(pp,1,nlstate);
2673: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2674: /* End of Freq */
2675: }
2676:
2677: /************ Prevalence ********************/
2678: 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)
2679: {
2680: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2681: in each health status at the date of interview (if between dateprev1 and dateprev2).
2682: We still use firstpass and lastpass as another selection.
2683: */
2684:
1.164 brouard 2685: int i, m, jk, j1, bool, z1,j;
2686:
2687: double **prop;
2688: double posprop;
1.126 brouard 2689: double y2; /* in fractional years */
2690: int iagemin, iagemax;
1.145 brouard 2691: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2692:
2693: iagemin= (int) agemin;
2694: iagemax= (int) agemax;
2695: /*pp=vector(1,nlstate);*/
2696: prop=matrix(1,nlstate,iagemin,iagemax+3);
2697: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2698: j1=0;
2699:
1.145 brouard 2700: /*j=cptcoveff;*/
1.126 brouard 2701: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2702:
1.145 brouard 2703: first=1;
2704: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2705: /*for(i1=1; i1<=ncodemax[k1];i1++){
2706: j1++;*/
1.126 brouard 2707:
2708: for (i=1; i<=nlstate; i++)
2709: for(m=iagemin; m <= iagemax+3; m++)
2710: prop[i][m]=0.0;
2711:
2712: for (i=1; i<=imx; i++) { /* Each individual */
2713: bool=1;
2714: if (cptcovn>0) {
2715: for (z1=1; z1<=cptcoveff; z1++)
2716: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2717: bool=0;
2718: }
2719: if (bool==1) {
2720: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2721: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2722: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2723: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2724: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2725: 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);
2726: if (s[m][i]>0 && s[m][i]<=nlstate) {
2727: /*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]]);*/
2728: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2729: prop[s[m][i]][iagemax+3] += weight[i];
2730: }
2731: }
2732: } /* end selection of waves */
2733: }
2734: }
2735: for(i=iagemin; i <= iagemax+3; i++){
2736: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2737: posprop += prop[jk][i];
2738: }
1.145 brouard 2739:
1.126 brouard 2740: for(jk=1; jk <=nlstate ; jk++){
2741: if( i <= iagemax){
2742: if(posprop>=1.e-5){
2743: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2744: } else{
2745: if(first==1){
2746: first=0;
2747: 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]);
2748: }
2749: }
1.126 brouard 2750: }
2751: }/* end jk */
2752: }/* end i */
1.145 brouard 2753: /*} *//* end i1 */
2754: } /* end j1 */
1.126 brouard 2755:
2756: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2757: /*free_vector(pp,1,nlstate);*/
2758: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2759: } /* End of prevalence */
2760:
2761: /************* Waves Concatenation ***************/
2762:
2763: 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)
2764: {
2765: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2766: Death is a valid wave (if date is known).
2767: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2768: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2769: and mw[mi+1][i]. dh depends on stepm.
2770: */
2771:
2772: int i, mi, m;
2773: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2774: double sum=0., jmean=0.;*/
2775: int first;
2776: int j, k=0,jk, ju, jl;
2777: double sum=0.;
2778: first=0;
1.164 brouard 2779: jmin=100000;
1.126 brouard 2780: jmax=-1;
2781: jmean=0.;
2782: for(i=1; i<=imx; i++){
2783: mi=0;
2784: m=firstpass;
2785: while(s[m][i] <= nlstate){
2786: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2787: mw[++mi][i]=m;
2788: if(m >=lastpass)
2789: break;
2790: else
2791: m++;
2792: }/* end while */
2793: if (s[m][i] > nlstate){
2794: mi++; /* Death is another wave */
2795: /* if(mi==0) never been interviewed correctly before death */
2796: /* Only death is a correct wave */
2797: mw[mi][i]=m;
2798: }
2799:
2800: wav[i]=mi;
2801: if(mi==0){
2802: nbwarn++;
2803: if(first==0){
2804: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2805: first=1;
2806: }
2807: if(first==1){
2808: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2809: }
2810: } /* end mi==0 */
2811: } /* End individuals */
2812:
2813: for(i=1; i<=imx; i++){
2814: for(mi=1; mi<wav[i];mi++){
2815: if (stepm <=0)
2816: dh[mi][i]=1;
2817: else{
2818: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2819: if (agedc[i] < 2*AGESUP) {
2820: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2821: if(j==0) j=1; /* Survives at least one month after exam */
2822: else if(j<0){
2823: nberr++;
2824: 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]);
2825: j=1; /* Temporary Dangerous patch */
2826: 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);
2827: 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]);
2828: 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);
2829: }
2830: k=k+1;
2831: if (j >= jmax){
2832: jmax=j;
2833: ijmax=i;
2834: }
2835: if (j <= jmin){
2836: jmin=j;
2837: ijmin=i;
2838: }
2839: sum=sum+j;
2840: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2841: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2842: }
2843: }
2844: else{
2845: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2846: /* 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]); */
2847:
2848: k=k+1;
2849: if (j >= jmax) {
2850: jmax=j;
2851: ijmax=i;
2852: }
2853: else if (j <= jmin){
2854: jmin=j;
2855: ijmin=i;
2856: }
2857: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2858: /*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]);*/
2859: if(j<0){
2860: nberr++;
2861: 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]);
2862: 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]);
2863: }
2864: sum=sum+j;
2865: }
2866: jk= j/stepm;
2867: jl= j -jk*stepm;
2868: ju= j -(jk+1)*stepm;
2869: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2870: if(jl==0){
2871: dh[mi][i]=jk;
2872: bh[mi][i]=0;
2873: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2874: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2875: dh[mi][i]=jk+1;
2876: bh[mi][i]=ju;
2877: }
2878: }else{
2879: if(jl <= -ju){
2880: dh[mi][i]=jk;
2881: bh[mi][i]=jl; /* bias is positive if real duration
2882: * is higher than the multiple of stepm and negative otherwise.
2883: */
2884: }
2885: else{
2886: dh[mi][i]=jk+1;
2887: bh[mi][i]=ju;
2888: }
2889: if(dh[mi][i]==0){
2890: dh[mi][i]=1; /* At least one step */
2891: bh[mi][i]=ju; /* At least one step */
2892: /* 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);*/
2893: }
2894: } /* end if mle */
2895: }
2896: } /* end wave */
2897: }
2898: jmean=sum/k;
2899: 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 2900: 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 2901: }
2902:
2903: /*********** Tricode ****************************/
1.145 brouard 2904: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2905: {
1.144 brouard 2906: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2907: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2908: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2909: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2910: /* nbcode[Tvar[j]][1]=
1.144 brouard 2911: */
1.130 brouard 2912:
1.145 brouard 2913: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2914: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2915: int cptcode=0; /* Modality max of covariates j */
2916: int modmincovj=0; /* Modality min of covariates j */
2917:
2918:
1.126 brouard 2919: cptcoveff=0;
2920:
1.145 brouard 2921: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2922: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2923:
1.145 brouard 2924: /* Loop on covariates without age and products */
2925: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2926: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2927: modality of this covariate Vj*/
1.145 brouard 2928: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2929: * If product of Vn*Vm, still boolean *:
2930: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2931: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2932: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2933: modality of the nth covariate of individual i. */
1.145 brouard 2934: if (ij > modmaxcovj)
2935: modmaxcovj=ij;
2936: else if (ij < modmincovj)
2937: modmincovj=ij;
2938: if ((ij < -1) && (ij > NCOVMAX)){
2939: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2940: exit(1);
2941: }else
1.136 brouard 2942: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2943: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2944: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2945: /* getting the maximum value of the modality of the covariate
2946: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2947: female is 1, then modmaxcovj=1.*/
1.126 brouard 2948: }
1.145 brouard 2949: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2950: cptcode=modmaxcovj;
1.137 brouard 2951: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2952: /*for (i=0; i<=cptcode; i++) {*/
2953: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2954: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2955: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2956: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2957: }
2958: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2959: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2960: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2961:
1.136 brouard 2962: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2963: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2964: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2965: modmincovj=3; modmaxcovj = 7;
2966: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2967: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2968: variables V1_1 and V1_2.
2969: nbcode[Tvar[j]][ij]=k;
2970: nbcode[Tvar[j]][1]=0;
2971: nbcode[Tvar[j]][2]=1;
2972: nbcode[Tvar[j]][3]=2;
2973: */
2974: ij=1; /* ij is similar to i but can jumps over null modalities */
2975: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2976: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2977: /*recode from 0 */
1.131 brouard 2978: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2979: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2980: k is a modality. If we have model=V1+V1*sex
2981: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2982: ij++;
2983: }
2984: if (ij > ncodemax[j]) break;
1.137 brouard 2985: } /* end of loop on */
2986: } /* end of loop on modality */
2987: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2988:
1.145 brouard 2989: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2990:
1.145 brouard 2991: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2992: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2993: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2994: Ndum[ij]++;
2995: }
1.126 brouard 2996:
2997: ij=1;
1.145 brouard 2998: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2999: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3000: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3001: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3002: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3003: ij++;
1.145 brouard 3004: }else
3005: Tvaraff[ij]=0;
1.126 brouard 3006: }
1.131 brouard 3007: ij--;
1.144 brouard 3008: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3009:
1.126 brouard 3010: }
3011:
1.145 brouard 3012:
1.126 brouard 3013: /*********** Health Expectancies ****************/
3014:
1.127 brouard 3015: 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 3016:
3017: {
3018: /* Health expectancies, no variances */
1.164 brouard 3019: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3020: int nhstepma, nstepma; /* Decreasing with age */
3021: double age, agelim, hf;
3022: double ***p3mat;
3023: double eip;
3024:
3025: pstamp(ficreseij);
3026: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3027: fprintf(ficreseij,"# Age");
3028: for(i=1; i<=nlstate;i++){
3029: for(j=1; j<=nlstate;j++){
3030: fprintf(ficreseij," e%1d%1d ",i,j);
3031: }
3032: fprintf(ficreseij," e%1d. ",i);
3033: }
3034: fprintf(ficreseij,"\n");
3035:
3036:
3037: if(estepm < stepm){
3038: printf ("Problem %d lower than %d\n",estepm, stepm);
3039: }
3040: else hstepm=estepm;
3041: /* We compute the life expectancy from trapezoids spaced every estepm months
3042: * This is mainly to measure the difference between two models: for example
3043: * if stepm=24 months pijx are given only every 2 years and by summing them
3044: * we are calculating an estimate of the Life Expectancy assuming a linear
3045: * progression in between and thus overestimating or underestimating according
3046: * to the curvature of the survival function. If, for the same date, we
3047: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3048: * to compare the new estimate of Life expectancy with the same linear
3049: * hypothesis. A more precise result, taking into account a more precise
3050: * curvature will be obtained if estepm is as small as stepm. */
3051:
3052: /* For example we decided to compute the life expectancy with the smallest unit */
3053: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3054: nhstepm is the number of hstepm from age to agelim
3055: nstepm is the number of stepm from age to agelin.
3056: Look at hpijx to understand the reason of that which relies in memory size
3057: and note for a fixed period like estepm months */
3058: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3059: survival function given by stepm (the optimization length). Unfortunately it
3060: means that if the survival funtion is printed only each two years of age and if
3061: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3062: results. So we changed our mind and took the option of the best precision.
3063: */
3064: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3065:
3066: agelim=AGESUP;
3067: /* If stepm=6 months */
3068: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3069: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3070:
3071: /* nhstepm age range expressed in number of stepm */
3072: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3073: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3074: /* if (stepm >= YEARM) hstepm=1;*/
3075: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3076: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3077:
3078: for (age=bage; age<=fage; age ++){
3079: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3080: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3081: /* if (stepm >= YEARM) hstepm=1;*/
3082: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3083:
3084: /* If stepm=6 months */
3085: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3086: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3087:
3088: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3089:
3090: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3091:
3092: printf("%d|",(int)age);fflush(stdout);
3093: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3094:
3095: /* Computing expectancies */
3096: for(i=1; i<=nlstate;i++)
3097: for(j=1; j<=nlstate;j++)
3098: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3099: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3100:
3101: /* 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]);*/
3102:
3103: }
3104:
3105: fprintf(ficreseij,"%3.0f",age );
3106: for(i=1; i<=nlstate;i++){
3107: eip=0;
3108: for(j=1; j<=nlstate;j++){
3109: eip +=eij[i][j][(int)age];
3110: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3111: }
3112: fprintf(ficreseij,"%9.4f", eip );
3113: }
3114: fprintf(ficreseij,"\n");
3115:
3116: }
3117: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3118: printf("\n");
3119: fprintf(ficlog,"\n");
3120:
3121: }
3122:
1.127 brouard 3123: 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 3124:
3125: {
3126: /* Covariances of health expectancies eij and of total life expectancies according
3127: to initial status i, ei. .
3128: */
3129: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3130: int nhstepma, nstepma; /* Decreasing with age */
3131: double age, agelim, hf;
3132: double ***p3matp, ***p3matm, ***varhe;
3133: double **dnewm,**doldm;
3134: double *xp, *xm;
3135: double **gp, **gm;
3136: double ***gradg, ***trgradg;
3137: int theta;
3138:
3139: double eip, vip;
3140:
3141: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3142: xp=vector(1,npar);
3143: xm=vector(1,npar);
3144: dnewm=matrix(1,nlstate*nlstate,1,npar);
3145: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3146:
3147: pstamp(ficresstdeij);
3148: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3149: fprintf(ficresstdeij,"# Age");
3150: for(i=1; i<=nlstate;i++){
3151: for(j=1; j<=nlstate;j++)
3152: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3153: fprintf(ficresstdeij," e%1d. ",i);
3154: }
3155: fprintf(ficresstdeij,"\n");
3156:
3157: pstamp(ficrescveij);
3158: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3159: fprintf(ficrescveij,"# Age");
3160: for(i=1; i<=nlstate;i++)
3161: for(j=1; j<=nlstate;j++){
3162: cptj= (j-1)*nlstate+i;
3163: for(i2=1; i2<=nlstate;i2++)
3164: for(j2=1; j2<=nlstate;j2++){
3165: cptj2= (j2-1)*nlstate+i2;
3166: if(cptj2 <= cptj)
3167: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3168: }
3169: }
3170: fprintf(ficrescveij,"\n");
3171:
3172: if(estepm < stepm){
3173: printf ("Problem %d lower than %d\n",estepm, stepm);
3174: }
3175: else hstepm=estepm;
3176: /* We compute the life expectancy from trapezoids spaced every estepm months
3177: * This is mainly to measure the difference between two models: for example
3178: * if stepm=24 months pijx are given only every 2 years and by summing them
3179: * we are calculating an estimate of the Life Expectancy assuming a linear
3180: * progression in between and thus overestimating or underestimating according
3181: * to the curvature of the survival function. If, for the same date, we
3182: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3183: * to compare the new estimate of Life expectancy with the same linear
3184: * hypothesis. A more precise result, taking into account a more precise
3185: * curvature will be obtained if estepm is as small as stepm. */
3186:
3187: /* For example we decided to compute the life expectancy with the smallest unit */
3188: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3189: nhstepm is the number of hstepm from age to agelim
3190: nstepm is the number of stepm from age to agelin.
3191: Look at hpijx to understand the reason of that which relies in memory size
3192: and note for a fixed period like estepm months */
3193: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3194: survival function given by stepm (the optimization length). Unfortunately it
3195: means that if the survival funtion is printed only each two years of age and if
3196: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3197: results. So we changed our mind and took the option of the best precision.
3198: */
3199: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3200:
3201: /* If stepm=6 months */
3202: /* nhstepm age range expressed in number of stepm */
3203: agelim=AGESUP;
3204: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3205: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3206: /* if (stepm >= YEARM) hstepm=1;*/
3207: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3208:
3209: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3210: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3211: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3212: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3213: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3214: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3215:
3216: for (age=bage; age<=fage; age ++){
3217: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3218: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3219: /* if (stepm >= YEARM) hstepm=1;*/
3220: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3221:
3222: /* If stepm=6 months */
3223: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3224: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3225:
3226: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3227:
3228: /* Computing Variances of health expectancies */
3229: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3230: decrease memory allocation */
3231: for(theta=1; theta <=npar; theta++){
3232: for(i=1; i<=npar; i++){
3233: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3234: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3235: }
3236: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3237: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3238:
3239: for(j=1; j<= nlstate; j++){
3240: for(i=1; i<=nlstate; i++){
3241: for(h=0; h<=nhstepm-1; h++){
3242: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3243: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3244: }
3245: }
3246: }
3247:
3248: for(ij=1; ij<= nlstate*nlstate; ij++)
3249: for(h=0; h<=nhstepm-1; h++){
3250: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3251: }
3252: }/* End theta */
3253:
3254:
3255: for(h=0; h<=nhstepm-1; h++)
3256: for(j=1; j<=nlstate*nlstate;j++)
3257: for(theta=1; theta <=npar; theta++)
3258: trgradg[h][j][theta]=gradg[h][theta][j];
3259:
3260:
3261: for(ij=1;ij<=nlstate*nlstate;ij++)
3262: for(ji=1;ji<=nlstate*nlstate;ji++)
3263: varhe[ij][ji][(int)age] =0.;
3264:
3265: printf("%d|",(int)age);fflush(stdout);
3266: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3267: for(h=0;h<=nhstepm-1;h++){
3268: for(k=0;k<=nhstepm-1;k++){
3269: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3270: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3271: for(ij=1;ij<=nlstate*nlstate;ij++)
3272: for(ji=1;ji<=nlstate*nlstate;ji++)
3273: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3274: }
3275: }
3276:
3277: /* Computing expectancies */
3278: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3279: for(i=1; i<=nlstate;i++)
3280: for(j=1; j<=nlstate;j++)
3281: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3282: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3283:
3284: /* 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]);*/
3285:
3286: }
3287:
3288: fprintf(ficresstdeij,"%3.0f",age );
3289: for(i=1; i<=nlstate;i++){
3290: eip=0.;
3291: vip=0.;
3292: for(j=1; j<=nlstate;j++){
3293: eip += eij[i][j][(int)age];
3294: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3295: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3296: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3297: }
3298: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3299: }
3300: fprintf(ficresstdeij,"\n");
3301:
3302: fprintf(ficrescveij,"%3.0f",age );
3303: for(i=1; i<=nlstate;i++)
3304: for(j=1; j<=nlstate;j++){
3305: cptj= (j-1)*nlstate+i;
3306: for(i2=1; i2<=nlstate;i2++)
3307: for(j2=1; j2<=nlstate;j2++){
3308: cptj2= (j2-1)*nlstate+i2;
3309: if(cptj2 <= cptj)
3310: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3311: }
3312: }
3313: fprintf(ficrescveij,"\n");
3314:
3315: }
3316: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3317: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3318: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3319: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3320: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3321: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3322: printf("\n");
3323: fprintf(ficlog,"\n");
3324:
3325: free_vector(xm,1,npar);
3326: free_vector(xp,1,npar);
3327: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3328: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3329: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3330: }
3331:
3332: /************ Variance ******************/
3333: 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[])
3334: {
3335: /* Variance of health expectancies */
3336: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3337: /* double **newm;*/
3338: double **dnewm,**doldm;
3339: double **dnewmp,**doldmp;
3340: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3341: int k;
1.126 brouard 3342: double *xp;
3343: double **gp, **gm; /* for var eij */
3344: double ***gradg, ***trgradg; /*for var eij */
3345: double **gradgp, **trgradgp; /* for var p point j */
3346: double *gpp, *gmp; /* for var p point j */
3347: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3348: double ***p3mat;
3349: double age,agelim, hf;
3350: double ***mobaverage;
3351: int theta;
3352: char digit[4];
3353: char digitp[25];
3354:
3355: char fileresprobmorprev[FILENAMELENGTH];
3356:
3357: if(popbased==1){
3358: if(mobilav!=0)
3359: strcpy(digitp,"-populbased-mobilav-");
3360: else strcpy(digitp,"-populbased-nomobil-");
3361: }
3362: else
3363: strcpy(digitp,"-stablbased-");
3364:
3365: if (mobilav!=0) {
3366: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3367: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3368: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3369: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3370: }
3371: }
3372:
3373: strcpy(fileresprobmorprev,"prmorprev");
3374: sprintf(digit,"%-d",ij);
3375: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3376: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3377: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3378: strcat(fileresprobmorprev,fileres);
3379: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3380: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3381: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3382: }
3383: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3384:
3385: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3386: pstamp(ficresprobmorprev);
3387: 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);
3388: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3389: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3390: fprintf(ficresprobmorprev," p.%-d SE",j);
3391: for(i=1; i<=nlstate;i++)
3392: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3393: }
3394: fprintf(ficresprobmorprev,"\n");
3395: fprintf(ficgp,"\n# Routine varevsij");
3396: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3397: 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");
3398: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3399: /* } */
3400: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3401: pstamp(ficresvij);
3402: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3403: if(popbased==1)
1.128 brouard 3404: 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 3405: else
3406: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3407: fprintf(ficresvij,"# Age");
3408: for(i=1; i<=nlstate;i++)
3409: for(j=1; j<=nlstate;j++)
3410: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3411: fprintf(ficresvij,"\n");
3412:
3413: xp=vector(1,npar);
3414: dnewm=matrix(1,nlstate,1,npar);
3415: doldm=matrix(1,nlstate,1,nlstate);
3416: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3417: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3418:
3419: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3420: gpp=vector(nlstate+1,nlstate+ndeath);
3421: gmp=vector(nlstate+1,nlstate+ndeath);
3422: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3423:
3424: if(estepm < stepm){
3425: printf ("Problem %d lower than %d\n",estepm, stepm);
3426: }
3427: else hstepm=estepm;
3428: /* For example we decided to compute the life expectancy with the smallest unit */
3429: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3430: nhstepm is the number of hstepm from age to agelim
3431: nstepm is the number of stepm from age to agelin.
1.128 brouard 3432: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3433: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3434: survival function given by stepm (the optimization length). Unfortunately it
3435: means that if the survival funtion is printed every two years of age and if
3436: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3437: results. So we changed our mind and took the option of the best precision.
3438: */
3439: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3440: agelim = AGESUP;
3441: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3442: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3443: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3444: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3445: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3446: gp=matrix(0,nhstepm,1,nlstate);
3447: gm=matrix(0,nhstepm,1,nlstate);
3448:
3449:
3450: for(theta=1; theta <=npar; theta++){
3451: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3452: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3453: }
3454: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3455: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3456:
3457: if (popbased==1) {
3458: if(mobilav ==0){
3459: for(i=1; i<=nlstate;i++)
3460: prlim[i][i]=probs[(int)age][i][ij];
3461: }else{ /* mobilav */
3462: for(i=1; i<=nlstate;i++)
3463: prlim[i][i]=mobaverage[(int)age][i][ij];
3464: }
3465: }
3466:
3467: for(j=1; j<= nlstate; j++){
3468: for(h=0; h<=nhstepm; h++){
3469: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3470: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3471: }
3472: }
3473: /* This for computing probability of death (h=1 means
3474: computed over hstepm matrices product = hstepm*stepm months)
3475: as a weighted average of prlim.
3476: */
3477: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3478: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3479: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3480: }
3481: /* end probability of death */
3482:
3483: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3484: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3485: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3486: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3487:
3488: if (popbased==1) {
3489: if(mobilav ==0){
3490: for(i=1; i<=nlstate;i++)
3491: prlim[i][i]=probs[(int)age][i][ij];
3492: }else{ /* mobilav */
3493: for(i=1; i<=nlstate;i++)
3494: prlim[i][i]=mobaverage[(int)age][i][ij];
3495: }
3496: }
3497:
1.128 brouard 3498: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3499: for(h=0; h<=nhstepm; h++){
3500: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3501: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3502: }
3503: }
3504: /* This for computing probability of death (h=1 means
3505: computed over hstepm matrices product = hstepm*stepm months)
3506: as a weighted average of prlim.
3507: */
3508: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3509: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3510: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3511: }
3512: /* end probability of death */
3513:
3514: for(j=1; j<= nlstate; j++) /* vareij */
3515: for(h=0; h<=nhstepm; h++){
3516: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3517: }
3518:
3519: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3520: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3521: }
3522:
3523: } /* End theta */
3524:
3525: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3526:
3527: for(h=0; h<=nhstepm; h++) /* veij */
3528: for(j=1; j<=nlstate;j++)
3529: for(theta=1; theta <=npar; theta++)
3530: trgradg[h][j][theta]=gradg[h][theta][j];
3531:
3532: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3533: for(theta=1; theta <=npar; theta++)
3534: trgradgp[j][theta]=gradgp[theta][j];
3535:
3536:
3537: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3538: for(i=1;i<=nlstate;i++)
3539: for(j=1;j<=nlstate;j++)
3540: vareij[i][j][(int)age] =0.;
3541:
3542: for(h=0;h<=nhstepm;h++){
3543: for(k=0;k<=nhstepm;k++){
3544: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3545: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3546: for(i=1;i<=nlstate;i++)
3547: for(j=1;j<=nlstate;j++)
3548: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3549: }
3550: }
3551:
3552: /* pptj */
3553: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3554: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3555: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3556: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3557: varppt[j][i]=doldmp[j][i];
3558: /* end ppptj */
3559: /* x centered again */
3560: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3561: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3562:
3563: if (popbased==1) {
3564: if(mobilav ==0){
3565: for(i=1; i<=nlstate;i++)
3566: prlim[i][i]=probs[(int)age][i][ij];
3567: }else{ /* mobilav */
3568: for(i=1; i<=nlstate;i++)
3569: prlim[i][i]=mobaverage[(int)age][i][ij];
3570: }
3571: }
3572:
3573: /* This for computing probability of death (h=1 means
3574: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3575: as a weighted average of prlim.
3576: */
3577: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3578: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3579: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3580: }
3581: /* end probability of death */
3582:
3583: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3584: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3585: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3586: for(i=1; i<=nlstate;i++){
3587: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3588: }
3589: }
3590: fprintf(ficresprobmorprev,"\n");
3591:
3592: fprintf(ficresvij,"%.0f ",age );
3593: for(i=1; i<=nlstate;i++)
3594: for(j=1; j<=nlstate;j++){
3595: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3596: }
3597: fprintf(ficresvij,"\n");
3598: free_matrix(gp,0,nhstepm,1,nlstate);
3599: free_matrix(gm,0,nhstepm,1,nlstate);
3600: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3601: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3602: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3603: } /* End age */
3604: free_vector(gpp,nlstate+1,nlstate+ndeath);
3605: free_vector(gmp,nlstate+1,nlstate+ndeath);
3606: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3607: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3608: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3609: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3610: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3611: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3612: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3613: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3614: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3615: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3616: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3617: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3618: 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);
3619: /* 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);
3620: */
3621: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3622: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3623:
3624: free_vector(xp,1,npar);
3625: free_matrix(doldm,1,nlstate,1,nlstate);
3626: free_matrix(dnewm,1,nlstate,1,npar);
3627: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3628: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3629: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3630: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3631: fclose(ficresprobmorprev);
3632: fflush(ficgp);
3633: fflush(fichtm);
3634: } /* end varevsij */
3635:
3636: /************ Variance of prevlim ******************/
3637: 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[])
3638: {
3639: /* Variance of prevalence limit */
3640: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3641:
1.126 brouard 3642: double **dnewm,**doldm;
3643: int i, j, nhstepm, hstepm;
3644: double *xp;
3645: double *gp, *gm;
3646: double **gradg, **trgradg;
3647: double age,agelim;
3648: int theta;
3649:
3650: pstamp(ficresvpl);
3651: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3652: fprintf(ficresvpl,"# Age");
3653: for(i=1; i<=nlstate;i++)
3654: fprintf(ficresvpl," %1d-%1d",i,i);
3655: fprintf(ficresvpl,"\n");
3656:
3657: xp=vector(1,npar);
3658: dnewm=matrix(1,nlstate,1,npar);
3659: doldm=matrix(1,nlstate,1,nlstate);
3660:
3661: hstepm=1*YEARM; /* Every year of age */
3662: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3663: agelim = AGESUP;
3664: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3665: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3666: if (stepm >= YEARM) hstepm=1;
3667: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3668: gradg=matrix(1,npar,1,nlstate);
3669: gp=vector(1,nlstate);
3670: gm=vector(1,nlstate);
3671:
3672: for(theta=1; theta <=npar; theta++){
3673: for(i=1; i<=npar; i++){ /* Computes gradient */
3674: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3675: }
3676: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3677: for(i=1;i<=nlstate;i++)
3678: gp[i] = prlim[i][i];
3679:
3680: for(i=1; i<=npar; i++) /* Computes gradient */
3681: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3682: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3683: for(i=1;i<=nlstate;i++)
3684: gm[i] = prlim[i][i];
3685:
3686: for(i=1;i<=nlstate;i++)
3687: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3688: } /* End theta */
3689:
3690: trgradg =matrix(1,nlstate,1,npar);
3691:
3692: for(j=1; j<=nlstate;j++)
3693: for(theta=1; theta <=npar; theta++)
3694: trgradg[j][theta]=gradg[theta][j];
3695:
3696: for(i=1;i<=nlstate;i++)
3697: varpl[i][(int)age] =0.;
3698: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3699: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3700: for(i=1;i<=nlstate;i++)
3701: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3702:
3703: fprintf(ficresvpl,"%.0f ",age );
3704: for(i=1; i<=nlstate;i++)
3705: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3706: fprintf(ficresvpl,"\n");
3707: free_vector(gp,1,nlstate);
3708: free_vector(gm,1,nlstate);
3709: free_matrix(gradg,1,npar,1,nlstate);
3710: free_matrix(trgradg,1,nlstate,1,npar);
3711: } /* End age */
3712:
3713: free_vector(xp,1,npar);
3714: free_matrix(doldm,1,nlstate,1,npar);
3715: free_matrix(dnewm,1,nlstate,1,nlstate);
3716:
3717: }
3718:
3719: /************ Variance of one-step probabilities ******************/
3720: 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[])
3721: {
1.164 brouard 3722: int i, j=0, k1, l1, tj;
1.126 brouard 3723: int k2, l2, j1, z1;
1.164 brouard 3724: int k=0, l;
1.145 brouard 3725: int first=1, first1, first2;
1.126 brouard 3726: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3727: double **dnewm,**doldm;
3728: double *xp;
3729: double *gp, *gm;
3730: double **gradg, **trgradg;
3731: double **mu;
1.164 brouard 3732: double age, cov[NCOVMAX+1];
1.126 brouard 3733: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3734: int theta;
3735: char fileresprob[FILENAMELENGTH];
3736: char fileresprobcov[FILENAMELENGTH];
3737: char fileresprobcor[FILENAMELENGTH];
3738: double ***varpij;
3739:
3740: strcpy(fileresprob,"prob");
3741: strcat(fileresprob,fileres);
3742: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3743: printf("Problem with resultfile: %s\n", fileresprob);
3744: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3745: }
3746: strcpy(fileresprobcov,"probcov");
3747: strcat(fileresprobcov,fileres);
3748: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3749: printf("Problem with resultfile: %s\n", fileresprobcov);
3750: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3751: }
3752: strcpy(fileresprobcor,"probcor");
3753: strcat(fileresprobcor,fileres);
3754: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3755: printf("Problem with resultfile: %s\n", fileresprobcor);
3756: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3757: }
3758: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3759: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3760: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3761: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3762: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3763: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3764: pstamp(ficresprob);
3765: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3766: fprintf(ficresprob,"# Age");
3767: pstamp(ficresprobcov);
3768: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3769: fprintf(ficresprobcov,"# Age");
3770: pstamp(ficresprobcor);
3771: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3772: fprintf(ficresprobcor,"# Age");
3773:
3774:
3775: for(i=1; i<=nlstate;i++)
3776: for(j=1; j<=(nlstate+ndeath);j++){
3777: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3778: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3779: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3780: }
3781: /* fprintf(ficresprob,"\n");
3782: fprintf(ficresprobcov,"\n");
3783: fprintf(ficresprobcor,"\n");
3784: */
1.131 brouard 3785: xp=vector(1,npar);
1.126 brouard 3786: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3787: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3788: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3789: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3790: first=1;
3791: fprintf(ficgp,"\n# Routine varprob");
3792: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3793: fprintf(fichtm,"\n");
3794:
3795: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3796: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3797: file %s<br>\n",optionfilehtmcov);
3798: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3799: and drawn. It helps understanding how is the covariance between two incidences.\
3800: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3801: 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. \
3802: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3803: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3804: standard deviations wide on each axis. <br>\
3805: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3806: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3807: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3808:
3809: cov[1]=1;
1.145 brouard 3810: /* tj=cptcoveff; */
3811: tj = (int) pow(2,cptcoveff);
1.126 brouard 3812: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3813: j1=0;
1.145 brouard 3814: for(j1=1; j1<=tj;j1++){
3815: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3816: /*j1++;*/
1.126 brouard 3817: if (cptcovn>0) {
3818: fprintf(ficresprob, "\n#********** Variable ");
3819: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3820: fprintf(ficresprob, "**********\n#\n");
3821: fprintf(ficresprobcov, "\n#********** Variable ");
3822: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3823: fprintf(ficresprobcov, "**********\n#\n");
3824:
3825: fprintf(ficgp, "\n#********** Variable ");
3826: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3827: fprintf(ficgp, "**********\n#\n");
3828:
3829:
3830: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3831: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3832: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3833:
3834: fprintf(ficresprobcor, "\n#********** Variable ");
3835: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3836: fprintf(ficresprobcor, "**********\n#");
3837: }
3838:
1.145 brouard 3839: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3840: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3841: gp=vector(1,(nlstate)*(nlstate+ndeath));
3842: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3843: for (age=bage; age<=fage; age ++){
3844: cov[2]=age;
3845: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3846: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3847: * 1 1 1 1 1
3848: * 2 2 1 1 1
3849: * 3 1 2 1 1
3850: */
3851: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3852: }
3853: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3854: for (k=1; k<=cptcovprod;k++)
3855: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3856:
3857:
3858: for(theta=1; theta <=npar; theta++){
3859: for(i=1; i<=npar; i++)
3860: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3861:
3862: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3863:
3864: k=0;
3865: for(i=1; i<= (nlstate); i++){
3866: for(j=1; j<=(nlstate+ndeath);j++){
3867: k=k+1;
3868: gp[k]=pmmij[i][j];
3869: }
3870: }
3871:
3872: for(i=1; i<=npar; i++)
3873: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3874:
3875: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3876: k=0;
3877: for(i=1; i<=(nlstate); i++){
3878: for(j=1; j<=(nlstate+ndeath);j++){
3879: k=k+1;
3880: gm[k]=pmmij[i][j];
3881: }
3882: }
3883:
3884: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3885: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3886: }
3887:
3888: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3889: for(theta=1; theta <=npar; theta++)
3890: trgradg[j][theta]=gradg[theta][j];
3891:
3892: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3893: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3894:
3895: pmij(pmmij,cov,ncovmodel,x,nlstate);
3896:
3897: k=0;
3898: for(i=1; i<=(nlstate); i++){
3899: for(j=1; j<=(nlstate+ndeath);j++){
3900: k=k+1;
3901: mu[k][(int) age]=pmmij[i][j];
3902: }
3903: }
3904: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3905: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3906: varpij[i][j][(int)age] = doldm[i][j];
3907:
3908: /*printf("\n%d ",(int)age);
3909: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3910: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3911: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3912: }*/
3913:
3914: fprintf(ficresprob,"\n%d ",(int)age);
3915: fprintf(ficresprobcov,"\n%d ",(int)age);
3916: fprintf(ficresprobcor,"\n%d ",(int)age);
3917:
3918: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3919: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3920: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3921: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3922: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3923: }
3924: i=0;
3925: for (k=1; k<=(nlstate);k++){
3926: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3927: i++;
1.126 brouard 3928: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3929: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3930: for (j=1; j<=i;j++){
1.145 brouard 3931: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3932: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3933: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3934: }
3935: }
3936: }/* end of loop for state */
3937: } /* end of loop for age */
1.145 brouard 3938: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3939: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3940: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3941: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3942:
1.126 brouard 3943: /* Confidence intervalle of pij */
3944: /*
1.131 brouard 3945: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3946: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3947: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3948: 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);
3949: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3950: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3951: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3952: */
3953:
3954: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3955: first1=1;first2=2;
1.126 brouard 3956: for (k2=1; k2<=(nlstate);k2++){
3957: for (l2=1; l2<=(nlstate+ndeath);l2++){
3958: if(l2==k2) continue;
3959: j=(k2-1)*(nlstate+ndeath)+l2;
3960: for (k1=1; k1<=(nlstate);k1++){
3961: for (l1=1; l1<=(nlstate+ndeath);l1++){
3962: if(l1==k1) continue;
3963: i=(k1-1)*(nlstate+ndeath)+l1;
3964: if(i<=j) continue;
3965: for (age=bage; age<=fage; age ++){
3966: if ((int)age %5==0){
3967: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3968: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3969: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3970: mu1=mu[i][(int) age]/stepm*YEARM ;
3971: mu2=mu[j][(int) age]/stepm*YEARM;
3972: c12=cv12/sqrt(v1*v2);
3973: /* Computing eigen value of matrix of covariance */
3974: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3975: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3976: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3977: if(first2==1){
3978: first1=0;
3979: 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);
3980: }
3981: 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);
3982: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3983: /* lc2=fabs(lc2); */
1.135 brouard 3984: }
3985:
1.126 brouard 3986: /* Eigen vectors */
3987: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3988: /*v21=sqrt(1.-v11*v11); *//* error */
3989: v21=(lc1-v1)/cv12*v11;
3990: v12=-v21;
3991: v22=v11;
3992: tnalp=v21/v11;
3993: if(first1==1){
3994: first1=0;
3995: 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);
3996: }
3997: 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);
3998: /*printf(fignu*/
3999: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4000: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4001: if(first==1){
4002: first=0;
4003: fprintf(ficgp,"\nset parametric;unset label");
4004: 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 4005: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4006: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4007: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4008: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4009: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4010: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4011: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4012: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4013: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4014: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4015: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4016: 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",\
4017: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4018: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4019: }else{
4020: first=0;
4021: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4022: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4023: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4024: 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",\
4025: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4026: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4027: }/* if first */
4028: } /* age mod 5 */
4029: } /* end loop age */
4030: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4031: first=1;
4032: } /*l12 */
4033: } /* k12 */
4034: } /*l1 */
4035: }/* k1 */
1.145 brouard 4036: /* } /* loop covariates */
1.126 brouard 4037: }
4038: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4039: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4040: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4041: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4042: free_vector(xp,1,npar);
4043: fclose(ficresprob);
4044: fclose(ficresprobcov);
4045: fclose(ficresprobcor);
4046: fflush(ficgp);
4047: fflush(fichtmcov);
4048: }
4049:
4050:
4051: /******************* Printing html file ***********/
4052: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4053: int lastpass, int stepm, int weightopt, char model[],\
4054: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4055: int popforecast, int estepm ,\
4056: double jprev1, double mprev1,double anprev1, \
4057: double jprev2, double mprev2,double anprev2){
4058: int jj1, k1, i1, cpt;
4059:
4060: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4061: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4062: </ul>");
4063: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4064: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4065: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4066: fprintf(fichtm,"\
4067: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4068: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4069: fprintf(fichtm,"\
4070: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4071: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4072: fprintf(fichtm,"\
1.128 brouard 4073: - (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 4074: <a href=\"%s\">%s</a> <br>\n",
4075: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4076: fprintf(fichtm,"\
4077: - Population projections by age and states: \
4078: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4079:
4080: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4081:
1.145 brouard 4082: m=pow(2,cptcoveff);
1.126 brouard 4083: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4084:
4085: jj1=0;
4086: for(k1=1; k1<=m;k1++){
4087: for(i1=1; i1<=ncodemax[k1];i1++){
4088: jj1++;
4089: if (cptcovn > 0) {
4090: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4091: for (cpt=1; cpt<=cptcoveff;cpt++)
4092: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4093: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4094: }
4095: /* Pij */
1.145 brouard 4096: 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> \
4097: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4098: /* Quasi-incidences */
4099: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4100: 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> \
4101: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4102: /* Period (stable) prevalence in each health state */
1.154 brouard 4103: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4104: 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> \
4105: <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 4106: }
4107: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4108: 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> \
4109: <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 4110: }
4111: } /* end i1 */
4112: }/* End k1 */
4113: fprintf(fichtm,"</ul>");
4114:
4115:
4116: fprintf(fichtm,"\
4117: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4118: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4119:
4120: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4121: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4122: fprintf(fichtm,"\
4123: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4124: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4125:
4126: fprintf(fichtm,"\
4127: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4128: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4129: fprintf(fichtm,"\
4130: - 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): \
4131: <a href=\"%s\">%s</a> <br>\n</li>",
4132: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4133: fprintf(fichtm,"\
4134: - (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): \
4135: <a href=\"%s\">%s</a> <br>\n</li>",
4136: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4137: fprintf(fichtm,"\
1.128 brouard 4138: - 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 4139: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4140: fprintf(fichtm,"\
1.128 brouard 4141: - 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",
4142: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4143: fprintf(fichtm,"\
4144: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4145: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4146:
4147: /* if(popforecast==1) fprintf(fichtm,"\n */
4148: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4149: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4150: /* <br>",fileres,fileres,fileres,fileres); */
4151: /* else */
4152: /* 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); */
4153: fflush(fichtm);
4154: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4155:
1.145 brouard 4156: m=pow(2,cptcoveff);
1.126 brouard 4157: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4158:
4159: jj1=0;
4160: for(k1=1; k1<=m;k1++){
4161: for(i1=1; i1<=ncodemax[k1];i1++){
4162: jj1++;
4163: if (cptcovn > 0) {
4164: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4165: for (cpt=1; cpt<=cptcoveff;cpt++)
4166: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4167: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4168: }
4169: for(cpt=1; cpt<=nlstate;cpt++) {
4170: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4171: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4172: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4173: }
4174: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4175: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4176: true period expectancies (those weighted with period prevalences are also\
4177: drawn in addition to the population based expectancies computed using\
4178: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4179: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4180: } /* end i1 */
4181: }/* End k1 */
4182: fprintf(fichtm,"</ul>");
4183: fflush(fichtm);
4184: }
4185:
4186: /******************* Gnuplot file **************/
4187: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4188:
4189: char dirfileres[132],optfileres[132];
1.164 brouard 4190: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4191: int ng=0;
1.126 brouard 4192: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4193: /* printf("Problem with file %s",optionfilegnuplot); */
4194: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4195: /* } */
4196:
4197: /*#ifdef windows */
4198: fprintf(ficgp,"cd \"%s\" \n",pathc);
4199: /*#endif */
4200: m=pow(2,cptcoveff);
4201:
4202: strcpy(dirfileres,optionfilefiname);
4203: strcpy(optfileres,"vpl");
4204: /* 1eme*/
1.153 brouard 4205: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4206: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4207: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4208: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4209: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4210: fprintf(ficgp,"set xlabel \"Age\" \n\
4211: set ylabel \"Probability\" \n\
1.145 brouard 4212: set ter png small size 320, 240\n\
1.126 brouard 4213: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4214:
4215: for (i=1; i<= nlstate ; i ++) {
4216: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4217: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4218: }
1.145 brouard 4219: 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 4220: for (i=1; i<= nlstate ; i ++) {
4221: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4222: else fprintf(ficgp," \%%*lf (\%%*lf)");
4223: }
1.145 brouard 4224: 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 4225: for (i=1; i<= nlstate ; i ++) {
4226: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4227: else fprintf(ficgp," \%%*lf (\%%*lf)");
4228: }
1.145 brouard 4229: 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 4230: }
4231: }
4232: /*2 eme*/
1.153 brouard 4233: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4234: for (k1=1; k1<= m ; k1 ++) {
4235: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4236: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4237:
4238: for (i=1; i<= nlstate+1 ; i ++) {
4239: k=2*i;
4240: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4241: for (j=1; j<= nlstate+1 ; j ++) {
4242: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4243: else fprintf(ficgp," \%%*lf (\%%*lf)");
4244: }
4245: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4246: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4247: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4248: for (j=1; j<= nlstate+1 ; j ++) {
4249: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4250: else fprintf(ficgp," \%%*lf (\%%*lf)");
4251: }
1.145 brouard 4252: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4253: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4254: for (j=1; j<= nlstate+1 ; j ++) {
4255: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4256: else fprintf(ficgp," \%%*lf (\%%*lf)");
4257: }
1.145 brouard 4258: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4259: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4260: }
4261: }
4262:
4263: /*3eme*/
4264:
4265: for (k1=1; k1<= m ; k1 ++) {
4266: for (cpt=1; cpt<= nlstate ; cpt ++) {
4267: /* k=2+nlstate*(2*cpt-2); */
4268: k=2+(nlstate+1)*(cpt-1);
4269: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4270: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4271: 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);
4272: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4273: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4274: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4275: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4276: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4277: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4278:
4279: */
4280: for (i=1; i< nlstate ; i ++) {
4281: 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);
4282: /* 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);*/
4283:
4284: }
4285: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4286: }
4287: }
4288:
4289: /* CV preval stable (period) */
1.153 brouard 4290: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4291: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4292: k=3;
1.153 brouard 4293: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4294: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4295: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4296: set ter png small size 320, 240\n\
1.126 brouard 4297: unset log y\n\
1.153 brouard 4298: plot [%.f:%.f] ", ageminpar, agemaxpar);
4299: for (i=1; i<= nlstate ; i ++){
4300: if(i==1)
4301: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4302: else
4303: fprintf(ficgp,", '' ");
1.154 brouard 4304: l=(nlstate+ndeath)*(i-1)+1;
4305: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4306: for (j=1; j<= (nlstate-1) ; j ++)
4307: fprintf(ficgp,"+$%d",k+l+j);
4308: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4309: } /* nlstate */
4310: fprintf(ficgp,"\n");
4311: } /* end cpt state*/
4312: } /* end covariate */
1.126 brouard 4313:
4314: /* proba elementaires */
4315: for(i=1,jk=1; i <=nlstate; i++){
4316: for(k=1; k <=(nlstate+ndeath); k++){
4317: if (k != i) {
4318: for(j=1; j <=ncovmodel; j++){
4319: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4320: jk++;
4321: fprintf(ficgp,"\n");
4322: }
4323: }
4324: }
4325: }
1.145 brouard 4326: /*goto avoid;*/
1.126 brouard 4327: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4328: for(jk=1; jk <=m; jk++) {
1.145 brouard 4329: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4330: if (ng==2)
4331: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4332: else
4333: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4334: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4335: i=1;
4336: for(k2=1; k2<=nlstate; k2++) {
4337: k3=i;
4338: for(k=1; k<=(nlstate+ndeath); k++) {
4339: if (k != k2){
4340: if(ng==2)
4341: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4342: else
4343: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4344: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4345: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4346: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4347: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4348: /* ij++; */
4349: /* } */
4350: /* else */
1.126 brouard 4351: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4352: }
4353: fprintf(ficgp,")/(1");
4354:
4355: for(k1=1; k1 <=nlstate; k1++){
4356: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4357: ij=1;
4358: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4359: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4360: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4361: /* ij++; */
4362: /* } */
4363: /* else */
1.126 brouard 4364: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4365: }
4366: fprintf(ficgp,")");
4367: }
4368: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4369: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4370: i=i+ncovmodel;
4371: }
4372: } /* end k */
4373: } /* end k2 */
4374: } /* end jk */
4375: } /* end ng */
1.164 brouard 4376: /* avoid: */
1.126 brouard 4377: fflush(ficgp);
4378: } /* end gnuplot */
4379:
4380:
4381: /*************** Moving average **************/
4382: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4383:
4384: int i, cpt, cptcod;
4385: int modcovmax =1;
4386: int mobilavrange, mob;
4387: double age;
4388:
4389: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4390: a covariate has 2 modalities */
4391: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4392:
4393: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4394: if(mobilav==1) mobilavrange=5; /* default */
4395: else mobilavrange=mobilav;
4396: for (age=bage; age<=fage; age++)
4397: for (i=1; i<=nlstate;i++)
4398: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4399: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4400: /* We keep the original values on the extreme ages bage, fage and for
4401: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4402: we use a 5 terms etc. until the borders are no more concerned.
4403: */
4404: for (mob=3;mob <=mobilavrange;mob=mob+2){
4405: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4406: for (i=1; i<=nlstate;i++){
4407: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4408: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4409: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4410: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4411: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4412: }
4413: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4414: }
4415: }
4416: }/* end age */
4417: }/* end mob */
4418: }else return -1;
4419: return 0;
4420: }/* End movingaverage */
4421:
4422:
4423: /************** Forecasting ******************/
4424: 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){
4425: /* proj1, year, month, day of starting projection
4426: agemin, agemax range of age
4427: dateprev1 dateprev2 range of dates during which prevalence is computed
4428: anproj2 year of en of projection (same day and month as proj1).
4429: */
1.164 brouard 4430: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4431: double agec; /* generic age */
4432: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4433: double *popeffectif,*popcount;
4434: double ***p3mat;
4435: double ***mobaverage;
4436: char fileresf[FILENAMELENGTH];
4437:
4438: agelim=AGESUP;
4439: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4440:
4441: strcpy(fileresf,"f");
4442: strcat(fileresf,fileres);
4443: if((ficresf=fopen(fileresf,"w"))==NULL) {
4444: printf("Problem with forecast resultfile: %s\n", fileresf);
4445: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4446: }
4447: printf("Computing forecasting: result on file '%s' \n", fileresf);
4448: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4449:
4450: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4451:
4452: if (mobilav!=0) {
4453: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4454: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4455: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4456: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4457: }
4458: }
4459:
4460: stepsize=(int) (stepm+YEARM-1)/YEARM;
4461: if (stepm<=12) stepsize=1;
4462: if(estepm < stepm){
4463: printf ("Problem %d lower than %d\n",estepm, stepm);
4464: }
4465: else hstepm=estepm;
4466:
4467: hstepm=hstepm/stepm;
4468: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4469: fractional in yp1 */
4470: anprojmean=yp;
4471: yp2=modf((yp1*12),&yp);
4472: mprojmean=yp;
4473: yp1=modf((yp2*30.5),&yp);
4474: jprojmean=yp;
4475: if(jprojmean==0) jprojmean=1;
4476: if(mprojmean==0) jprojmean=1;
4477:
4478: i1=cptcoveff;
4479: if (cptcovn < 1){i1=1;}
4480:
4481: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4482:
4483: fprintf(ficresf,"#****** Routine prevforecast **\n");
4484:
4485: /* if (h==(int)(YEARM*yearp)){ */
4486: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4487: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4488: k=k+1;
4489: fprintf(ficresf,"\n#******");
4490: for(j=1;j<=cptcoveff;j++) {
4491: 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]]);
4492: }
4493: fprintf(ficresf,"******\n");
4494: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4495: for(j=1; j<=nlstate+ndeath;j++){
4496: for(i=1; i<=nlstate;i++)
4497: fprintf(ficresf," p%d%d",i,j);
4498: fprintf(ficresf," p.%d",j);
4499: }
4500: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4501: fprintf(ficresf,"\n");
4502: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4503:
4504: for (agec=fage; agec>=(ageminpar-1); agec--){
4505: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4506: nhstepm = nhstepm/hstepm;
4507: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4508: oldm=oldms;savm=savms;
4509: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4510:
4511: for (h=0; h<=nhstepm; h++){
4512: if (h*hstepm/YEARM*stepm ==yearp) {
4513: fprintf(ficresf,"\n");
4514: for(j=1;j<=cptcoveff;j++)
4515: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4516: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4517: }
4518: for(j=1; j<=nlstate+ndeath;j++) {
4519: ppij=0.;
4520: for(i=1; i<=nlstate;i++) {
4521: if (mobilav==1)
4522: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4523: else {
4524: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4525: }
4526: if (h*hstepm/YEARM*stepm== yearp) {
4527: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4528: }
4529: } /* end i */
4530: if (h*hstepm/YEARM*stepm==yearp) {
4531: fprintf(ficresf," %.3f", ppij);
4532: }
4533: }/* end j */
4534: } /* end h */
4535: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4536: } /* end agec */
4537: } /* end yearp */
4538: } /* end cptcod */
4539: } /* end cptcov */
4540:
4541: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4542:
4543: fclose(ficresf);
4544: }
4545:
4546: /************** Forecasting *****not tested NB*************/
4547: 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){
4548:
4549: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4550: int *popage;
4551: double calagedatem, agelim, kk1, kk2;
4552: double *popeffectif,*popcount;
4553: double ***p3mat,***tabpop,***tabpopprev;
4554: double ***mobaverage;
4555: char filerespop[FILENAMELENGTH];
4556:
4557: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4558: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4559: agelim=AGESUP;
4560: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4561:
4562: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4563:
4564:
4565: strcpy(filerespop,"pop");
4566: strcat(filerespop,fileres);
4567: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4568: printf("Problem with forecast resultfile: %s\n", filerespop);
4569: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4570: }
4571: printf("Computing forecasting: result on file '%s' \n", filerespop);
4572: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4573:
4574: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4575:
4576: if (mobilav!=0) {
4577: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4578: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4579: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4580: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4581: }
4582: }
4583:
4584: stepsize=(int) (stepm+YEARM-1)/YEARM;
4585: if (stepm<=12) stepsize=1;
4586:
4587: agelim=AGESUP;
4588:
4589: hstepm=1;
4590: hstepm=hstepm/stepm;
4591:
4592: if (popforecast==1) {
4593: if((ficpop=fopen(popfile,"r"))==NULL) {
4594: printf("Problem with population file : %s\n",popfile);exit(0);
4595: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4596: }
4597: popage=ivector(0,AGESUP);
4598: popeffectif=vector(0,AGESUP);
4599: popcount=vector(0,AGESUP);
4600:
4601: i=1;
4602: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4603:
4604: imx=i;
4605: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4606: }
4607:
4608: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4609: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4610: k=k+1;
4611: fprintf(ficrespop,"\n#******");
4612: for(j=1;j<=cptcoveff;j++) {
4613: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4614: }
4615: fprintf(ficrespop,"******\n");
4616: fprintf(ficrespop,"# Age");
4617: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4618: if (popforecast==1) fprintf(ficrespop," [Population]");
4619:
4620: for (cpt=0; cpt<=0;cpt++) {
4621: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4622:
4623: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4624: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4625: nhstepm = nhstepm/hstepm;
4626:
4627: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4628: oldm=oldms;savm=savms;
4629: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4630:
4631: for (h=0; h<=nhstepm; h++){
4632: if (h==(int) (calagedatem+YEARM*cpt)) {
4633: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4634: }
4635: for(j=1; j<=nlstate+ndeath;j++) {
4636: kk1=0.;kk2=0;
4637: for(i=1; i<=nlstate;i++) {
4638: if (mobilav==1)
4639: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4640: else {
4641: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4642: }
4643: }
4644: if (h==(int)(calagedatem+12*cpt)){
4645: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4646: /*fprintf(ficrespop," %.3f", kk1);
4647: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4648: }
4649: }
4650: for(i=1; i<=nlstate;i++){
4651: kk1=0.;
4652: for(j=1; j<=nlstate;j++){
4653: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4654: }
4655: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4656: }
4657:
4658: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4659: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4660: }
4661: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4662: }
4663: }
4664:
4665: /******/
4666:
4667: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4668: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4669: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4670: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4671: nhstepm = nhstepm/hstepm;
4672:
4673: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4674: oldm=oldms;savm=savms;
4675: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4676: for (h=0; h<=nhstepm; h++){
4677: if (h==(int) (calagedatem+YEARM*cpt)) {
4678: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4679: }
4680: for(j=1; j<=nlstate+ndeath;j++) {
4681: kk1=0.;kk2=0;
4682: for(i=1; i<=nlstate;i++) {
4683: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4684: }
4685: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4686: }
4687: }
4688: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4689: }
4690: }
4691: }
4692: }
4693:
4694: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4695:
4696: if (popforecast==1) {
4697: free_ivector(popage,0,AGESUP);
4698: free_vector(popeffectif,0,AGESUP);
4699: free_vector(popcount,0,AGESUP);
4700: }
4701: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4702: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4703: fclose(ficrespop);
4704: } /* End of popforecast */
4705:
4706: int fileappend(FILE *fichier, char *optionfich)
4707: {
4708: if((fichier=fopen(optionfich,"a"))==NULL) {
4709: printf("Problem with file: %s\n", optionfich);
4710: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4711: return (0);
4712: }
4713: fflush(fichier);
4714: return (1);
4715: }
4716:
4717:
4718: /**************** function prwizard **********************/
4719: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4720: {
4721:
4722: /* Wizard to print covariance matrix template */
4723:
1.164 brouard 4724: char ca[32], cb[32];
4725: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4726: int numlinepar;
4727:
4728: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4729: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4730: for(i=1; i <=nlstate; i++){
4731: jj=0;
4732: for(j=1; j <=nlstate+ndeath; j++){
4733: if(j==i) continue;
4734: jj++;
4735: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4736: printf("%1d%1d",i,j);
4737: fprintf(ficparo,"%1d%1d",i,j);
4738: for(k=1; k<=ncovmodel;k++){
4739: /* printf(" %lf",param[i][j][k]); */
4740: /* fprintf(ficparo," %lf",param[i][j][k]); */
4741: printf(" 0.");
4742: fprintf(ficparo," 0.");
4743: }
4744: printf("\n");
4745: fprintf(ficparo,"\n");
4746: }
4747: }
4748: printf("# Scales (for hessian or gradient estimation)\n");
4749: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4750: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4751: for(i=1; i <=nlstate; i++){
4752: jj=0;
4753: for(j=1; j <=nlstate+ndeath; j++){
4754: if(j==i) continue;
4755: jj++;
4756: fprintf(ficparo,"%1d%1d",i,j);
4757: printf("%1d%1d",i,j);
4758: fflush(stdout);
4759: for(k=1; k<=ncovmodel;k++){
4760: /* printf(" %le",delti3[i][j][k]); */
4761: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4762: printf(" 0.");
4763: fprintf(ficparo," 0.");
4764: }
4765: numlinepar++;
4766: printf("\n");
4767: fprintf(ficparo,"\n");
4768: }
4769: }
4770: printf("# Covariance matrix\n");
4771: /* # 121 Var(a12)\n\ */
4772: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4773: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4774: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4775: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4776: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4777: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4778: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4779: fflush(stdout);
4780: fprintf(ficparo,"# Covariance matrix\n");
4781: /* # 121 Var(a12)\n\ */
4782: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4783: /* # ...\n\ */
4784: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4785:
4786: for(itimes=1;itimes<=2;itimes++){
4787: jj=0;
4788: for(i=1; i <=nlstate; i++){
4789: for(j=1; j <=nlstate+ndeath; j++){
4790: if(j==i) continue;
4791: for(k=1; k<=ncovmodel;k++){
4792: jj++;
4793: ca[0]= k+'a'-1;ca[1]='\0';
4794: if(itimes==1){
4795: printf("#%1d%1d%d",i,j,k);
4796: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4797: }else{
4798: printf("%1d%1d%d",i,j,k);
4799: fprintf(ficparo,"%1d%1d%d",i,j,k);
4800: /* printf(" %.5le",matcov[i][j]); */
4801: }
4802: ll=0;
4803: for(li=1;li <=nlstate; li++){
4804: for(lj=1;lj <=nlstate+ndeath; lj++){
4805: if(lj==li) continue;
4806: for(lk=1;lk<=ncovmodel;lk++){
4807: ll++;
4808: if(ll<=jj){
4809: cb[0]= lk +'a'-1;cb[1]='\0';
4810: if(ll<jj){
4811: if(itimes==1){
4812: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4813: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4814: }else{
4815: printf(" 0.");
4816: fprintf(ficparo," 0.");
4817: }
4818: }else{
4819: if(itimes==1){
4820: printf(" Var(%s%1d%1d)",ca,i,j);
4821: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4822: }else{
4823: printf(" 0.");
4824: fprintf(ficparo," 0.");
4825: }
4826: }
4827: }
4828: } /* end lk */
4829: } /* end lj */
4830: } /* end li */
4831: printf("\n");
4832: fprintf(ficparo,"\n");
4833: numlinepar++;
4834: } /* end k*/
4835: } /*end j */
4836: } /* end i */
4837: } /* end itimes */
4838:
4839: } /* end of prwizard */
4840: /******************* Gompertz Likelihood ******************************/
4841: double gompertz(double x[])
4842: {
4843: double A,B,L=0.0,sump=0.,num=0.;
4844: int i,n=0; /* n is the size of the sample */
4845:
4846: for (i=0;i<=imx-1 ; i++) {
4847: sump=sump+weight[i];
4848: /* sump=sump+1;*/
4849: num=num+1;
4850: }
4851:
4852:
4853: /* for (i=0; i<=imx; i++)
4854: 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]);*/
4855:
4856: for (i=1;i<=imx ; i++)
4857: {
4858: if (cens[i] == 1 && wav[i]>1)
4859: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4860:
4861: if (cens[i] == 0 && wav[i]>1)
4862: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4863: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4864:
4865: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4866: if (wav[i] > 1 ) { /* ??? */
4867: L=L+A*weight[i];
4868: /* 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]);*/
4869: }
4870: }
4871:
4872: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4873:
4874: return -2*L*num/sump;
4875: }
4876:
1.136 brouard 4877: #ifdef GSL
4878: /******************* Gompertz_f Likelihood ******************************/
4879: double gompertz_f(const gsl_vector *v, void *params)
4880: {
4881: double A,B,LL=0.0,sump=0.,num=0.;
4882: double *x= (double *) v->data;
4883: int i,n=0; /* n is the size of the sample */
4884:
4885: for (i=0;i<=imx-1 ; i++) {
4886: sump=sump+weight[i];
4887: /* sump=sump+1;*/
4888: num=num+1;
4889: }
4890:
4891:
4892: /* for (i=0; i<=imx; i++)
4893: 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]);*/
4894: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4895: for (i=1;i<=imx ; i++)
4896: {
4897: if (cens[i] == 1 && wav[i]>1)
4898: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4899:
4900: if (cens[i] == 0 && wav[i]>1)
4901: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4902: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4903:
4904: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4905: if (wav[i] > 1 ) { /* ??? */
4906: LL=LL+A*weight[i];
4907: /* 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]);*/
4908: }
4909: }
4910:
4911: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4912: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4913:
4914: return -2*LL*num/sump;
4915: }
4916: #endif
4917:
1.126 brouard 4918: /******************* Printing html file ***********/
4919: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4920: int lastpass, int stepm, int weightopt, char model[],\
4921: int imx, double p[],double **matcov,double agemortsup){
4922: int i,k;
4923:
4924: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4925: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4926: for (i=1;i<=2;i++)
4927: 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]));
4928: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4929: fprintf(fichtm,"</ul>");
4930:
4931: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4932:
4933: 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>");
4934:
4935: for (k=agegomp;k<(agemortsup-2);k++)
4936: 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]);
4937:
4938:
4939: fflush(fichtm);
4940: }
4941:
4942: /******************* Gnuplot file **************/
4943: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4944:
4945: char dirfileres[132],optfileres[132];
1.164 brouard 4946:
1.126 brouard 4947: int ng;
4948:
4949:
4950: /*#ifdef windows */
4951: fprintf(ficgp,"cd \"%s\" \n",pathc);
4952: /*#endif */
4953:
4954:
4955: strcpy(dirfileres,optionfilefiname);
4956: strcpy(optfileres,"vpl");
4957: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4958: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4959: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4960: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4961: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4962:
4963: }
4964:
1.136 brouard 4965: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4966: {
1.126 brouard 4967:
1.136 brouard 4968: /*-------- data file ----------*/
4969: FILE *fic;
4970: char dummy[]=" ";
1.164 brouard 4971: int i=0, j=0, n=0;
1.136 brouard 4972: int linei, month, year,iout;
4973: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 4974: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 4975: char *stratrunc;
4976: int lstra;
1.126 brouard 4977:
4978:
1.136 brouard 4979: if((fic=fopen(datafile,"r"))==NULL) {
4980: printf("Problem while opening datafile: %s\n", datafile);return 1;
4981: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4982: }
1.126 brouard 4983:
1.136 brouard 4984: i=1;
4985: linei=0;
4986: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4987: linei=linei+1;
4988: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4989: if(line[j] == '\t')
4990: line[j] = ' ';
4991: }
4992: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4993: ;
4994: };
4995: line[j+1]=0; /* Trims blanks at end of line */
4996: if(line[0]=='#'){
4997: fprintf(ficlog,"Comment line\n%s\n",line);
4998: printf("Comment line\n%s\n",line);
4999: continue;
5000: }
5001: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5002: strcpy(line, linetmp);
1.136 brouard 5003:
1.126 brouard 5004:
1.136 brouard 5005: for (j=maxwav;j>=1;j--){
1.137 brouard 5006: cutv(stra, strb, line, ' ');
1.136 brouard 5007: if(strb[0]=='.') { /* Missing status */
5008: lval=-1;
5009: }else{
5010: errno=0;
5011: lval=strtol(strb,&endptr,10);
5012: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5013: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5014: 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);
5015: 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 5016: return 1;
5017: }
5018: }
5019: s[j][i]=lval;
5020:
5021: strcpy(line,stra);
5022: cutv(stra, strb,line,' ');
5023: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5024: }
1.145 brouard 5025: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 5026: month=99;
5027: year=9999;
5028: }else{
1.141 brouard 5029: 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);
5030: 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 5031: return 1;
5032: }
5033: anint[j][i]= (double) year;
5034: mint[j][i]= (double)month;
5035: strcpy(line,stra);
5036: } /* ENd Waves */
5037:
5038: cutv(stra, strb,line,' ');
5039: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5040: }
5041: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5042: month=99;
5043: year=9999;
5044: }else{
1.141 brouard 5045: 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);
5046: 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 5047: return 1;
5048: }
5049: andc[i]=(double) year;
5050: moisdc[i]=(double) month;
5051: strcpy(line,stra);
5052:
5053: cutv(stra, strb,line,' ');
5054: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5055: }
1.145 brouard 5056: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 5057: month=99;
5058: year=9999;
5059: }else{
1.141 brouard 5060: 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);
5061: 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 5062: return 1;
5063: }
5064: if (year==9999) {
1.141 brouard 5065: 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);
5066: 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 5067: return 1;
1.126 brouard 5068:
1.136 brouard 5069: }
5070: annais[i]=(double)(year);
5071: moisnais[i]=(double)(month);
5072: strcpy(line,stra);
5073:
5074: cutv(stra, strb,line,' ');
5075: errno=0;
5076: dval=strtod(strb,&endptr);
5077: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5078: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5079: 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 5080: fflush(ficlog);
5081: return 1;
5082: }
5083: weight[i]=dval;
5084: strcpy(line,stra);
5085:
5086: for (j=ncovcol;j>=1;j--){
5087: cutv(stra, strb,line,' ');
5088: if(strb[0]=='.') { /* Missing status */
5089: lval=-1;
5090: }else{
5091: errno=0;
5092: lval=strtol(strb,&endptr,10);
5093: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5094: 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);
5095: 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 5096: return 1;
5097: }
5098: }
5099: if(lval <-1 || lval >1){
1.141 brouard 5100: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5101: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5102: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5103: For example, for multinomial values like 1, 2 and 3,\n \
5104: build V1=0 V2=0 for the reference value (1),\n \
5105: V1=1 V2=0 for (2) \n \
5106: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5107: output of IMaCh is often meaningless.\n \
5108: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5109: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5110: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5111: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5112: For example, for multinomial values like 1, 2 and 3,\n \
5113: build V1=0 V2=0 for the reference value (1),\n \
5114: V1=1 V2=0 for (2) \n \
5115: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5116: output of IMaCh is often meaningless.\n \
5117: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5118: return 1;
5119: }
5120: covar[j][i]=(double)(lval);
5121: strcpy(line,stra);
5122: }
5123: lstra=strlen(stra);
5124:
5125: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5126: stratrunc = &(stra[lstra-9]);
5127: num[i]=atol(stratrunc);
5128: }
5129: else
5130: num[i]=atol(stra);
5131: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5132: 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;}*/
5133:
5134: i=i+1;
5135: } /* End loop reading data */
1.126 brouard 5136:
1.136 brouard 5137: *imax=i-1; /* Number of individuals */
5138: fclose(fic);
5139:
5140: return (0);
1.164 brouard 5141: /* endread: */
1.136 brouard 5142: printf("Exiting readdata: ");
5143: fclose(fic);
5144: return (1);
1.126 brouard 5145:
5146:
5147:
1.136 brouard 5148: }
1.145 brouard 5149: void removespace(char *str) {
5150: char *p1 = str, *p2 = str;
5151: do
5152: while (*p2 == ' ')
5153: p2++;
5154: while (*p1++ = *p2++);
5155: }
5156:
5157: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5158: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5159: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5160: * - cptcovn or number of covariates k of the models excluding age*products =6
5161: * - cptcovage number of covariates with age*products =2
5162: * - cptcovs number of simple covariates
5163: * - 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
5164: * which is a new column after the 9 (ncovcol) variables.
5165: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5166: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5167: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5168: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5169: */
1.136 brouard 5170: {
1.145 brouard 5171: int i, j, k, ks;
1.164 brouard 5172: int j1, k1, k2;
1.136 brouard 5173: char modelsav[80];
1.145 brouard 5174: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5175:
1.145 brouard 5176: /*removespace(model);*/
1.136 brouard 5177: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5178: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5179: j=nbocc(model,'+'); /**< j=Number of '+' */
5180: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5181: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5182: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5183: /* including age products which are counted in cptcovage.
5184: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5185: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5186: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5187: strcpy(modelsav,model);
1.137 brouard 5188: if (strstr(model,"AGE") !=0){
5189: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5190: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5191: return 1;
5192: }
1.141 brouard 5193: if (strstr(model,"v") !=0){
5194: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5195: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5196: return 1;
5197: }
1.136 brouard 5198:
1.145 brouard 5199: /* Design
5200: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5201: * < ncovcol=8 >
5202: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5203: * k= 1 2 3 4 5 6 7 8
5204: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5205: * covar[k,i], value of kth covariate if not including age for individual i:
5206: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5207: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5208: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5209: * Tage[++cptcovage]=k
5210: * if products, new covar are created after ncovcol with k1
5211: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5212: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5213: * 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
5214: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5215: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5216: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5217: * < ncovcol=8 >
5218: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5219: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5220: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5221: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5222: * p Tprod[1]@2={ 6, 5}
5223: *p Tvard[1][1]@4= {7, 8, 5, 6}
5224: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5225: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5226: *How to reorganize?
5227: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5228: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5229: * {2, 1, 4, 8, 5, 6, 3, 7}
5230: * Struct []
5231: */
5232:
1.136 brouard 5233: /* This loop fills the array Tvar from the string 'model'.*/
5234: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5235: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5236: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5237: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5238: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5239: /* k=1 Tvar[1]=2 (from V2) */
5240: /* k=5 Tvar[5] */
5241: /* for (k=1; k<=cptcovn;k++) { */
5242: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5243: /* } */
5244: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5245: /*
5246: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5247: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5248: Tvar[k]=0;
5249: cptcovage=0;
5250: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5251: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5252: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5253: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5254: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5255: /*scanf("%d",i);*/
1.145 brouard 5256: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5257: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5258: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5259: /* covar is not filled and then is empty */
1.136 brouard 5260: cptcovprod--;
1.145 brouard 5261: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5262: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5263: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5264: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5265: /*printf("stre=%s ", stre);*/
1.137 brouard 5266: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5267: cptcovprod--;
1.145 brouard 5268: cutl(stre,strb,strc,'V');
1.136 brouard 5269: Tvar[k]=atoi(stre);
5270: cptcovage++;
5271: Tage[cptcovage]=k;
1.137 brouard 5272: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5273: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5274: cptcovn++;
5275: cptcovprodnoage++;k1++;
5276: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5277: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5278: because this model-covariate is a construction we invent a new column
5279: ncovcol + k1
5280: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5281: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5282: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5283: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5284: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5285: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5286: k2=k2+2;
5287: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5288: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5289: for (i=1; i<=lastobs;i++){
5290: /* Computes the new covariate which is a product of
1.145 brouard 5291: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5292: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5293: }
5294: } /* End age is not in the model */
5295: } /* End if model includes a product */
1.136 brouard 5296: else { /* no more sum */
5297: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5298: /* scanf("%d",i);*/
1.145 brouard 5299: cutl(strd,strc,strb,'V');
5300: ks++; /**< Number of simple covariates */
5301: cptcovn++;
5302: Tvar[k]=atoi(strd);
1.136 brouard 5303: }
1.137 brouard 5304: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5305: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5306: scanf("%d",i);*/
5307: } /* end of loop + */
5308: } /* end model */
5309:
5310: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5311: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5312:
5313: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5314: printf("cptcovprod=%d ", cptcovprod);
5315: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5316:
5317: scanf("%d ",i);*/
5318:
5319:
1.137 brouard 5320: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5321: /*endread:*/
1.136 brouard 5322: printf("Exiting decodemodel: ");
5323: return (1);
5324: }
5325:
5326: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5327: {
5328: int i, m;
5329:
5330: for (i=1; i<=imx; i++) {
5331: for(m=2; (m<= maxwav); m++) {
5332: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5333: anint[m][i]=9999;
5334: s[m][i]=-1;
5335: }
5336: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5337: *nberr++;
5338: 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\n",(int)moisdc[i],(int)andc[i],num[i],i);
5339: 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\n",(int)moisdc[i],(int)andc[i],num[i],i);
5340: s[m][i]=-1;
5341: }
5342: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5343: *nberr++;
5344: 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]);
5345: 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]);
5346: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5347: }
5348: }
5349: }
5350:
5351: for (i=1; i<=imx; i++) {
5352: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5353: for(m=firstpass; (m<= lastpass); m++){
5354: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5355: if (s[m][i] >= nlstate+1) {
5356: if(agedc[i]>0)
5357: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5358: agev[m][i]=agedc[i];
5359: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5360: else {
5361: if ((int)andc[i]!=9999){
5362: nbwarn++;
5363: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5364: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5365: agev[m][i]=-1;
5366: }
5367: }
5368: }
5369: else if(s[m][i] !=9){ /* Standard case, age in fractional
5370: years but with the precision of a month */
5371: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5372: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5373: agev[m][i]=1;
5374: else if(agev[m][i] < *agemin){
5375: *agemin=agev[m][i];
5376: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5377: }
5378: else if(agev[m][i] >*agemax){
5379: *agemax=agev[m][i];
1.156 brouard 5380: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5381: }
5382: /*agev[m][i]=anint[m][i]-annais[i];*/
5383: /* agev[m][i] = age[i]+2*m;*/
5384: }
5385: else { /* =9 */
5386: agev[m][i]=1;
5387: s[m][i]=-1;
5388: }
5389: }
5390: else /*= 0 Unknown */
5391: agev[m][i]=1;
5392: }
5393:
5394: }
5395: for (i=1; i<=imx; i++) {
5396: for(m=firstpass; (m<=lastpass); m++){
5397: if (s[m][i] > (nlstate+ndeath)) {
5398: *nberr++;
5399: 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);
5400: 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);
5401: return 1;
5402: }
5403: }
5404: }
5405:
5406: /*for (i=1; i<=imx; i++){
5407: for (m=firstpass; (m<lastpass); m++){
5408: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5409: }
5410:
5411: }*/
5412:
5413:
1.139 brouard 5414: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5415: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5416:
5417: return (0);
1.164 brouard 5418: /* endread:*/
1.136 brouard 5419: printf("Exiting calandcheckages: ");
5420: return (1);
5421: }
5422:
1.167 ! brouard 5423: syscompilerinfo()
! 5424: {
! 5425: /* #include "syscompilerinfo.h"*/
! 5426: #include <gnu/libc-version.h>
! 5427: #if defined(__GNUC__)
! 5428: # if defined(__GNUC_PATCHLEVEL__)
! 5429: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
! 5430: + __GNUC_MINOR__ * 100 \
! 5431: + __GNUC_PATCHLEVEL__)
! 5432: # else
! 5433: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
! 5434: + __GNUC_MINOR__ * 100)
! 5435: # endif
! 5436: #endif
! 5437:
! 5438: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
! 5439: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
! 5440: // Windows (x64 and x86)
! 5441: #elif __unix__ // all unices, not all compilers
! 5442: // Unix
! 5443: #elif __linux__
! 5444: // linux
! 5445: #elif __APPLE__
! 5446: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
! 5447: #endif
! 5448:
! 5449: /* __MINGW32__ */
! 5450: /* __CYGWIN__ */
! 5451: /* __MINGW64__ */
! 5452: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
! 5453: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
! 5454: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
! 5455: /* _WIN64 // Defined for applications for Win64. */
! 5456: /* _M_X64 // Defined for compilations that target x64 processors. */
! 5457: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
! 5458: #include <stdint.h>
! 5459: #if UINTPTR_MAX == 0xffffffff
! 5460: printf("32-bit \n"); /* 32-bit */
! 5461: #elif UINTPTR_MAX == 0xffffffffffffffff
! 5462: printf("64-bit \n");/* 64-bit */
! 5463: #else
! 5464: printf("wtf-bit \n"); /* wtf */
! 5465: #endif
! 5466:
! 5467: struct utsname sysInfo;
! 5468:
! 5469: if (uname(&sysInfo) != -1) {
! 5470: puts(sysInfo.sysname);
! 5471: puts(sysInfo.nodename);
! 5472: puts(sysInfo.release);
! 5473: puts(sysInfo.version);
! 5474: puts(sysInfo.machine);
! 5475: }
! 5476: else
! 5477: perror("uname() error");
! 5478: printf("GNU C version %d\n", __GNUC_VERSION__);
! 5479: printf("GNU libc version: %s\n", gnu_get_libc_version());
! 5480:
! 5481: }
1.136 brouard 5482:
5483: /***********************************************/
5484: /**************** Main Program *****************/
5485: /***********************************************/
5486:
5487: int main(int argc, char *argv[])
5488: {
5489: #ifdef GSL
5490: const gsl_multimin_fminimizer_type *T;
5491: size_t iteri = 0, it;
5492: int rval = GSL_CONTINUE;
5493: int status = GSL_SUCCESS;
5494: double ssval;
5495: #endif
5496: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5497: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5498:
5499: int jj, ll, li, lj, lk;
1.136 brouard 5500: int numlinepar=0; /* Current linenumber of parameter file */
5501: int itimes;
5502: int NDIM=2;
5503: int vpopbased=0;
5504:
1.164 brouard 5505: char ca[32], cb[32];
1.136 brouard 5506: /* FILE *fichtm; *//* Html File */
5507: /* FILE *ficgp;*/ /*Gnuplot File */
5508: struct stat info;
1.164 brouard 5509: double agedeb;
1.136 brouard 5510: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5511:
1.165 brouard 5512: double fret;
1.136 brouard 5513: double dum; /* Dummy variable */
5514: double ***p3mat;
5515: double ***mobaverage;
1.164 brouard 5516:
5517: char line[MAXLINE];
1.136 brouard 5518: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5519: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5520: char *tok, *val; /* pathtot */
1.136 brouard 5521: int firstobs=1, lastobs=10;
1.164 brouard 5522: int c, h , cpt;
5523: int jl;
5524: int i1, j1, jk, stepsize;
5525: int *tab;
1.136 brouard 5526: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5527: int mobilav=0,popforecast=0;
5528: int hstepm, nhstepm;
5529: int agemortsup;
5530: float sumlpop=0.;
5531: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5532: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5533:
1.164 brouard 5534: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5535: double ftolpl=FTOL;
5536: double **prlim;
5537: double ***param; /* Matrix of parameters */
5538: double *p;
5539: double **matcov; /* Matrix of covariance */
5540: double ***delti3; /* Scale */
5541: double *delti; /* Scale */
5542: double ***eij, ***vareij;
5543: double **varpl; /* Variances of prevalence limits by age */
5544: double *epj, vepp;
1.164 brouard 5545:
1.136 brouard 5546: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5547: double **ximort;
1.145 brouard 5548: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5549: int *dcwave;
5550:
1.164 brouard 5551: char z[1]="c";
1.136 brouard 5552:
5553: /*char *strt;*/
5554: char strtend[80];
1.126 brouard 5555:
1.164 brouard 5556:
1.126 brouard 5557: /* setlocale (LC_ALL, ""); */
5558: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5559: /* textdomain (PACKAGE); */
5560: /* setlocale (LC_CTYPE, ""); */
5561: /* setlocale (LC_MESSAGES, ""); */
5562:
5563: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5564: rstart_time = time(NULL);
5565: /* (void) gettimeofday(&start_time,&tzp);*/
5566: start_time = *localtime(&rstart_time);
1.126 brouard 5567: curr_time=start_time;
1.157 brouard 5568: /*tml = *localtime(&start_time.tm_sec);*/
5569: /* strcpy(strstart,asctime(&tml)); */
5570: strcpy(strstart,asctime(&start_time));
1.126 brouard 5571:
5572: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5573: /* tp.tm_sec = tp.tm_sec +86400; */
5574: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5575: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5576: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5577: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5578: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5579: /* strt=asctime(&tmg); */
5580: /* printf("Time(after) =%s",strstart); */
5581: /* (void) time (&time_value);
5582: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5583: * tm = *localtime(&time_value);
5584: * strstart=asctime(&tm);
5585: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5586: */
5587:
5588: nberr=0; /* Number of errors and warnings */
5589: nbwarn=0;
5590: getcwd(pathcd, size);
5591:
5592: printf("\n%s\n%s",version,fullversion);
5593: if(argc <=1){
5594: printf("\nEnter the parameter file name: ");
5595: fgets(pathr,FILENAMELENGTH,stdin);
5596: i=strlen(pathr);
5597: if(pathr[i-1]=='\n')
5598: pathr[i-1]='\0';
1.156 brouard 5599: i=strlen(pathr);
5600: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5601: pathr[i-1]='\0';
1.126 brouard 5602: for (tok = pathr; tok != NULL; ){
5603: printf("Pathr |%s|\n",pathr);
5604: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5605: printf("val= |%s| pathr=%s\n",val,pathr);
5606: strcpy (pathtot, val);
5607: if(pathr[0] == '\0') break; /* Dirty */
5608: }
5609: }
5610: else{
5611: strcpy(pathtot,argv[1]);
5612: }
5613: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5614: /*cygwin_split_path(pathtot,path,optionfile);
5615: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5616: /* cutv(path,optionfile,pathtot,'\\');*/
5617:
5618: /* Split argv[0], imach program to get pathimach */
5619: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5620: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5621: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5622: /* strcpy(pathimach,argv[0]); */
5623: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5624: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5625: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5626: chdir(path); /* Can be a relative path */
5627: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5628: printf("Current directory %s!\n",pathcd);
5629: strcpy(command,"mkdir ");
5630: strcat(command,optionfilefiname);
5631: if((outcmd=system(command)) != 0){
5632: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5633: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5634: /* fclose(ficlog); */
5635: /* exit(1); */
5636: }
5637: /* if((imk=mkdir(optionfilefiname))<0){ */
5638: /* perror("mkdir"); */
5639: /* } */
5640:
5641: /*-------- arguments in the command line --------*/
5642:
5643: /* Log file */
5644: strcat(filelog, optionfilefiname);
5645: strcat(filelog,".log"); /* */
5646: if((ficlog=fopen(filelog,"w"))==NULL) {
5647: printf("Problem with logfile %s\n",filelog);
5648: goto end;
5649: }
5650: fprintf(ficlog,"Log filename:%s\n",filelog);
5651: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5652: fprintf(ficlog,"\nEnter the parameter file name: \n");
5653: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5654: path=%s \n\
5655: optionfile=%s\n\
5656: optionfilext=%s\n\
1.156 brouard 5657: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5658:
1.167 ! brouard 5659: syscompilerinfo();
! 5660:
1.126 brouard 5661: printf("Local time (at start):%s",strstart);
5662: fprintf(ficlog,"Local time (at start): %s",strstart);
5663: fflush(ficlog);
5664: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5665: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5666:
5667: /* */
5668: strcpy(fileres,"r");
5669: strcat(fileres, optionfilefiname);
5670: strcat(fileres,".txt"); /* Other files have txt extension */
5671:
5672: /*---------arguments file --------*/
5673:
5674: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5675: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5676: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5677: fflush(ficlog);
1.149 brouard 5678: /* goto end; */
5679: exit(70);
1.126 brouard 5680: }
5681:
5682:
5683:
5684: strcpy(filereso,"o");
5685: strcat(filereso,fileres);
5686: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5687: printf("Problem with Output resultfile: %s\n", filereso);
5688: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5689: fflush(ficlog);
5690: goto end;
5691: }
5692:
5693: /* Reads comments: lines beginning with '#' */
5694: numlinepar=0;
5695: while((c=getc(ficpar))=='#' && c!= EOF){
5696: ungetc(c,ficpar);
5697: fgets(line, MAXLINE, ficpar);
5698: numlinepar++;
1.141 brouard 5699: fputs(line,stdout);
1.126 brouard 5700: fputs(line,ficparo);
5701: fputs(line,ficlog);
5702: }
5703: ungetc(c,ficpar);
5704:
5705: 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);
5706: numlinepar++;
5707: 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);
5708: 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);
5709: 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);
5710: fflush(ficlog);
5711: while((c=getc(ficpar))=='#' && c!= EOF){
5712: ungetc(c,ficpar);
5713: fgets(line, MAXLINE, ficpar);
5714: numlinepar++;
1.141 brouard 5715: fputs(line, stdout);
5716: //puts(line);
1.126 brouard 5717: fputs(line,ficparo);
5718: fputs(line,ficlog);
5719: }
5720: ungetc(c,ficpar);
5721:
5722:
1.145 brouard 5723: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5724: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5725: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5726: v1+v2*age+v2*v3 makes cptcovn = 3
5727: */
5728: if (strlen(model)>1)
1.145 brouard 5729: 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*/
5730: else
5731: ncovmodel=2;
1.126 brouard 5732: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5733: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5734: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5735: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5736: 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);
5737: 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);
5738: fflush(stdout);
5739: fclose (ficlog);
5740: goto end;
5741: }
1.126 brouard 5742: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5743: delti=delti3[1][1];
5744: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5745: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5746: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5747: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5748: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5749: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5750: fclose (ficparo);
5751: fclose (ficlog);
5752: goto end;
5753: exit(0);
5754: }
5755: else if(mle==-3) {
5756: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5757: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5758: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5759: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5760: matcov=matrix(1,npar,1,npar);
5761: }
5762: else{
1.145 brouard 5763: /* Read guessed parameters */
1.126 brouard 5764: /* Reads comments: lines beginning with '#' */
5765: while((c=getc(ficpar))=='#' && c!= EOF){
5766: ungetc(c,ficpar);
5767: fgets(line, MAXLINE, ficpar);
5768: numlinepar++;
1.141 brouard 5769: fputs(line,stdout);
1.126 brouard 5770: fputs(line,ficparo);
5771: fputs(line,ficlog);
5772: }
5773: ungetc(c,ficpar);
5774:
5775: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5776: for(i=1; i <=nlstate; i++){
5777: j=0;
5778: for(jj=1; jj <=nlstate+ndeath; jj++){
5779: if(jj==i) continue;
5780: j++;
5781: fscanf(ficpar,"%1d%1d",&i1,&j1);
5782: if ((i1 != i) && (j1 != j)){
5783: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5784: It might be a problem of design; if ncovcol and the model are correct\n \
5785: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5786: exit(1);
5787: }
5788: fprintf(ficparo,"%1d%1d",i1,j1);
5789: if(mle==1)
5790: printf("%1d%1d",i,j);
5791: fprintf(ficlog,"%1d%1d",i,j);
5792: for(k=1; k<=ncovmodel;k++){
5793: fscanf(ficpar," %lf",¶m[i][j][k]);
5794: if(mle==1){
5795: printf(" %lf",param[i][j][k]);
5796: fprintf(ficlog," %lf",param[i][j][k]);
5797: }
5798: else
5799: fprintf(ficlog," %lf",param[i][j][k]);
5800: fprintf(ficparo," %lf",param[i][j][k]);
5801: }
5802: fscanf(ficpar,"\n");
5803: numlinepar++;
5804: if(mle==1)
5805: printf("\n");
5806: fprintf(ficlog,"\n");
5807: fprintf(ficparo,"\n");
5808: }
5809: }
5810: fflush(ficlog);
5811:
1.145 brouard 5812: /* Reads scales values */
1.126 brouard 5813: p=param[1][1];
5814:
5815: /* Reads comments: lines beginning with '#' */
5816: while((c=getc(ficpar))=='#' && c!= EOF){
5817: ungetc(c,ficpar);
5818: fgets(line, MAXLINE, ficpar);
5819: numlinepar++;
1.141 brouard 5820: fputs(line,stdout);
1.126 brouard 5821: fputs(line,ficparo);
5822: fputs(line,ficlog);
5823: }
5824: ungetc(c,ficpar);
5825:
5826: for(i=1; i <=nlstate; i++){
5827: for(j=1; j <=nlstate+ndeath-1; j++){
5828: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 5829: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5830: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5831: exit(1);
5832: }
5833: printf("%1d%1d",i,j);
5834: fprintf(ficparo,"%1d%1d",i1,j1);
5835: fprintf(ficlog,"%1d%1d",i1,j1);
5836: for(k=1; k<=ncovmodel;k++){
5837: fscanf(ficpar,"%le",&delti3[i][j][k]);
5838: printf(" %le",delti3[i][j][k]);
5839: fprintf(ficparo," %le",delti3[i][j][k]);
5840: fprintf(ficlog," %le",delti3[i][j][k]);
5841: }
5842: fscanf(ficpar,"\n");
5843: numlinepar++;
5844: printf("\n");
5845: fprintf(ficparo,"\n");
5846: fprintf(ficlog,"\n");
5847: }
5848: }
5849: fflush(ficlog);
5850:
1.145 brouard 5851: /* Reads covariance matrix */
1.126 brouard 5852: delti=delti3[1][1];
5853:
5854:
5855: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5856:
5857: /* Reads comments: lines beginning with '#' */
5858: while((c=getc(ficpar))=='#' && c!= EOF){
5859: ungetc(c,ficpar);
5860: fgets(line, MAXLINE, ficpar);
5861: numlinepar++;
1.141 brouard 5862: fputs(line,stdout);
1.126 brouard 5863: fputs(line,ficparo);
5864: fputs(line,ficlog);
5865: }
5866: ungetc(c,ficpar);
5867:
5868: matcov=matrix(1,npar,1,npar);
1.131 brouard 5869: for(i=1; i <=npar; i++)
5870: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5871:
1.126 brouard 5872: for(i=1; i <=npar; i++){
1.145 brouard 5873: fscanf(ficpar,"%s",str);
1.126 brouard 5874: if(mle==1)
5875: printf("%s",str);
5876: fprintf(ficlog,"%s",str);
5877: fprintf(ficparo,"%s",str);
5878: for(j=1; j <=i; j++){
5879: fscanf(ficpar," %le",&matcov[i][j]);
5880: if(mle==1){
5881: printf(" %.5le",matcov[i][j]);
5882: }
5883: fprintf(ficlog," %.5le",matcov[i][j]);
5884: fprintf(ficparo," %.5le",matcov[i][j]);
5885: }
5886: fscanf(ficpar,"\n");
5887: numlinepar++;
5888: if(mle==1)
5889: printf("\n");
5890: fprintf(ficlog,"\n");
5891: fprintf(ficparo,"\n");
5892: }
5893: for(i=1; i <=npar; i++)
5894: for(j=i+1;j<=npar;j++)
5895: matcov[i][j]=matcov[j][i];
5896:
5897: if(mle==1)
5898: printf("\n");
5899: fprintf(ficlog,"\n");
5900:
5901: fflush(ficlog);
5902:
5903: /*-------- Rewriting parameter file ----------*/
5904: strcpy(rfileres,"r"); /* "Rparameterfile */
5905: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5906: strcat(rfileres,"."); /* */
5907: strcat(rfileres,optionfilext); /* Other files have txt extension */
5908: if((ficres =fopen(rfileres,"w"))==NULL) {
5909: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5910: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5911: }
5912: fprintf(ficres,"#%s\n",version);
5913: } /* End of mle != -3 */
5914:
5915:
5916: n= lastobs;
5917: num=lvector(1,n);
5918: moisnais=vector(1,n);
5919: annais=vector(1,n);
5920: moisdc=vector(1,n);
5921: andc=vector(1,n);
5922: agedc=vector(1,n);
5923: cod=ivector(1,n);
5924: weight=vector(1,n);
5925: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5926: mint=matrix(1,maxwav,1,n);
5927: anint=matrix(1,maxwav,1,n);
1.131 brouard 5928: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5929: tab=ivector(1,NCOVMAX);
1.144 brouard 5930: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5931:
1.136 brouard 5932: /* Reads data from file datafile */
5933: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5934: goto end;
5935:
5936: /* Calculation of the number of parameters from char model */
1.137 brouard 5937: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5938: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5939: k=3 V4 Tvar[k=3]= 4 (from V4)
5940: k=2 V1 Tvar[k=2]= 1 (from V1)
5941: k=1 Tvar[1]=2 (from V2)
5942: */
5943: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5944: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5945: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5946: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5947: */
5948: /* For model-covariate k tells which data-covariate to use but
5949: because this model-covariate is a construction we invent a new column
5950: ncovcol + k1
5951: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5952: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5953: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5954: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5955: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5956: */
1.145 brouard 5957: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5958: 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 5959: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5960: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5961: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5962: 4 covariates (3 plus signs)
5963: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5964: */
1.136 brouard 5965:
5966: if(decodemodel(model, lastobs) == 1)
5967: goto end;
5968:
1.137 brouard 5969: if((double)(lastobs-imx)/(double)imx > 1.10){
5970: nbwarn++;
5971: 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);
5972: 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);
5973: }
1.136 brouard 5974: /* if(mle==1){*/
1.137 brouard 5975: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5976: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5977: }
5978:
5979: /*-calculation of age at interview from date of interview and age at death -*/
5980: agev=matrix(1,maxwav,1,imx);
5981:
5982: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5983: goto end;
5984:
1.126 brouard 5985:
1.136 brouard 5986: agegomp=(int)agemin;
5987: free_vector(moisnais,1,n);
5988: free_vector(annais,1,n);
1.126 brouard 5989: /* free_matrix(mint,1,maxwav,1,n);
5990: free_matrix(anint,1,maxwav,1,n);*/
5991: free_vector(moisdc,1,n);
5992: free_vector(andc,1,n);
1.145 brouard 5993: /* */
5994:
1.126 brouard 5995: wav=ivector(1,imx);
5996: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5997: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5998: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5999:
6000: /* Concatenates waves */
6001: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6002: /* */
6003:
1.126 brouard 6004: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6005:
6006: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6007: ncodemax[1]=1;
1.145 brouard 6008: Ndum =ivector(-1,NCOVMAX);
6009: if (ncovmodel > 2)
6010: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6011:
6012: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6013: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6014: h=0;
6015:
6016:
6017: /*if (cptcovn > 0) */
1.126 brouard 6018:
1.145 brouard 6019:
1.126 brouard 6020: m=pow(2,cptcoveff);
6021:
1.131 brouard 6022: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6023: 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 */
6024: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6025: 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 6026: h++;
1.141 brouard 6027: if (h>m)
1.136 brouard 6028: h=1;
1.144 brouard 6029: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6030: * h 1 2 3 4
6031: *______________________________
6032: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6033: * 2 2 1 1 1
6034: * 3 i=2 1 2 1 1
6035: * 4 2 2 1 1
6036: * 5 i=3 1 i=2 1 2 1
6037: * 6 2 1 2 1
6038: * 7 i=4 1 2 2 1
6039: * 8 2 2 2 1
6040: * 9 i=5 1 i=3 1 i=2 1 1
6041: * 10 2 1 1 1
6042: * 11 i=6 1 2 1 1
6043: * 12 2 2 1 1
6044: * 13 i=7 1 i=4 1 2 1
6045: * 14 2 1 2 1
6046: * 15 i=8 1 2 2 1
6047: * 16 2 2 2 1
6048: */
1.141 brouard 6049: codtab[h][k]=j;
1.145 brouard 6050: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6051: 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 6052: }
6053: }
6054: }
6055: }
6056: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6057: codtab[1][2]=1;codtab[2][2]=2; */
6058: /* for(i=1; i <=m ;i++){
6059: for(k=1; k <=cptcovn; k++){
1.131 brouard 6060: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6061: }
6062: printf("\n");
6063: }
6064: scanf("%d",i);*/
1.145 brouard 6065:
6066: free_ivector(Ndum,-1,NCOVMAX);
6067:
6068:
1.126 brouard 6069:
6070: /*------------ gnuplot -------------*/
6071: strcpy(optionfilegnuplot,optionfilefiname);
6072: if(mle==-3)
6073: strcat(optionfilegnuplot,"-mort");
6074: strcat(optionfilegnuplot,".gp");
6075:
6076: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6077: printf("Problem with file %s",optionfilegnuplot);
6078: }
6079: else{
6080: fprintf(ficgp,"\n# %s\n", version);
6081: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6082: //fprintf(ficgp,"set missing 'NaNq'\n");
6083: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6084: }
6085: /* fclose(ficgp);*/
6086: /*--------- index.htm --------*/
6087:
6088: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6089: if(mle==-3)
6090: strcat(optionfilehtm,"-mort");
6091: strcat(optionfilehtm,".htm");
6092: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6093: printf("Problem with %s \n",optionfilehtm);
6094: exit(0);
1.126 brouard 6095: }
6096:
6097: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6098: strcat(optionfilehtmcov,"-cov.htm");
6099: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6100: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6101: }
6102: else{
6103: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6104: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6105: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6106: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6107: }
6108:
6109: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6110: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6111: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6112: \n\
6113: <hr size=\"2\" color=\"#EC5E5E\">\
6114: <ul><li><h4>Parameter files</h4>\n\
6115: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6116: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6117: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6118: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6119: - Date and time at start: %s</ul>\n",\
6120: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6121: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6122: fileres,fileres,\
6123: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6124: fflush(fichtm);
6125:
6126: strcpy(pathr,path);
6127: strcat(pathr,optionfilefiname);
6128: chdir(optionfilefiname); /* Move to directory named optionfile */
6129:
6130: /* Calculates basic frequencies. Computes observed prevalence at single age
6131: and prints on file fileres'p'. */
6132: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6133:
6134: fprintf(fichtm,"\n");
6135: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6136: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6137: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6138: imx,agemin,agemax,jmin,jmax,jmean);
6139: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6140: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6141: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6142: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6143: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6144:
6145:
6146: /* For Powell, parameters are in a vector p[] starting at p[1]
6147: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6148: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6149:
6150: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6151:
6152: if (mle==-3){
1.136 brouard 6153: ximort=matrix(1,NDIM,1,NDIM);
6154: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6155: cens=ivector(1,n);
6156: ageexmed=vector(1,n);
6157: agecens=vector(1,n);
6158: dcwave=ivector(1,n);
6159:
6160: for (i=1; i<=imx; i++){
6161: dcwave[i]=-1;
6162: for (m=firstpass; m<=lastpass; m++)
6163: if (s[m][i]>nlstate) {
6164: dcwave[i]=m;
6165: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6166: break;
6167: }
6168: }
6169:
6170: for (i=1; i<=imx; i++) {
6171: if (wav[i]>0){
6172: ageexmed[i]=agev[mw[1][i]][i];
6173: j=wav[i];
6174: agecens[i]=1.;
6175:
6176: if (ageexmed[i]> 1 && wav[i] > 0){
6177: agecens[i]=agev[mw[j][i]][i];
6178: cens[i]= 1;
6179: }else if (ageexmed[i]< 1)
6180: cens[i]= -1;
6181: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6182: cens[i]=0 ;
6183: }
6184: else cens[i]=-1;
6185: }
6186:
6187: for (i=1;i<=NDIM;i++) {
6188: for (j=1;j<=NDIM;j++)
6189: ximort[i][j]=(i == j ? 1.0 : 0.0);
6190: }
6191:
1.145 brouard 6192: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6193: /*printf("%lf %lf", p[1], p[2]);*/
6194:
6195:
1.136 brouard 6196: #ifdef GSL
6197: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6198: #else
1.126 brouard 6199: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6200: #endif
1.126 brouard 6201: strcpy(filerespow,"pow-mort");
6202: strcat(filerespow,fileres);
6203: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6204: printf("Problem with resultfile: %s\n", filerespow);
6205: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6206: }
1.136 brouard 6207: #ifdef GSL
6208: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6209: #else
1.126 brouard 6210: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6211: #endif
1.126 brouard 6212: /* for (i=1;i<=nlstate;i++)
6213: for(j=1;j<=nlstate+ndeath;j++)
6214: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6215: */
6216: fprintf(ficrespow,"\n");
1.136 brouard 6217: #ifdef GSL
6218: /* gsl starts here */
6219: T = gsl_multimin_fminimizer_nmsimplex;
6220: gsl_multimin_fminimizer *sfm = NULL;
6221: gsl_vector *ss, *x;
6222: gsl_multimin_function minex_func;
6223:
6224: /* Initial vertex size vector */
6225: ss = gsl_vector_alloc (NDIM);
6226:
6227: if (ss == NULL){
6228: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6229: }
6230: /* Set all step sizes to 1 */
6231: gsl_vector_set_all (ss, 0.001);
6232:
6233: /* Starting point */
1.126 brouard 6234:
1.136 brouard 6235: x = gsl_vector_alloc (NDIM);
6236:
6237: if (x == NULL){
6238: gsl_vector_free(ss);
6239: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6240: }
6241:
6242: /* Initialize method and iterate */
6243: /* p[1]=0.0268; p[NDIM]=0.083; */
6244: /* gsl_vector_set(x, 0, 0.0268); */
6245: /* gsl_vector_set(x, 1, 0.083); */
6246: gsl_vector_set(x, 0, p[1]);
6247: gsl_vector_set(x, 1, p[2]);
6248:
6249: minex_func.f = &gompertz_f;
6250: minex_func.n = NDIM;
6251: minex_func.params = (void *)&p; /* ??? */
6252:
6253: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6254: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6255:
6256: printf("Iterations beginning .....\n\n");
6257: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6258:
6259: iteri=0;
6260: while (rval == GSL_CONTINUE){
6261: iteri++;
6262: status = gsl_multimin_fminimizer_iterate(sfm);
6263:
6264: if (status) printf("error: %s\n", gsl_strerror (status));
6265: fflush(0);
6266:
6267: if (status)
6268: break;
6269:
6270: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6271: ssval = gsl_multimin_fminimizer_size (sfm);
6272:
6273: if (rval == GSL_SUCCESS)
6274: printf ("converged to a local maximum at\n");
6275:
6276: printf("%5d ", iteri);
6277: for (it = 0; it < NDIM; it++){
6278: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6279: }
6280: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6281: }
6282:
6283: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6284:
6285: gsl_vector_free(x); /* initial values */
6286: gsl_vector_free(ss); /* inital step size */
6287: for (it=0; it<NDIM; it++){
6288: p[it+1]=gsl_vector_get(sfm->x,it);
6289: fprintf(ficrespow," %.12lf", p[it]);
6290: }
6291: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6292: #endif
6293: #ifdef POWELL
6294: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6295: #endif
1.126 brouard 6296: fclose(ficrespow);
6297:
6298: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6299:
6300: for(i=1; i <=NDIM; i++)
6301: for(j=i+1;j<=NDIM;j++)
6302: matcov[i][j]=matcov[j][i];
6303:
6304: printf("\nCovariance matrix\n ");
6305: for(i=1; i <=NDIM; i++) {
6306: for(j=1;j<=NDIM;j++){
6307: printf("%f ",matcov[i][j]);
6308: }
6309: printf("\n ");
6310: }
6311:
6312: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6313: for (i=1;i<=NDIM;i++)
6314: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6315:
6316: lsurv=vector(1,AGESUP);
6317: lpop=vector(1,AGESUP);
6318: tpop=vector(1,AGESUP);
6319: lsurv[agegomp]=100000;
6320:
6321: for (k=agegomp;k<=AGESUP;k++) {
6322: agemortsup=k;
6323: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6324: }
6325:
6326: for (k=agegomp;k<agemortsup;k++)
6327: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6328:
6329: for (k=agegomp;k<agemortsup;k++){
6330: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6331: sumlpop=sumlpop+lpop[k];
6332: }
6333:
6334: tpop[agegomp]=sumlpop;
6335: for (k=agegomp;k<(agemortsup-3);k++){
6336: /* tpop[k+1]=2;*/
6337: tpop[k+1]=tpop[k]-lpop[k];
6338: }
6339:
6340:
6341: printf("\nAge lx qx dx Lx Tx e(x)\n");
6342: for (k=agegomp;k<(agemortsup-2);k++)
6343: 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]);
6344:
6345:
6346: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6347: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6348:
6349: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6350: stepm, weightopt,\
6351: model,imx,p,matcov,agemortsup);
6352:
6353: free_vector(lsurv,1,AGESUP);
6354: free_vector(lpop,1,AGESUP);
6355: free_vector(tpop,1,AGESUP);
1.136 brouard 6356: #ifdef GSL
6357: free_ivector(cens,1,n);
6358: free_vector(agecens,1,n);
6359: free_ivector(dcwave,1,n);
6360: free_matrix(ximort,1,NDIM,1,NDIM);
6361: #endif
1.126 brouard 6362: } /* Endof if mle==-3 */
6363:
6364: else{ /* For mle >=1 */
1.132 brouard 6365: globpr=0;/* debug */
6366: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6367: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6368: for (k=1; k<=npar;k++)
6369: printf(" %d %8.5f",k,p[k]);
6370: printf("\n");
6371: globpr=1; /* to print the contributions */
6372: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6373: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6374: for (k=1; k<=npar;k++)
6375: printf(" %d %8.5f",k,p[k]);
6376: printf("\n");
6377: if(mle>=1){ /* Could be 1 or 2 */
6378: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6379: }
6380:
6381: /*--------- results files --------------*/
6382: 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);
6383:
6384:
6385: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6386: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6387: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6388: for(i=1,jk=1; i <=nlstate; i++){
6389: for(k=1; k <=(nlstate+ndeath); k++){
6390: if (k != i) {
6391: printf("%d%d ",i,k);
6392: fprintf(ficlog,"%d%d ",i,k);
6393: fprintf(ficres,"%1d%1d ",i,k);
6394: for(j=1; j <=ncovmodel; j++){
6395: printf("%lf ",p[jk]);
6396: fprintf(ficlog,"%lf ",p[jk]);
6397: fprintf(ficres,"%lf ",p[jk]);
6398: jk++;
6399: }
6400: printf("\n");
6401: fprintf(ficlog,"\n");
6402: fprintf(ficres,"\n");
6403: }
6404: }
6405: }
6406: if(mle!=0){
6407: /* Computing hessian and covariance matrix */
6408: ftolhess=ftol; /* Usually correct */
6409: hesscov(matcov, p, npar, delti, ftolhess, func);
6410: }
6411: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6412: printf("# Scales (for hessian or gradient estimation)\n");
6413: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6414: for(i=1,jk=1; i <=nlstate; i++){
6415: for(j=1; j <=nlstate+ndeath; j++){
6416: if (j!=i) {
6417: fprintf(ficres,"%1d%1d",i,j);
6418: printf("%1d%1d",i,j);
6419: fprintf(ficlog,"%1d%1d",i,j);
6420: for(k=1; k<=ncovmodel;k++){
6421: printf(" %.5e",delti[jk]);
6422: fprintf(ficlog," %.5e",delti[jk]);
6423: fprintf(ficres," %.5e",delti[jk]);
6424: jk++;
6425: }
6426: printf("\n");
6427: fprintf(ficlog,"\n");
6428: fprintf(ficres,"\n");
6429: }
6430: }
6431: }
6432:
6433: 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");
6434: if(mle>=1)
6435: 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");
6436: 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");
6437: /* # 121 Var(a12)\n\ */
6438: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6439: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6440: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6441: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6442: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6443: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6444: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6445:
6446:
6447: /* Just to have a covariance matrix which will be more understandable
6448: even is we still don't want to manage dictionary of variables
6449: */
6450: for(itimes=1;itimes<=2;itimes++){
6451: jj=0;
6452: for(i=1; i <=nlstate; i++){
6453: for(j=1; j <=nlstate+ndeath; j++){
6454: if(j==i) continue;
6455: for(k=1; k<=ncovmodel;k++){
6456: jj++;
6457: ca[0]= k+'a'-1;ca[1]='\0';
6458: if(itimes==1){
6459: if(mle>=1)
6460: printf("#%1d%1d%d",i,j,k);
6461: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6462: fprintf(ficres,"#%1d%1d%d",i,j,k);
6463: }else{
6464: if(mle>=1)
6465: printf("%1d%1d%d",i,j,k);
6466: fprintf(ficlog,"%1d%1d%d",i,j,k);
6467: fprintf(ficres,"%1d%1d%d",i,j,k);
6468: }
6469: ll=0;
6470: for(li=1;li <=nlstate; li++){
6471: for(lj=1;lj <=nlstate+ndeath; lj++){
6472: if(lj==li) continue;
6473: for(lk=1;lk<=ncovmodel;lk++){
6474: ll++;
6475: if(ll<=jj){
6476: cb[0]= lk +'a'-1;cb[1]='\0';
6477: if(ll<jj){
6478: if(itimes==1){
6479: if(mle>=1)
6480: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6481: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6482: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6483: }else{
6484: if(mle>=1)
6485: printf(" %.5e",matcov[jj][ll]);
6486: fprintf(ficlog," %.5e",matcov[jj][ll]);
6487: fprintf(ficres," %.5e",matcov[jj][ll]);
6488: }
6489: }else{
6490: if(itimes==1){
6491: if(mle>=1)
6492: printf(" Var(%s%1d%1d)",ca,i,j);
6493: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6494: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6495: }else{
6496: if(mle>=1)
6497: printf(" %.5e",matcov[jj][ll]);
6498: fprintf(ficlog," %.5e",matcov[jj][ll]);
6499: fprintf(ficres," %.5e",matcov[jj][ll]);
6500: }
6501: }
6502: }
6503: } /* end lk */
6504: } /* end lj */
6505: } /* end li */
6506: if(mle>=1)
6507: printf("\n");
6508: fprintf(ficlog,"\n");
6509: fprintf(ficres,"\n");
6510: numlinepar++;
6511: } /* end k*/
6512: } /*end j */
6513: } /* end i */
6514: } /* end itimes */
6515:
6516: fflush(ficlog);
6517: fflush(ficres);
6518:
6519: while((c=getc(ficpar))=='#' && c!= EOF){
6520: ungetc(c,ficpar);
6521: fgets(line, MAXLINE, ficpar);
1.141 brouard 6522: fputs(line,stdout);
1.126 brouard 6523: fputs(line,ficparo);
6524: }
6525: ungetc(c,ficpar);
6526:
6527: estepm=0;
6528: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6529: if (estepm==0 || estepm < stepm) estepm=stepm;
6530: if (fage <= 2) {
6531: bage = ageminpar;
6532: fage = agemaxpar;
6533: }
6534:
6535: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6536: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6537: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6538:
6539: while((c=getc(ficpar))=='#' && c!= EOF){
6540: ungetc(c,ficpar);
6541: fgets(line, MAXLINE, ficpar);
1.141 brouard 6542: fputs(line,stdout);
1.126 brouard 6543: fputs(line,ficparo);
6544: }
6545: ungetc(c,ficpar);
6546:
6547: 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);
6548: 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);
6549: 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);
6550: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6551: 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);
6552:
6553: while((c=getc(ficpar))=='#' && c!= EOF){
6554: ungetc(c,ficpar);
6555: fgets(line, MAXLINE, ficpar);
1.141 brouard 6556: fputs(line,stdout);
1.126 brouard 6557: fputs(line,ficparo);
6558: }
6559: ungetc(c,ficpar);
6560:
6561:
6562: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6563: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6564:
6565: fscanf(ficpar,"pop_based=%d\n",&popbased);
6566: fprintf(ficparo,"pop_based=%d\n",popbased);
6567: fprintf(ficres,"pop_based=%d\n",popbased);
6568:
6569: while((c=getc(ficpar))=='#' && c!= EOF){
6570: ungetc(c,ficpar);
6571: fgets(line, MAXLINE, ficpar);
1.141 brouard 6572: fputs(line,stdout);
1.126 brouard 6573: fputs(line,ficparo);
6574: }
6575: ungetc(c,ficpar);
6576:
6577: 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);
6578: 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);
6579: 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);
6580: 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);
6581: 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);
6582: /* day and month of proj2 are not used but only year anproj2.*/
6583:
6584:
6585:
1.145 brouard 6586: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6587: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6588:
6589: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6590: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6591:
6592: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6593: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6594: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6595:
6596: /*------------ free_vector -------------*/
6597: /* chdir(path); */
6598:
6599: free_ivector(wav,1,imx);
6600: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6601: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6602: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6603: free_lvector(num,1,n);
6604: free_vector(agedc,1,n);
6605: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6606: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6607: fclose(ficparo);
6608: fclose(ficres);
6609:
6610:
6611: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6612: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6613: fclose(ficrespl);
6614:
1.145 brouard 6615: #ifdef FREEEXIT2
6616: #include "freeexit2.h"
6617: #endif
6618:
1.126 brouard 6619: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6620: #include "hpijx.h"
6621: fclose(ficrespij);
1.126 brouard 6622:
1.145 brouard 6623: /*-------------- Variance of one-step probabilities---*/
6624: k=1;
1.126 brouard 6625: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6626:
6627:
6628: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6629: for(i=1;i<=AGESUP;i++)
6630: for(j=1;j<=NCOVMAX;j++)
6631: for(k=1;k<=NCOVMAX;k++)
6632: probs[i][j][k]=0.;
6633:
6634: /*---------- Forecasting ------------------*/
6635: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6636: if(prevfcast==1){
6637: /* if(stepm ==1){*/
6638: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6639: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6640: /* } */
6641: /* else{ */
6642: /* erreur=108; */
6643: /* 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); */
6644: /* 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); */
6645: /* } */
6646: }
6647:
6648:
1.127 brouard 6649: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6650:
6651: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6652: /* 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",\
6653: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6654: */
1.126 brouard 6655:
1.127 brouard 6656: if (mobilav!=0) {
6657: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6658: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6659: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6660: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6661: }
1.126 brouard 6662: }
6663:
6664:
1.127 brouard 6665: /*---------- Health expectancies, no variances ------------*/
6666:
1.126 brouard 6667: strcpy(filerese,"e");
6668: strcat(filerese,fileres);
6669: if((ficreseij=fopen(filerese,"w"))==NULL) {
6670: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6671: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6672: }
6673: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6674: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6675: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6676: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6677:
6678: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6679: fprintf(ficreseij,"\n#****** ");
6680: for(j=1;j<=cptcoveff;j++) {
6681: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6682: }
6683: fprintf(ficreseij,"******\n");
6684:
6685: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6686: oldm=oldms;savm=savms;
6687: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6688:
6689: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6690: /*}*/
1.127 brouard 6691: }
6692: fclose(ficreseij);
6693:
6694:
6695: /*---------- Health expectancies and variances ------------*/
6696:
6697:
6698: strcpy(filerest,"t");
6699: strcat(filerest,fileres);
6700: if((ficrest=fopen(filerest,"w"))==NULL) {
6701: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6702: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6703: }
6704: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6705: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6706:
1.126 brouard 6707:
6708: strcpy(fileresstde,"stde");
6709: strcat(fileresstde,fileres);
6710: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6711: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6712: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6713: }
6714: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6715: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6716:
6717: strcpy(filerescve,"cve");
6718: strcat(filerescve,fileres);
6719: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6720: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6721: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6722: }
6723: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6724: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6725:
6726: strcpy(fileresv,"v");
6727: strcat(fileresv,fileres);
6728: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6729: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6730: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6731: }
6732: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6733: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6734:
1.145 brouard 6735: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6736: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6737:
6738: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6739: fprintf(ficrest,"\n#****** ");
1.126 brouard 6740: for(j=1;j<=cptcoveff;j++)
6741: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6742: fprintf(ficrest,"******\n");
6743:
6744: fprintf(ficresstdeij,"\n#****** ");
6745: fprintf(ficrescveij,"\n#****** ");
6746: for(j=1;j<=cptcoveff;j++) {
6747: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6748: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6749: }
6750: fprintf(ficresstdeij,"******\n");
6751: fprintf(ficrescveij,"******\n");
6752:
6753: fprintf(ficresvij,"\n#****** ");
6754: for(j=1;j<=cptcoveff;j++)
6755: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6756: fprintf(ficresvij,"******\n");
6757:
6758: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6759: oldm=oldms;savm=savms;
1.127 brouard 6760: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6761: /*
6762: */
6763: /* goto endfree; */
1.126 brouard 6764:
6765: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6766: pstamp(ficrest);
1.145 brouard 6767:
6768:
1.128 brouard 6769: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6770: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6771: cptcod= 0; /* To be deleted */
6772: 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 6773: 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 6774: if(vpopbased==1)
6775: 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);
6776: else
6777: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6778: fprintf(ficrest,"# Age e.. (std) ");
6779: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6780: fprintf(ficrest,"\n");
1.126 brouard 6781:
1.128 brouard 6782: epj=vector(1,nlstate+1);
6783: for(age=bage; age <=fage ;age++){
6784: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6785: if (vpopbased==1) {
6786: if(mobilav ==0){
6787: for(i=1; i<=nlstate;i++)
6788: prlim[i][i]=probs[(int)age][i][k];
6789: }else{ /* mobilav */
6790: for(i=1; i<=nlstate;i++)
6791: prlim[i][i]=mobaverage[(int)age][i][k];
6792: }
1.126 brouard 6793: }
6794:
1.128 brouard 6795: fprintf(ficrest," %4.0f",age);
6796: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6797: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6798: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6799: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6800: }
6801: epj[nlstate+1] +=epj[j];
1.126 brouard 6802: }
6803:
1.128 brouard 6804: for(i=1, vepp=0.;i <=nlstate;i++)
6805: for(j=1;j <=nlstate;j++)
6806: vepp += vareij[i][j][(int)age];
6807: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6808: for(j=1;j <=nlstate;j++){
6809: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6810: }
6811: fprintf(ficrest,"\n");
1.126 brouard 6812: }
6813: }
6814: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6815: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6816: free_vector(epj,1,nlstate+1);
1.145 brouard 6817: /*}*/
1.126 brouard 6818: }
6819: free_vector(weight,1,n);
1.145 brouard 6820: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6821: free_imatrix(s,1,maxwav+1,1,n);
6822: free_matrix(anint,1,maxwav,1,n);
6823: free_matrix(mint,1,maxwav,1,n);
6824: free_ivector(cod,1,n);
6825: free_ivector(tab,1,NCOVMAX);
6826: fclose(ficresstdeij);
6827: fclose(ficrescveij);
6828: fclose(ficresvij);
6829: fclose(ficrest);
6830: fclose(ficpar);
6831:
6832: /*------- Variance of period (stable) prevalence------*/
6833:
6834: strcpy(fileresvpl,"vpl");
6835: strcat(fileresvpl,fileres);
6836: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6837: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6838: exit(0);
6839: }
6840: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6841:
1.145 brouard 6842: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6843: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6844:
6845: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6846: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6847: for(j=1;j<=cptcoveff;j++)
6848: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6849: fprintf(ficresvpl,"******\n");
6850:
6851: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6852: oldm=oldms;savm=savms;
6853: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6854: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6855: /*}*/
1.126 brouard 6856: }
6857:
6858: fclose(ficresvpl);
6859:
6860: /*---------- End : free ----------------*/
6861: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6862: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6863: } /* mle==-3 arrives here for freeing */
1.164 brouard 6864: /* endfree:*/
1.141 brouard 6865: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6866: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6867: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6868: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6869: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6870: free_matrix(covar,0,NCOVMAX,1,n);
6871: free_matrix(matcov,1,npar,1,npar);
6872: /*free_vector(delti,1,npar);*/
6873: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6874: free_matrix(agev,1,maxwav,1,imx);
6875: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6876:
1.145 brouard 6877: free_ivector(ncodemax,1,NCOVMAX);
6878: free_ivector(Tvar,1,NCOVMAX);
6879: free_ivector(Tprod,1,NCOVMAX);
6880: free_ivector(Tvaraff,1,NCOVMAX);
6881: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6882:
6883: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6884: free_imatrix(codtab,1,100,1,10);
6885: fflush(fichtm);
6886: fflush(ficgp);
6887:
6888:
6889: if((nberr >0) || (nbwarn>0)){
6890: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6891: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6892: }else{
6893: printf("End of Imach\n");
6894: fprintf(ficlog,"End of Imach\n");
6895: }
6896: printf("See log file on %s\n",filelog);
6897: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6898: /*(void) gettimeofday(&end_time,&tzp);*/
6899: rend_time = time(NULL);
6900: end_time = *localtime(&rend_time);
6901: /* tml = *localtime(&end_time.tm_sec); */
6902: strcpy(strtend,asctime(&end_time));
1.126 brouard 6903: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6904: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6905: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6906:
1.157 brouard 6907: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6908: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6909: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6910: /* printf("Total time was %d uSec.\n", total_usecs);*/
6911: /* if(fileappend(fichtm,optionfilehtm)){ */
6912: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6913: fclose(fichtm);
6914: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6915: fclose(fichtmcov);
6916: fclose(ficgp);
6917: fclose(ficlog);
6918: /*------ End -----------*/
6919:
6920:
6921: printf("Before Current directory %s!\n",pathcd);
6922: if(chdir(pathcd) != 0)
6923: printf("Can't move to directory %s!\n",path);
6924: if(getcwd(pathcd,MAXLINE) > 0)
6925: printf("Current directory %s!\n",pathcd);
6926: /*strcat(plotcmd,CHARSEPARATOR);*/
6927: sprintf(plotcmd,"gnuplot");
1.157 brouard 6928: #ifdef _WIN32
1.126 brouard 6929: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6930: #endif
6931: if(!stat(plotcmd,&info)){
1.158 brouard 6932: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6933: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6934: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6935: }else
6936: strcpy(pplotcmd,plotcmd);
1.157 brouard 6937: #ifdef __unix
1.126 brouard 6938: strcpy(plotcmd,GNUPLOTPROGRAM);
6939: if(!stat(plotcmd,&info)){
1.158 brouard 6940: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6941: }else
6942: strcpy(pplotcmd,plotcmd);
6943: #endif
6944: }else
6945: strcpy(pplotcmd,plotcmd);
6946:
6947: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6948: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6949:
6950: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6951: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6952: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6953: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6954: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6955: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6956: }
1.158 brouard 6957: printf(" Successful, please wait...");
1.126 brouard 6958: while (z[0] != 'q') {
6959: /* chdir(path); */
1.154 brouard 6960: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6961: scanf("%s",z);
6962: /* if (z[0] == 'c') system("./imach"); */
6963: if (z[0] == 'e') {
1.158 brouard 6964: #ifdef __APPLE__
1.152 brouard 6965: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6966: #elif __linux
6967: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6968: #else
1.152 brouard 6969: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6970: #endif
6971: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6972: system(pplotcmd);
1.126 brouard 6973: }
6974: else if (z[0] == 'g') system(plotcmd);
6975: else if (z[0] == 'q') exit(0);
6976: }
6977: end:
6978: while (z[0] != 'q') {
6979: printf("\nType q for exiting: ");
6980: scanf("%s",z);
6981: }
6982: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>